/*
 *  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.DuplicateSubmission.DuplicateSubmission;
import com.youchain.annotation.AnonymousAccess;
import com.youchain.annotation.Log;
import com.youchain.basicdata.domain.BigItem;
import com.youchain.basicdata.domain.ItemLis;
import com.youchain.basicdata.domain.ProductionPlan;
import com.youchain.basicdata.domain.ProductionPlanVo;
import com.youchain.basicdata.repository.ItemLisRepository;
import com.youchain.basicdata.repository.ProductionPlanRepository;
import com.youchain.basicdata.service.BigItemService;
import com.youchain.basicdata.service.ProductionPlanService;
import com.youchain.basicdata.service.dto.ProductionPlanQueryCriteria;
import com.youchain.businessdata.domain.Spareparts;
import com.youchain.businessdata.inputJson.buttenJson.ProductionPlanButton;
import com.youchain.businessdata.service.SparepartsService;
import com.youchain.config.FileProperties;
import com.youchain.exception.BadRequestException;
import com.youchain.exception.handler.ApiError;
import com.youchain.exception.handler.ApiResult;
import com.youchain.modules.system.domain.Dept;
import com.youchain.utils.*;
import com.youchain.utils.readFilebak.ReadUbuntuFiles;
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.io.InputStream;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;

/**
 * @author JiangKun
 * @website https://eladmin.vip
 * @date 2024-01-04
 **/
@Slf4j
@RestController
@RequiredArgsConstructor
@Api(tags = "productionPlan管理")
@RequestMapping("/api/productionPlan")
public class ProductionPlanController {

    private final ProductionPlanService productionPlanService;
    private final ProductionPlanRepository productionPlanRepository;
    private final BigItemService bigItemService;
    private final ItemLisRepository itemLisRepository;
    private final FileProperties properties;
    private final SparepartsService sparepartsService;
    private final ReadUbuntuFiles readUbuntuFiles;

    @PostMapping(value = "/import_data")
    @ApiOperation("导入生产顺序计划")
    @Log("导入生产顺序计划")
    @Transactional
    @AnonymousAccess
    public ResponseEntity<Object> createSysAppUpdate(@RequestParam("file") MultipartFile multipartFile)  {
        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;//序号
        Map<String, Long> map = new HashMap<String, Long>();//制造线，序号
        for (i = 0; i < readAll.size(); i++) {
            //No	工位	下线日期	IDNO	月度序号	机型	机型名称	国别	机号	备注
            String No = OptionalUtils.getTrimmedString(readAll.get(i),"No",null);
            String makeLine = OptionalUtils.getTrimmedString(readAll.get(i),"工位",null);
            String downlineDate = OptionalUtils.getTrimmedString(readAll.get(i),"下线日期",null);
            String IDNO = OptionalUtils.getTrimmedString(readAll.get(i),"IDNO",null);
            String monthlyNo = OptionalUtils.getTrimmedString(readAll.get(i),"月度序号",null);
            String bigItemCode =OptionalUtils.getTrimmedString(readAll.get(i),"机型",null);
            String machineNo =OptionalUtils.getTrimmedString(readAll.get(i),"机号",null);
            String description = OptionalUtils.getTrimmedString(readAll.get(i),"备注",null);
            String areaCode =OptionalUtils.getTrimmedString(readAll.get(i),"工位编码",null);
            String[] areaCodes=null;
            if(areaCode!=null){
                areaCodes=areaCode.split(",");
            }
            log.info(i+"==="+"idno:"+IDNO);
            Long orderNo =1L;
            List<ProductionPlan> idnoList = productionPlanRepository.findByIDNO(IDNO);
            if (!idnoList.isEmpty()) {
                orderNo = idnoList.get(0).getOrderNo();
            } else {
                orderNo = productionPlanRepository.getMaxOrderNo();
                if (orderNo==null) {
                    map.put(makeLine, 1L);
                }else{
                    orderNo=orderNo+1;
                }
            }
            //判断 status是否为consume状态的
            if(areaCode==null) {
                int hyCount = productionPlanRepository.existsHyIdno(makeLine,IDNO);
                if (hyCount > 0) {
                    throw new BadRequestException("大于" + IDNO + "存在已耗用数据");
                } else {
                    List<ProductionPlan> byMakeLineOrderNo = productionPlanRepository.findByIdnoList(makeLine,IDNO);
                    productionPlanRepository.deleteAll(byMakeLineOrderNo);
                }
            }else{
                int hyCount = productionPlanRepository.existsGwHyIdno(makeLine, IDNO,areaCodes);
                if (hyCount > 0) {
                    throw new BadRequestException( "大于" + IDNO + "存在已耗用数据");
                } else {
                    List<ProductionPlan> byMakeLineOrderNo = productionPlanRepository.findByGwIdnoList(makeLine,IDNO ,areaCodes);
                    productionPlanRepository.deleteAll(byMakeLineOrderNo);
                }
            }
            List<ItemLis> byBigItemList = itemLisRepository.findByBigItemCode(bigItemCode);
            if(areaCode!=null){
                byBigItemList = itemLisRepository.findByGwBigCode(bigItemCode,areaCodes);
            }
            if(byBigItemList.size()==0){
                throw new BadRequestException( bigItemCode + "未找到对应工位清单");
            }
            for (ItemLis itemlist : byBigItemList) {
                ProductionPlan productionPlan = new ProductionPlan();
                productionPlan.setBigItem(itemlist.getBigItem());
                productionPlan.setType(itemlist.getOutType());
                productionPlan.setWorkingStation(itemlist.getStationType());
                productionPlan.setPartVariety(itemlist.getBpType());
                productionPlan.setRkArea(itemlist.getRArea());
                productionPlan.setDept(dept);
                productionPlan.setDescription(description);
                productionPlan.setEnabled(itemlist.getEnabled());
                productionPlan.setNo(Integer.valueOf(No));
                productionPlan.setMakeLine(makeLine);
                productionPlan.setDownlineDate( new Timestamp(DateUtil.ymd_date(downlineDate).getTime()));
                productionPlan.setIdno(IDNO);
                productionPlan.setImportDate(new Timestamp (new Date ().getTime()));
                productionPlan.setMonthlyNo(monthlyNo);
                productionPlan.setMachineNo(machineNo);
                productionPlan.setStatue("UN_CONSUME");
                productionPlan.setOrderNo(orderNo);
                productionPlanRepository.save(productionPlan);

            }
        }
        return new ResponseEntity<>("导入成功",HttpStatus.OK);
    }


