/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.youchain.basicdata.rest;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.youchain.annotation.AnonymousAccess;
import com.youchain.annotation.Log;
import com.youchain.basicdata.domain.Area;
import com.youchain.basicdata.domain.BigItem;
import com.youchain.basicdata.domain.ItemLis;
import com.youchain.basicdata.repository.AreaRepository;
import com.youchain.basicdata.repository.BigItemRepository;
import com.youchain.basicdata.repository.ItemLisRepository;
import com.youchain.basicdata.service.ItemLisService;
import com.youchain.basicdata.service.dto.ItemLisQueryCriteria;
import com.youchain.config.FileProperties;
import com.youchain.exception.BadRequestException;
import com.youchain.exception.handler.ApiError;
import com.youchain.modules.system.domain.Dept;
import com.youchain.utils.FileUtil;
import com.youchain.utils.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Pageable;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;

/**
 * @author baobinglin
 * @website https://eladmin.vip
 * @date 2024-01-03
 **/
@Slf4j
@RestController
@RequiredArgsConstructor
@Api(tags = "itemLis管理")
@RequestMapping("/api/itemLis")
public class ItemLisController {

    private final ItemLisService itemLisService;
    private final FileProperties properties;
    private final BigItemRepository bigItemRepository;
    private final ItemLisRepository itemLisRepository;
    private final AreaRepository areaRepository;

    @PostMapping(value = "/import_data")
    @ApiOperation("导入完成品工位清单")
    @Transactional
    @AnonymousAccess
    @Log("导入完成品工位清单")
    public ResponseEntity<Object> createSysAppUpdate(@RequestParam("file") MultipartFile multipartFile) throws Exception {
        FileUtil.checkSize(properties.getMaxSize(), multipartFile.getSize());
        String suffix = FileUtil.getExtensionName(multipartFile.getOriginalFilename());
        String type = FileUtil.getFileType(suffix);
        File file = FileUtil.upload(multipartFile, properties.getPath().getPath() + type + File.separator);
        Dept dept = UserUtils.getDept();

        ExcelReader reader = ExcelUtil.getReader(file);
        List<Map<String, Object>> readAll = reader.readAll();
        int i = 0;//序号
        int edit_len = 0;
        int new_len = 0;
            Map<String, Long> map = new HashMap<String, Long>();//制造线，序号
            for (i = 0; i < readAll.size(); i++) {
                //完成品品番	完成品型式名	工位	出库类型	入库库区	备注
                String bigItemCode = readAll.get(i).get("完成品品番").toString().trim();
                String bigItemName = readAll.get(i).get("完成品型式名").toString().trim();
                String stationType = readAll.get(i).get("工位").toString().trim();
                String outType = readAll.get(i).get("出库类型").toString().trim();
                String rAreaCode = readAll.get(i).get("入库库区").toString().trim();
                String description = readAll.get(i).get("备注")==null?"":readAll.get(i).get("备注").toString().trim();

                //查询完成品番的id
                BigItem bigItem = bigItemRepository.findByCode(bigItemCode);
                if (bigItem==null) {
                    throw  new BadRequestException(bigItemCode + "不存在" + (i + 1));
                }
                //入库库区
                Area area = areaRepository.findByCodeOrName(rAreaCode,rAreaCode);
                if(area==null) {
                    throw  new BadRequestException(rAreaCode + "不存在" + (i + 1));
                }
                //查询是否已经存在
                Boolean isNew=Boolean.FALSE;
                ItemLis itemLis = itemLisRepository.findByBigItemIdStationType(bigItem.getId(), stationType);
                if (itemLis==null) {
                    itemLis = new ItemLis();
                    itemLis.setBigItem(bigItem);
                    itemLis.setStationType(stationType);
                    isNew=Boolean.TRUE;
                }
                //开始插入数据
                itemLis.setOutType(outType);
                itemLis.setRArea(area);
                itemLis.setDept(dept);
                itemLis.setDescription(description);
                if(isNew){
                    itemLisService.create(itemLis);
                }else{
                    itemLisService.update(itemLis);
                }
            }
        return new ResponseEntity<>("导入成功",HttpStatus.OK);
    }


    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @AnonymousAccess
    public void exportItemLis(HttpServletResponse response, ItemLisQueryCriteria criteria) throws Exception {
        itemLisService.download(itemLisService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询itemLis")
    @ApiOperation("查询itemLis")
    @AnonymousAccess
    public ResponseEntity<Object> queryItemLis(ItemLisQueryCriteria criteria, Pageable pageable) {
        return new ResponseEntity<>(itemLisService.queryAll(criteria, pageable), HttpStatus.OK);
    }

    @PostMapping
    @Log("新增itemLis")
    @ApiOperation("新增itemLis")
    @PreAuthorize("@el.check('super:man')")
    public ResponseEntity<Object> createItemLis(@Validated @RequestBody ItemLis resources) {
        //存入所属工位
        resources.setStationType(resources.getRArea().getWorkingStation());
        return new ResponseEntity<>(itemLisService.create(resources), HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改itemLis")
    @ApiOperation("修改itemLis")
    @PreAuthorize("@el.check('super:man')")
    public ResponseEntity<Object> updateItemLis(@Validated @RequestBody ItemLis resources) {
        itemLisService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping
    @Log("删除itemLis")
    @ApiOperation("删除itemLis")
    @PreAuthorize("@el.check('super:man')")
    public ResponseEntity<Object> deleteItemLis(@RequestBody Long[] ids) {
        itemLisService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}