/*
*  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.BigItem;
import com.youchain.basicdata.domain.Item;
import com.youchain.basicdata.domain.StockType;
import com.youchain.basicdata.repository.BigItemRepository;
import com.youchain.basicdata.repository.ItemRepository;
import com.youchain.basicdata.service.ImportDataService;
import com.youchain.basicdata.service.ItemService;
import com.youchain.basicdata.service.StockTypeService;
import com.youchain.basicdata.service.dto.BomAccountQueryCriteria;
import com.youchain.basicdata.service.dto.ItemDto;
import com.youchain.basicdata.service.dto.ItemQueryCriteria;
import com.youchain.businessdata.domain.Asn;
import com.youchain.businessdata.domain.PickDetail;
import com.youchain.businessdata.domain.PickTicket;
import com.youchain.businessdata.service.AsnService;
import com.youchain.businessdata.service.PickDetailService;
import com.youchain.businessdata.service.PickTicketService;
import com.youchain.businessdata.service.dto.AsnDto;
import com.youchain.config.FileProperties;
import com.youchain.exception.BadRequestException;
import com.youchain.exception.handler.ApiError;
import com.youchain.modules.system.domain.DictDetail;
import com.youchain.modules.system.service.DictDetailService;
import com.youchain.modules.system.service.dto.DictQueryCriteria;
import com.youchain.utils.BizStatus;
import com.youchain.utils.FileUtil;
import com.youchain.utils.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Pageable;
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 org.springframework.web.multipart.MultipartFile;

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


/**
* @website https://eladmin.vip
* @author houjianlan
* @date 2023-08-16
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "导入管理")
@Slf4j
@RequestMapping("/api/importData")
public class ImportDataController {
    private final FileProperties properties;
    private final ImportDataService importDataService;
    private final AsnService asnService;
    private final PickTicketService pickTicketService;
    private final PickDetailService pickDetailService;
    @Log("导入完成品品番")
    @ApiOperation("导入完成品品番")
    @PostMapping(value = "/bigItem")
    @Transactional
    @AnonymousAccess
    public ResponseEntity<Object> importBigItem( @RequestParam("file") MultipartFile multipartFile) {
        List<Map<String, Object>> readAll = getMaps(multipartFile);
        int a=0;//新增
        int b=0;//修改
        int c=0;//错误
        int d=0;//执行
        List<String> cList=new ArrayList<>();
        for (int i = 0; i < readAll.size(); i++) {
            String code =readAll.get(i).get("完成品品番")==null?null:readAll.get(i).get("完成品品番").toString();
            if(code==null||code.equals("")){
                break;
            }
            String re = importDataService.importBigItem(readAll.get(i));
        }
        return new ResponseEntity("导入成功",HttpStatus.OK);
    }
    @Log("导入部品品番")
    @ApiOperation("导入部品品番")
    @PostMapping(value = "/item")
    @AnonymousAccess
    public ResponseEntity<Object> importItem( @RequestParam("file") MultipartFile multipartFile) {
        try {
            String result = importDataService.importItem(multipartFile);
            return new ResponseEntity(result, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity("导入失败：" + e.getMessage(), HttpStatus.BAD_REQUEST);
        }
    }
    @Log("导入其他入库")
    @ApiOperation("导入其他入库")
    @PostMapping(value = "/importAsnDetail")
    @Transactional
    @AnonymousAccess
    public ResponseEntity<Object> importAsnDetail(@RequestParam Long asnId, @RequestParam("file") MultipartFile multipartFile) {
        List<Map<String, Object>> readAll = getMaps(multipartFile);
        List<String> cList=new ArrayList<>();
        Asn asn=asnService.getEntity(asnId);
        if(asn==null){
            throw new BadRequestException(HttpStatus.NOT_FOUND,  "该单据不存在");
        }
        if(!asn.getStatus().equals(BizStatus.OPEN))
        {
            throw new BadRequestException(HttpStatus.NOT_FOUND,  "该单据状态不正确");
        }
        for (int i = 0; i < readAll.size(); i++) {
            String re = importDataService.importAsnDetail(readAll.get(i),asn);
            if(re!=null&&!re.equals("")){
                throw new BadRequestException(HttpStatus.NOT_FOUND, (i+1)+"行"+re);
            }
        }
        return new ResponseEntity("导入成功", HttpStatus.OK);
    }
    @Log("导入其他出库")
    @ApiOperation("导入其他出库")
    @PostMapping(value = "/importPickDetail")
    @Transactional
    @AnonymousAccess
    public ResponseEntity<Object> importPickDetail(@RequestParam Long ptId, @RequestParam("file") MultipartFile multipartFile) {
        List<Map<String, Object>> readAll = getMaps(multipartFile);
        List<String> cList=new ArrayList<>();
        PickTicket pt=pickTicketService.getEntity(ptId);
        if(pt==null){
            throw new BadRequestException(HttpStatus.NOT_FOUND,  "该单据不存在");
        }
        if(!pt.getStatus().equals(BizStatus.OPEN)&&!pt.getStatus().equals(BizStatus.ALLOCATE))
        {
            throw new BadRequestException(HttpStatus.NOT_FOUND,  "该单据状态不正确");
        }
        for (int i = 0; i < readAll.size(); i++) {
            String re = importDataService.importPickDetail(readAll.get(i),pt);
            if(re!=null&&!re.equals("")){
                throw new BadRequestException(HttpStatus.NOT_FOUND, (i+1)+"行"+re);
            }
        }
        List<PickDetail> ds=pickDetailService.queryPickDetailList(pt.getId());
//        for(PickDetail d:ds) {
//            pickDetailService.allocate(d.getId(),d.getOrderQty());
//        }
        return new ResponseEntity("导入成功", HttpStatus.OK);
    }

    @Log("导入BOM工位清单")
    @ApiOperation("导入BOM工位清单")
    @PostMapping(value = "/bomAccount")
    @Transactional
    @AnonymousAccess
    public ResponseEntity<Object> importBomAccount( @RequestParam("file") MultipartFile multipartFile) {
        List<Map<String, Object>> readAll = getMaps(multipartFile);
        for (int i = 0; i < readAll.size(); i++) {
            importDataService.importBomAccount(i,readAll.get(i));
        }
        return new ResponseEntity("导入成功"+ readAll.size()+"行", HttpStatus.OK);
    }


    /**
     * 解析导入文件
     * @param multipartFile
     * @return
     */
    private List<Map<String, Object>> getMaps(MultipartFile multipartFile) {
        FileUtil.checkSize(properties.getMaxSize(), multipartFile.getSize());
        String suffix = FileUtil.getExtensionName(multipartFile.getOriginalFilename());
        String type = FileUtil.getFileType(suffix);
        log.error("--" + properties.getPath().getPath() + type + File.separator);
        File file = FileUtil.upload(multipartFile, properties.getPath().getPath() + type + File.separator);
        log.error("--" + file.getPath());
        ExcelReader reader = ExcelUtil.getReader(file);
        List<Map<String, Object>> readAll = reader.readAll();
        return readAll;
    }
}