    @PutMapping(value = "/haoYong")
    @ApiOperation("批量耗用")
    @Log("批量耗用")
    @Transactional
    @PreAuthorize("@el.check('super:man')")
    @DuplicateSubmission(5)
    public ResponseEntity<Object> piLiangHaoYong( @RequestBody ProductionPlanVo productionPlanVo){
        List<ProductionPlan> productionPlans = productionPlanService.piLiangHaoYong(productionPlanVo);
        if(productionPlans == null || productionPlans.size() < productionPlanVo.getNumber()){
            throw new BadRequestException("未耗用机型不足台数，无法批量耗用");
        }
        //如果第一条不是选择记录，则错误
        boolean temp=false;
        for(ProductionPlan p:productionPlans){
            if(p.getId().equals(productionPlanVo.getId())){
                temp=true;
            }
            if(p.getStatue().equals(BizStatus.CONSUME)){
                throw new BadRequestException("不能重复耗用");
            }
        }
        if(!temp){
            throw new BadRequestException("不能重复耗用");
        }
        productionPlanService.scsxHaoyong(productionPlans,productionPlanVo.getAreaId(),"生产顺序计划耗用");
        return new ResponseEntity<>("耗用成功！",HttpStatus.OK);
    }

    @PutMapping(value = "/readHaoYongData")
    @ApiOperation("下线数据读取")
    @Log("下线数据读取")
    @Transactional
    @PreAuthorize("@el.check('super:man')")
    @DuplicateSubmission(5)
    public ResponseEntity<Object> readHaoYongData(){
        readUbuntuFiles.readFtp();
        return new ResponseEntity<>("耗用成功！",HttpStatus.OK);
    }

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

    @GetMapping
    @Log("查询productionPlan")
    @ApiOperation("查询productionPlan")
   @AnonymousAccess
    public ResponseEntity<Object> queryProductionPlan(ProductionPlanQueryCriteria criteria, Pageable pageable) {
        return new ResponseEntity<>(productionPlanService.queryAll(criteria, pageable), HttpStatus.OK);
    }

    @PostMapping
    @Log("新增productionPlan")
    @ApiOperation("新增productionPlan")
    @PreAuthorize("@el.check('super:man')")
    public ResponseEntity<Object> createProductionPlan(@Validated @RequestBody ProductionPlan resources) {
        return new ResponseEntity<>(productionPlanService.create(resources), HttpStatus.CREATED);
    }
    @PostMapping("/manualGeneration")
    @Log("生产顺序-手工生成")
    @ApiOperation("生产顺序-手工生成")
    @PreAuthorize("@el.check('super:man')")
    public ResponseEntity<Object> manualGeneration(@Validated @RequestBody ProductionPlanButton resources) {
        if (resources.getManualGeneration().getQuantity() == 0){
            throw new BadRequestException(HttpStatus.NOT_FOUND,  "数量不能为0");
        }
        ProductionPlan plan=resources.getManualGeneration().getProductionPlan();
        List<ProductionPlan> whyList = productionPlanRepository.getAllData(plan.getWorkingStation(), plan.getIdno());
        int num=resources.getManualGeneration().getQuantity();
        if(whyList.size()<num){
            throw  new BadRequestException("未耗用数只有"+whyList.size()+"不足"+num);
        }
        productionPlanService.manualGenerationSavePlanPick(whyList,num,"手工生产顺序计划生成",null,null,null);
        return new ResponseEntity<>("手工生成成功", HttpStatus.CREATED);
    }

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

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