package com.ximai.mes.pro.service.impl.productionSolution;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ximai.common.exception.ServiceException;
import com.ximai.common.utils.MessageUtils;
import com.ximai.common.utils.SecurityUtils;
import com.ximai.common.utils.data.DataUtil;
import com.ximai.common.utils.data.ExceptionUtil;
import com.ximai.common.utils.data.StringUtils;
import com.ximai.mes.md.domain.MdItem;
import com.ximai.mes.md.domain.MdWorkstation;
import com.ximai.mes.md.mapper.MdItemMapper;
import com.ximai.mes.md.mapper.MdWorkstationMapper;
import com.ximai.mes.pro.domain.ProProcess;
import com.ximai.mes.pro.domain.proWorkOrder.ProWorkorder;
import com.ximai.mes.pro.domain.productionSolution.*;
import com.ximai.mes.pro.domain.prototypeRequest.ProPrototypeRequestProcessQcindex;
import com.ximai.mes.pro.domain.vo.*;
import com.ximai.mes.pro.dto.productionSolution.ProProductionSolutionProcessDrawingCreate;
import com.ximai.mes.pro.dto.productionSolution.ProProductionSolutionProcessDrawingDto;
import com.ximai.mes.pro.dto.productionSolution.ProProductionSolutionProcessDrawingUpdate;
import com.ximai.mes.pro.mapper.ProProcessMapper;
import com.ximai.mes.pro.mapper.proWorkOrder.ProWorkorderMapper;
import com.ximai.mes.pro.mapper.productionSolution.*;
import com.ximai.mes.pro.service.productionSolution.IProProductionSolutionProcessDrawingService;
import com.ximai.mes.pro.service.productionSolution.IProProductionSolutionProcessQcindexService;
import com.ximai.mes.pro.service.productionSolution.IProProductionSolutionProcessToolService;
import com.ximai.mes.pro.service.productionSolution.IProProductionSolutionService;
import com.ximai.system.strategy.AutoCodeUtil;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 生产版本Service业务层处理
 *
 * @author zht
 * @date 2024-01-23
 */
@Service
public class ProProductionSolutionServiceImpl implements IProProductionSolutionService {
    @Autowired
    private ProProductionSolutionMapper proProductionSolutionMapper;

    @Autowired
    private ProProductionSolutionBomMapper proProductionSolutionBomMapper;

    @Autowired
    private ProProductionSolutionProcessMapper proProductionSolutionProcessMapper;

    @Autowired
    private ProProductionSolutionProcessItemMapper proProductionSolutionProcessItemMapper;

    @Autowired
    private ProProductionSolutionProcessToolMapper proProductionSolutionProcessToolMapper;

    @Autowired
    private ProProductionSolutionProcessQcindexMapper proProductionSolutionProcessQcindexMapper;

    @Autowired
    private IProProductionSolutionProcessToolService ProProductionSolutionProcessToolService;

    ;
    @Autowired
    private IProProductionSolutionProcessQcindexService proProductionSolutionProcessQcindexService;

    @Autowired
    private ProProductionSolutionBomHeadMapper proProductionSolutionBomHeadMapper;

    @Autowired
    private ProProductionSolutionBomItemMapper proProductionSolutionBomItemMapper;

    @Autowired
    private AutoCodeUtil autoCodeUtil;

    @Autowired
    private MdItemMapper mdItemMapper;

    @Autowired
    private ProProductionSolutionSpecificationSheetMapper proProductionSolutionSpecificationSheetMapper;

    @Autowired
    private MdWorkstationMapper mdWorkstationMapper;

    @Autowired
    private ProProcessMapper proProcessMapper;

    @Autowired
    private ProProductionSolutionServiceImpl proProductionSolutionService;
    @Autowired
    private IProProductionSolutionProcessDrawingService productionSolutionProcessDrawingService;

    @Autowired
    private ProWorkorderMapper proWorkorderMapper;
    /**
     * 查询生产版本
     *
     * @param productionSolutionId 生产版本主键
     * @return 生产版本
     */
    @Override
    public ProProductionSolutionVo selectProProductionSolutionByProductionSolutionId(Long productionSolutionId) {
        ProProductionSolution proProductionSolution = proProductionSolutionMapper.selectProProductionSolutionByProductionSolutionId(productionSolutionId);
        if(proProductionSolution==null){
            throw new ServiceException(MessageUtils.message("pro.workOrder.error.not.null.process.solution"));
        }
        // 根据id获取头表信息
        QueryWrapper<ProProductionSolutionBomHead> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.eq("production_solution_id", productionSolutionId);
        ProProductionSolutionBomHead proProductionSolutionBomHead = proProductionSolutionBomHeadMapper.selectOne(objectQueryWrapper);

        ProProductionSolutionBomHeadVo proProductionSolutionBomHeadVo = new ProProductionSolutionBomHeadVo();
        // 获取bom行表信息
        if (StringUtils.isNotNull(proProductionSolutionBomHead)) {
            BeanUtils.copyProperties(proProductionSolutionBomHead, proProductionSolutionBomHeadVo);
            QueryWrapper<ProProductionSolutionBomItem> proProductionSolutionBomItemQueryWrapper = new QueryWrapper<>();
            proProductionSolutionBomItemQueryWrapper.eq("bom_head_id", proProductionSolutionBomHead.getBomHeadId());
            List<ProProductionSolutionBomItem> proProductionSolutionBomItems = proProductionSolutionBomItemMapper.selectList(proProductionSolutionBomItemQueryWrapper);

            // 封装行信息
            proProductionSolutionBomHeadVo.setBomItemList(proProductionSolutionBomItems);
        }

        List<ProProductionSolutionProcessVo> processList = proProductionSolutionProcessMapper.selectProProductionSolutionProcessByProductionSolutionId(productionSolutionId);
        processList.forEach(s->{
            if(s.getSerial()==null){
                s.setSerial(1);
            }
        });
        processList.sort(Comparator.comparing(ProProductionSolutionProcessVo::getSerial));
        // 查询图纸
        Map<Long, List<ProProductionSolutionProcessDrawing>> drawingMap = productionSolutionProcessDrawingService.selectProProductionSolutionProcessDrawingList(new QueryWrapper<ProProductionSolutionProcessDrawing>().eq("production_solution_id", productionSolutionId))
                .stream().collect(Collectors.groupingBy(s->s.getProductionSolutionProcessId()));

        for (ProProductionSolutionProcessVo proProductionSolutionProcessVo : processList) {
            Long productionSolutionProcessId = proProductionSolutionProcessVo.getProductionSolutionProcessId();
            List<ProProductionSolutionProcessItem> processItemList = proProductionSolutionProcessItemMapper.selectProProductionSolutionProcessItemByProductionSolutionProcessId(productionSolutionProcessId);
            proProductionSolutionProcessVo.setProcessItemList(processItemList);
            proProductionSolutionProcessVo.setDrawingList(drawingMap.getOrDefault(productionSolutionProcessId, new ArrayList<>()));
        }
        ProProductionSolutionVo proProductionSolutionVo = proProductionSolution.deepCopyObj(ProProductionSolutionVo.class);

        //查询工装量具
        ProProductionSolutionProcessTool toolQuery = new ProProductionSolutionProcessTool();
        toolQuery.setPrototypeSolutionId(proProductionSolution.getProductionSolutionId());

        List<ProProductionSolutionProcessToolVo> toolList = ProProductionSolutionProcessToolService.selectProProductionSolutionProcessToolVoList(toolQuery);

        Map<Long, List<ProProductionSolutionProcessToolVo>> toolMap = toolList.stream().collect(Collectors.groupingBy(ProProductionSolutionProcessToolVo::getPrototypeSolutionProcessId));
        //查询检验项
        ProPrototypeRequestProcessQcindex qcindex = new ProPrototypeRequestProcessQcindex();
        toolQuery.setPrototypeSolutionId(proProductionSolution.getProductionSolutionId());
        List<ProProductionSolutionProcessQcindexVo> qcindexList = proProductionSolutionProcessQcindexService.selectProProductionSolutionProcessQcindexVoList(qcindex);
        Map<Long, List<ProProductionSolutionProcessQcindexVo>> qcindexMap = qcindexList.stream().collect(Collectors.groupingBy(ProProductionSolutionProcessQcindexVo::getPrototypeSolutionProcessId));
        for (ProProductionSolutionProcessVo proProductionSolutionProcess : processList) {
            proProductionSolutionProcess.setToolList(toolMap.getOrDefault(proProductionSolutionProcess.getProductionSolutionProcessId(), new ArrayList<>()));
            proProductionSolutionProcess.setQcindexList(qcindexMap.getOrDefault(proProductionSolutionProcess.getProductionSolutionProcessId(), new ArrayList<>()));

        }
        proProductionSolutionVo.setBomHead(proProductionSolutionBomHeadVo);
        proProductionSolutionVo.setProcessList(processList);

        return proProductionSolutionVo;
    }

    /**
     * 查询生产版本列表
     *
     * @param proProductionSolution 生产版本
     * @return 生产版本
     */
    @Override
    public List<ProProductionSolution> selectProProductionSolutionList(ProProductionSolution proProductionSolution) {
        return proProductionSolutionMapper.selectProProductionSolutionList(proProductionSolution);
    }

    /**
     * 新增生产版本
     *
     * @return 结果
     */
    @Override
    @Transactional
    public int insertProProductionSolution(ProProductionSolutionVo proProductionSolutionVo) {
        if (!StringUtils.isNotNull(proProductionSolutionVo)) {
            return 9;
        }
        ProProductionSolution proProductionSolution = new ProProductionSolution();
        BeanUtils.copyProperties(proProductionSolutionVo, proProductionSolution);
        // 数据转换

        String itemCode = proProductionSolutionVo.getItemCode();
        MdItem mdItem = null;
        if (StringUtils.isNotNull(itemCode)) {
            mdItem = mdItemMapper.selectMdItemByCodes(itemCode);
            ExceptionUtil.checkTrueThrowException(ObjectUtil.isEmpty(mdItem), MessageUtils.message("pro.material.error.not.exist"));
            if (ObjectUtil.isNotEmpty(mdItem)) {
                proProductionSolution.setItemId(mdItem.getItemId());
            }
        }

        if(StringUtils.isEmpty(proProductionSolutionVo.getProductionSolutionCode())){
            //不允许为空
            ExceptionUtil.checkTrueThrowException(true, MessageUtils.message("md.workStation.error.not.productionSolutionCode"));
        }else{
            if(mdItem != null){
                //判断编号是否未使用
                List<ProProductionSolution> proProductionSolutions = proProductionSolutionMapper.selectProductionSolutionCode(mdItem.getItemId(),proProductionSolutionVo.getProductionSolutionCode());
                ExceptionUtil.checkTrueThrowException(proProductionSolutions.size() > 0, MessageUtils.message("md.workStation.error.productionSolutionCode.unique"));
                //判断产品相关编号大小
                proProductionSolutions = proProductionSolutionMapper.selectProductionSolutionCode(mdItem.getItemId(),null);
                if(proProductionSolutions.size() > 0){
                    if(StringUtils.isNotEmpty(proProductionSolutions.get(0).getProductionSolutionCode())){
                        Long longOld = new Long(proProductionSolutions.get(0).getProductionSolutionCode());
                        Long longNew = new Long(proProductionSolutionVo.getProductionSolutionCode());
                        ExceptionUtil.checkTrueThrowException(longOld > longNew, MessageUtils.message("md.workStation.error.productionSolutionCode.size"));
                    }
                }
            }

        }

        // 保存主数据
        String createBy = SecurityUtils.getUsername();
        proProductionSolution.setCreateBy(createBy);
        proProductionSolution.setCreateTime(new Date());
        int i = proProductionSolutionMapper.insertProProductionSolution(proProductionSolution);
        if (i != 1) {
            return 2;
        }
        Long productionSolutionId = proProductionSolution.getProductionSolutionId();

        // 保存BOM信息
        // 保存头表
        ProProductionSolutionBomHeadVo bomHead = proProductionSolutionVo.getBomHead();
        if (StringUtils.isNotNull(bomHead)) {
            ProProductionSolutionBomHead proProductionSolutionBomHead = new ProProductionSolutionBomHead();
            BeanUtils.copyProperties(bomHead, proProductionSolutionBomHead);
            proProductionSolutionBomHead.setItemId(proProductionSolution.getItemId());
            proProductionSolutionBomHead.setProductionSolutionId(productionSolutionId);
            i = proProductionSolutionBomHeadMapper.insert(proProductionSolutionBomHead);
            if (i != 1) {
                return 2;
            }
            Long bomHeadId = proProductionSolutionBomHead.getBomHeadId();
            // 保存行表信息
            List<ProProductionSolutionBomItem> bomItemList = bomHead.getBomItemList();
            if (StringUtils.isNotNull(bomItemList)) {
                for (ProProductionSolutionBomItem proProductionSolutionBomItem : bomItemList) {
                    proProductionSolutionBomItem.setBomHeadId(bomHeadId);
                    // 查詢物料信息--獲取itemId
                    MdItem item = mdItemMapper.selectMdItemBySapItemCode(proProductionSolutionBomItem.getSapItemCode());
                    ExceptionUtil.checkTrueThrowException(Objects.isNull(item), MessageUtils.message("pro.material.error.not.exist"));
                    if (StringUtils.isNotNull(item)) {
                        proProductionSolutionBomItem.setItemId(item.getItemId());
                        i = proProductionSolutionBomItemMapper.insert(proProductionSolutionBomItem);
                        if (i != 1) {
                            return 2;
                        }
                    }

                }
            }
        }
        // 保存工序
        DecimalFormat df = new DecimalFormat("0000");
        List<ProProductionSolutionProcessVo> processList = proProductionSolutionVo.getProcessList();
        if (StringUtils.isNotNull(processList)) {
            int k=1;
            for (ProProductionSolutionProcessVo proProductionSolutionProcessVo : processList) {
                // 保存工序主表信息
                ProProductionSolutionProcess proProductionSolutionProcess = new ProProductionSolutionProcess();
                BeanUtils.copyProperties(proProductionSolutionProcessVo, proProductionSolutionProcess);
                String idx = df.format(k * 10);
                proProductionSolutionProcess.setIdx(idx);
                proProductionSolutionProcess.setSerial(k);
                if (proProductionSolutionProcessVo.getQuantity() == null) {
                    proProductionSolutionProcess.setQuantity(new BigDecimal("1"));
                }
                if (StringUtils.isEmpty(proProductionSolutionProcessVo.getUnitOfMeasure())) {
                    proProductionSolutionProcess.setUnitOfMeasure(proProductionSolutionVo.getUnitOfMeasure());
                }
                if (StringUtils.isEmpty(proProductionSolutionProcessVo.getStdWorkingTimeUom())) {
                    proProductionSolutionProcess.setStdWorkingTimeUom("MIN");
                }

                if (StringUtils.isNotNull(proProductionSolutionProcessVo.getEmployeesNum())) {
                    proProductionSolutionProcess.setEmployeesNum(1);
                }
                //判断工作中心是否为空
                ExceptionUtil.checkTrueThrowException(StringUtils.isNull(proProductionSolutionProcessVo.getWorkstationCode()), MessageUtils.message("md.workStation.error.not.exist"));
                //根据编码查看mes的工作中心
                MdWorkstation mdWorkstation = mdWorkstationMapper.selectMdWorkstationByWorkstationCodes(proProductionSolutionProcessVo.getWorkstationCode());
                if (ObjectUtil.isNotEmpty(mdWorkstation)) {
                    proProductionSolutionProcess.setWorkstationId(mdWorkstation.getWorkstationId());
                } else {
                    ExceptionUtil.checkTrueThrowException(true, MessageUtils.message("md.workStation.error.not.exist"));
                }
                //判断工序是否为空
                ExceptionUtil.checkTrueThrowException(StringUtils.isNull(proProductionSolutionProcessVo.getProcessCode()), MessageUtils.message("md.process.error.not.exist"));
                //根据查看mes的工序
                ProProcess proProcess = proProcessMapper.selectProProcessByProcessCodes(proProductionSolutionProcessVo.getProcessCode());
                if (ObjectUtil.isNotEmpty(proProcess)) {
                    proProductionSolutionProcess.setProcessId(proProcess.getProcessId());
                    proProductionSolutionProcess.setProcessName(proProcess.getProcessName());
                } else {
                    ExceptionUtil.checkTrueThrowException(true, MessageUtils.message("md.process.error.not.exist"));
                }

                proProductionSolutionProcess.setProductionSolutionId(productionSolutionId);
                i = proProductionSolutionProcessMapper.insertProProductionSolutionProcess(proProductionSolutionProcess);
                if (i != 1) {
                    return 2;
                }
                Long productionSolutionProcessId = proProductionSolutionProcess.getProductionSolutionProcessId();

                // 保存工序物料信息
                List<ProProductionSolutionProcessItem> processItemList = proProductionSolutionProcessVo.getProcessItemList();
                if (StringUtils.isNotNull(processItemList)) {
                    for (ProProductionSolutionProcessItem proProductionSolutionProcessItem : processItemList) {
                        proProductionSolutionProcessItem.setProductionSolutionProcessId(productionSolutionProcessId);
                        MdItem item = mdItemMapper.selectMdItemBySapItemCode(proProductionSolutionProcessItem.getSapItemCode());
                        ExceptionUtil.checkTrueThrowException(StringUtils.isNull(item), MessageUtils.message("pro.material.error.not.exist"));
                        if (StringUtils.isNotNull(item)) {
                            proProductionSolutionProcessItem.setItemId(item.getItemId());
                            proProductionSolutionProcessItem.setSapItemName(item.getItemName());
                            i = proProductionSolutionProcessItemMapper.insertProProductionSolutionProcessItem(proProductionSolutionProcessItem);
                            if (i != 1) {
                                return 2;
                            }
                        }

                    }
                }

                // 保存质检信息
                List<ProProductionSolutionProcessQcindexVo> qcindexList = proProductionSolutionProcessVo.getQcindexList();
                if (StringUtils.isNotNull(qcindexList)) {
                    for (ProProductionSolutionProcessQcindexVo proProductionSolutionProcessQcindexVo : qcindexList) {
                        ProProductionSolutionProcessQcindex proProductionSolutionProcessQcindex = new ProProductionSolutionProcessQcindex();
                        BeanUtils.copyProperties(proProductionSolutionProcessQcindexVo, proProductionSolutionProcessQcindex);
                        proProductionSolutionProcessQcindex.setPrototypeSolutionId(productionSolutionId);
                        proProductionSolutionProcessQcindex.setPrototypeSolutionProcessId(productionSolutionProcessId);
                        i = proProductionSolutionProcessQcindexMapper.insertProProductionSolutionProcessQcindex(proProductionSolutionProcessQcindex);
                        if (i != 1) {
                            return 2;
                        }
                    }
                }

                // 保存工装信息
                List<ProProductionSolutionProcessToolVo> toolList = proProductionSolutionProcessVo.getToolList();
                if (StringUtils.isNotNull(toolList)) {
                    for (ProProductionSolutionProcessToolVo proProductionSolutionProcessToolVo : toolList) {
                        ProProductionSolutionProcessTool proProductionSolutionProcessTool = new ProProductionSolutionProcessTool();
                        BeanUtils.copyProperties(proProductionSolutionProcessToolVo, proProductionSolutionProcessTool);
                        mdItem = mdItemMapper.selectMdItemByCodea(proProductionSolutionProcessToolVo.getItemCode());
                        proProductionSolutionProcessTool.setToolId(mdItem.getItemId());
                        proProductionSolutionProcessTool.setPrototypeSolutionId(productionSolutionId);
                        proProductionSolutionProcessTool.setPrototypeSolutionProcessId(productionSolutionProcessId);
                        BigDecimal normalData = DataUtil.getNormalData(proProductionSolutionProcessToolVo.getQuantity(), BigDecimal.ONE);
                        proProductionSolutionProcessTool.setQuantity(normalData.longValue());

                        i = proProductionSolutionProcessToolMapper.insertProProductionSolutionProcessTool(proProductionSolutionProcessTool);
                        if (i != 1) {
                            return 2;
                        }
                    }
                }
                //图纸保存
                List<ProProductionSolutionProcessDrawing> drawingCreateList = proProductionSolutionProcessVo.getDrawingList();
                drawingCreateList.forEach(s->{
                    ProProductionSolutionProcessDrawingCreate create = new ProProductionSolutionProcessDrawingCreate();
                    BeanUtil.copyProperties(s, create);
                    create.setProductionSolutionId(productionSolutionId);
                    create.setProductionSolutionProcessId(productionSolutionProcessId);
                    productionSolutionProcessDrawingService.insertProProductionSolutionProcessDrawing(create);
                });
                k++;
            }
        }


        return i;
    }


    /**
     * 修改生产版本
     * mes中修改只需要接收Ep信息就行-直接改
     *
     * @return 结果
     */
    @Transactional
    @Override
    public int updateProProductionSolution(ProProductionSolutionVo proProductionSolutionVo) {
        ProProductionSolution proProductionSolution = proProductionSolutionMapper.selectProProductionSolutionByProductionSolutionId(proProductionSolutionVo.getProductionSolutionId());
        proProductionSolution.setRemark(proProductionSolutionVo.getRemark());
        BeanUtils.copyProperties(proProductionSolutionVo, proProductionSolution);
        String createBy = SecurityUtils.getUsername();
        proProductionSolution.setUpdateBy(createBy);
        proProductionSolution.setUpdateTime(new Date());
        int i = proProductionSolutionMapper.updateProProductionSolution(proProductionSolution);

        // 获取打样工序
        List<ProProductionSolutionProcessVo> processList = proProductionSolutionVo.getProcessList();
        ProProductionSolutionProcess productionRequestProcess = new ProProductionSolutionProcess();
        productionRequestProcess.setProductionSolutionId(proProductionSolutionVo.getProductionSolutionId());
        List<ProProductionSolutionProcessVo> processListDb = proProductionSolutionProcessMapper.selectProProductionSolutionProcessList(productionRequestProcess);
        if(processList!=null){
            Map<Long,List<ProProductionSolutionProcessDrawing>> processDrawingMap = productionSolutionProcessDrawingService.selectProProductionSolutionProcessDrawingList(new QueryWrapper<ProProductionSolutionProcessDrawing>().eq("production_solution_id", proProductionSolutionVo.getProductionSolutionId()))
                    .stream().collect(Collectors.groupingBy(s->s.getProductionSolutionProcessId()));
            int k=1;
            DecimalFormat df = new DecimalFormat("0000");
            for (ProProductionSolutionProcessVo proProductionSolutionProcessVo : processList) {
                proProductionSolutionProcessVo.setProductionSolutionId(proProductionSolution.getProductionSolutionId());
                // 保存工序
                ProProductionSolutionProcess tempProcess = proProductionSolutionProcessVo.getProductionSolutionProcess(proProductionSolutionProcessVo);
                tempProcess.setSerial(k);
                String idx = df.format(k * 10);
                tempProcess.setIdx(idx);
                if(tempProcess.getProductionSolutionProcessId()==null) {
                    proProductionSolutionProcessMapper.insertProProductionSolutionProcess(tempProcess);
                }else{
                    proProductionSolutionProcessMapper.updateProProductionSolutionProcess(tempProcess);
                }
                Long prototypeRequestProcessId = tempProcess.getProductionSolutionProcessId();
                // 获取工序物料-保存
                List<ProProductionSolutionProcessItem> proProductionSolutionProcessItemList = proProductionSolutionProcessVo.getProcessItemList();
                ProProductionSolutionProcessItem proProductionSolutionProcessItemQuery = new ProProductionSolutionProcessItem();
                proProductionSolutionProcessItemQuery.setProductionSolutionProcessId(proProductionSolutionProcessVo.getProductionSolutionProcessId());
                List<ProProductionSolutionProcessItem> proProductionSolutionProcessItemListDb = proProductionSolutionProcessItemMapper.selectProProductionSolutionProcessItemList(proProductionSolutionProcessItemQuery);
                for (ProProductionSolutionProcessItem proProductionSolutionProcessItem : proProductionSolutionProcessItemList) {
                    proProductionSolutionProcessItem.setProductionSolutionProcessId(prototypeRequestProcessId);
                    if(proProductionSolutionProcessItem.getProductionSolutionProcessItemId()==null) {
                        proProductionSolutionProcessItemMapper.insertProProductionSolutionProcessItem(proProductionSolutionProcessItem);
                    }else{
                        proProductionSolutionProcessItemMapper.updateProProductionSolutionProcessItem(proProductionSolutionProcessItem);
                    }
                }
                proProductionSolutionProcessItemListDb.forEach(v->{
                    if(!proProductionSolutionProcessItemList.stream().filter(v2->{
                        return v.getProductionSolutionProcessItemId().equals(v2.getProductionSolutionProcessItemId());
                    }).findFirst().isPresent()){
                        proProductionSolutionProcessMapper.deleteProProductionSolutionProcessByProductionSolutionProcessId(v.getProductionSolutionProcessItemId());
                    };
                });

                //检验项保存、删除
                List<ProProductionSolutionProcessQcindexVo> proProductionSolutionProcessQcindexList = proProductionSolutionProcessVo.getQcindexList();
                ProProductionSolutionProcessQcindex proProductionSolutionProcessQcindexQuery = new ProProductionSolutionProcessQcindex();
                proProductionSolutionProcessQcindexQuery.setPrototypeSolutionProcessId(proProductionSolutionProcessVo.getProductionSolutionProcessId());
                List<ProProductionSolutionProcessQcindex> proProductionSolutionProcessQcindexListDb = proProductionSolutionProcessQcindexMapper.selectProProductionSolutionProcessQcindexList(proProductionSolutionProcessQcindexQuery);
                for (ProProductionSolutionProcessQcindexVo proProductionSolutionProcessQcindexVo : proProductionSolutionProcessQcindexList) {
                    ProProductionSolutionProcessQcindex proProductionSolutionProcessQcindex = new ProProductionSolutionProcessQcindex();
                    BeanUtil.copyProperties(proProductionSolutionProcessQcindexVo, proProductionSolutionProcessQcindex);
                    proProductionSolutionProcessQcindex.setPrototypeSolutionId(proProductionSolutionProcessVo.getProductionSolutionId());
                    proProductionSolutionProcessQcindex.setPrototypeSolutionProcessId(prototypeRequestProcessId);
                    if(proProductionSolutionProcessQcindex.getPrototypeSolutionProcessQcindexId()==null) {
                        proProductionSolutionProcessQcindexMapper.insertProProductionSolutionProcessQcindex(proProductionSolutionProcessQcindex);
                    }else{
                        proProductionSolutionProcessQcindexMapper.updateProProductionSolutionProcessQcindex(proProductionSolutionProcessQcindex);
                    }
                }
                proProductionSolutionProcessQcindexListDb.forEach(v->{
                    if(!proProductionSolutionProcessQcindexList.stream().filter(v2->{
                        return v.getPrototypeSolutionProcessQcindexId().equals(v2.getPrototypeSolutionProcessQcindexId());
                    }).findFirst().isPresent()){
                        proProductionSolutionProcessQcindexMapper.deleteProProductionSolutionProcessQcindexByPrototypeSolutionProcessQcindexId(v.getPrototypeSolutionProcessQcindexId());
                    };
                });
                //工装
                List<ProProductionSolutionProcessToolVo> proProductionSolutionProcessToolList = proProductionSolutionProcessVo.getToolList();
                ProProductionSolutionProcessTool proProductionSolutionProcessToolQuery = new ProProductionSolutionProcessTool();
                proProductionSolutionProcessToolQuery.setPrototypeSolutionProcessId(prototypeRequestProcessId);
                List<ProProductionSolutionProcessTool> proProductionSolutionProcessToolListDb = proProductionSolutionProcessToolMapper.selectProProductionSolutionProcessToolList(proProductionSolutionProcessToolQuery);
                for (ProProductionSolutionProcessToolVo proProductionSolutionProcessToolVo : proProductionSolutionProcessToolList) {
                    ProProductionSolutionProcessTool proProductionSolutionProcessTool = new ProProductionSolutionProcessTool();
                    BeanUtil.copyProperties(proProductionSolutionProcessToolVo, proProductionSolutionProcessTool);
                    proProductionSolutionProcessTool.setPrototypeSolutionProcessId(prototypeRequestProcessId);
                    proProductionSolutionProcessTool.setPrototypeSolutionId(proProductionSolutionProcessVo.getProductionSolutionId());
                    if(proProductionSolutionProcessTool.getPrototypeSolutionProcessToolId()==null) {
                        proProductionSolutionProcessToolMapper.insertProProductionSolutionProcessTool(proProductionSolutionProcessTool);
                    }else{
                        proProductionSolutionProcessToolMapper.updateProProductionSolutionProcessTool(proProductionSolutionProcessTool);
                    }
                }
                proProductionSolutionProcessToolListDb.forEach(v->{
                    if(!proProductionSolutionProcessToolList.stream().filter(v2->{
                        return v.getPrototypeSolutionProcessToolId().equals(v2.getPrototypeSolutionProcessToolId());
                    }).findFirst().isPresent()){
                        proProductionSolutionProcessToolMapper.deleteProProductionSolutionProcessToolByPrototypeSolutionProcessToolId(v.getPrototypeSolutionProcessToolId());
                    };
                });
                //图纸
                List<ProProductionSolutionProcessDrawing> drawingCreateList = proProductionSolutionProcessVo.getDrawingList();
                List<ProProductionSolutionProcessDrawing> drawingListDb = processDrawingMap.getOrDefault(prototypeRequestProcessId, new ArrayList<>());
                for (ProProductionSolutionProcessDrawing drawingTemp : drawingCreateList) {
                    drawingTemp.setProductionSolutionProcessId(prototypeRequestProcessId);
                    drawingTemp.setProductionSolutionId(proProductionSolutionProcessVo.getProductionSolutionId());
                    if(drawingTemp.getProductionSolutionProcessFileId()==null) {
                        ProProductionSolutionProcessDrawingCreate drawingCreate = new ProProductionSolutionProcessDrawingCreate();
                        BeanUtil.copyProperties(drawingTemp, drawingCreate);
                        productionSolutionProcessDrawingService.insertProProductionSolutionProcessDrawing(drawingCreate);
                    }else{
                        ProProductionSolutionProcessDrawingUpdate drawingUpdate = new ProProductionSolutionProcessDrawingUpdate();
                        BeanUtil.copyProperties(drawingTemp, drawingUpdate);
                        productionSolutionProcessDrawingService.updateProProductionSolutionProcessDrawing(drawingUpdate);
                    }
                }
                drawingListDb.forEach(v->{
                    if(!drawingCreateList.stream().filter(v2->{
                        return v.getProductionSolutionProcessFileId().equals(v2.getProductionSolutionProcessFileId());
                    }).findFirst().isPresent()){
                        productionSolutionProcessDrawingService.deleteProProductionSolutionProcessDrawingByProductionSolutionProcessFileId(v.getProductionSolutionProcessFileId());
                    };
                });
                k++;
            }
            processListDb.forEach(v->{
                Optional<ProProductionSolutionProcessVo> optionalProProductionSolutionProcessVo = processList.stream().filter(v2->{
                    return v.getProductionSolutionProcessId().equals(v2.getProductionSolutionProcessId());
                }).findFirst();
                if(!optionalProProductionSolutionProcessVo.isPresent()){
                    proProductionSolutionProcessMapper.deleteProProductionSolutionProcessByProductionSolutionProcessId(v.getProductionSolutionProcessId());
                };
            });
        }
        return 1;
    }

    public void deleteCheck(Long[] productionSolutionIds){
        for (Long productionSolutionId : productionSolutionIds){
            QueryWrapper<ProWorkorder> query = new QueryWrapper<>();
            query.eq("t1.production_solution_id",productionSolutionId);
            List<ProWorkorder>  proWorkorders = proWorkorderMapper.selectListByQw(query);
            ExceptionUtil.checkTrueThrowException(proWorkorders.size() > 0 , MessageUtils.message("delete.data.error.occupied"));
        }

    }

    /**
     * 批量删除生产版本
     *
     * @param productionSolutionIds 需要删除的生产版本主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteProProductionSolutionByProductionSolutionIds(Long[] productionSolutionIds) {
        deleteCheck(productionSolutionIds);
        if (StringUtils.isNotNull(productionSolutionIds)) {
            for (Long productionSolutionId : productionSolutionIds) {
                deleteProProductionSolutionByProductionSolutionId(productionSolutionId);
            }
        }
        return 1;
    }

    /**
     * 删除生产版本信息
     *
     * @param productionSolutionId 生产版本主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteProProductionSolutionByProductionSolutionId(Long productionSolutionId) {
        if (StringUtils.isNull(productionSolutionId)) {
            return 3;
        }
        ProProductionSolution proProductionSolution = proProductionSolutionMapper.selectProProductionSolutionByProductionSolutionId(productionSolutionId);
        int i = 1;
        if (StringUtils.isNotNull(proProductionSolution)) {
            i = proProductionSolutionMapper.deleteProProductionSolutionByProductionSolutionId(productionSolutionId);
            if (i != 1) {
                return 4;
            }
            // 删除BOM信息
            // 获取头表信息
            QueryWrapper<ProProductionSolutionBomHead> bomHeadQueryWrapper = new QueryWrapper<ProProductionSolutionBomHead>().eq("production_solution_id", productionSolutionId);
            ProProductionSolutionBomHead proProductionSolutionBomHead = proProductionSolutionBomHeadMapper.selectOne(bomHeadQueryWrapper);
            if (StringUtils.isNotNull(proProductionSolutionBomHead)) {
                Long bomHeadId = proProductionSolutionBomHead.getBomHeadId();
                // 获取行表信息
                QueryWrapper<ProProductionSolutionBomItem> bomItemQueryWrapper = new QueryWrapper<ProProductionSolutionBomItem>().eq("bom_head_id", bomHeadId);
                List<ProProductionSolutionBomItem> proProductionSolutionBomItems = proProductionSolutionBomItemMapper.selectList(bomItemQueryWrapper);
                if (StringUtils.isNotNull(proProductionSolutionBomItems)&&!proProductionSolutionBomItems.isEmpty()) {
                    List<Long> ids = proProductionSolutionBomItems.stream().map(ProProductionSolutionBomItem::getBomItemId).collect(Collectors.toList());
                    proProductionSolutionBomItemMapper.deleteBatchIds(ids);
                }
                i = proProductionSolutionBomHeadMapper.deleteById(bomHeadId);
                if (i != 1) {
                    return 4;
                }
            }
            // 删除工序信息
            ProProductionSolutionProcess proProductionSolutionProcess = new ProProductionSolutionProcess();
            proProductionSolutionProcess.setProductionSolutionId(productionSolutionId);
            List<ProProductionSolutionProcessVo> proProductionSolutionProcesses = proProductionSolutionProcessMapper.selectProProductionSolutionProcessList(proProductionSolutionProcess);
            if (StringUtils.isNotNull(proProductionSolutionProcesses)) {
                for (ProProductionSolutionProcessVo productionSolutionProcess : proProductionSolutionProcesses) {
                    Long productionSolutionProcessId = productionSolutionProcess.getProductionSolutionProcessId();
                    i = proProductionSolutionProcessMapper.deleteProProductionSolutionProcessByProductionSolutionProcessId(productionSolutionProcessId);
                    if (i != 1) {
                        return 4;
                    }
                    // 删除工序物料
                    List<ProProductionSolutionProcessItem> proProductionSolutionProcessItems = proProductionSolutionProcessItemMapper.selectProProductionSolutionProcessItemByProductionSolutionProcessId(productionSolutionProcessId);
                    if (StringUtils.isNotNull(proProductionSolutionProcessItems)) {
                        for (ProProductionSolutionProcessItem proProductionSolutionProcessItem : proProductionSolutionProcessItems) {
                            Long productionSolutionProcessItemId = proProductionSolutionProcessItem.getProductionSolutionProcessItemId();
                            i = proProductionSolutionProcessItemMapper.deleteProProductionSolutionProcessItemByProductionSolutionProcessItemId(productionSolutionProcessItemId);
                            if (i != 1) {
                                return 4;
                            }
                        }
                    }
                    // 删除工装
                    List<ProProductionSolutionProcessTool> proProductionSolutionProcessTools = proProductionSolutionProcessToolMapper.selectProProductionSolutionProcessToolByPrototypeSolutionProcessId(productionSolutionProcessId);
                    if (StringUtils.isNotNull(proProductionSolutionProcessTools)) {
                        for (ProProductionSolutionProcessTool proProductionSolutionProcessTool : proProductionSolutionProcessTools) {
                            Long prototypeSolutionProcessToolId = proProductionSolutionProcessTool.getPrototypeSolutionProcessToolId();
                            i = proProductionSolutionProcessToolMapper.deleteProProductionSolutionProcessToolByPrototypeSolutionProcessToolId(prototypeSolutionProcessToolId);
                            if (i != 1) {
                                return 4;
                            }
                        }
                    }
                    // 删除质检
                    List<ProProductionSolutionProcessQcindex> proProductionSolutionProcessQcindices = proProductionSolutionProcessQcindexMapper.selectProProductionSolutionProcessQcindexByPrototypeSolutionProcessId(productionSolutionProcessId);
                    if (StringUtils.isNotNull(proProductionSolutionProcessQcindices)) {
                        for (ProProductionSolutionProcessQcindex proProductionSolutionProcessQcindex : proProductionSolutionProcessQcindices) {
                            i = proProductionSolutionProcessQcindexMapper.deleteProProductionSolutionProcessQcindexByPrototypeSolutionProcessQcindexId(proProductionSolutionProcessQcindex.getPrototypeSolutionProcessQcindexId());
                            if (i != 1) {
                                return 4;
                            }
                        }
                    }
                    // 删除图纸
                    List<ProProductionSolutionProcessDrawing> proProductionSolutionProcessDrawings = productionSolutionProcessDrawingService.selectProProductionSolutionProcessDrawingList(new QueryWrapper<ProProductionSolutionProcessDrawing>().eq("production_solution_id", productionSolutionId));
                    if (!proProductionSolutionProcessDrawings.isEmpty()) {
                        Long[] ids = new Long[proProductionSolutionProcessDrawings.size()];
                        proProductionSolutionProcessDrawings.stream().map(s->s.getProductionSolutionProcessFileId()).collect(Collectors.toList()).toArray(ids);
                        productionSolutionProcessDrawingService.deleteProProductionSolutionProcessDrawingByProductionSolutionProcessFileIds(ids);
                    }
                }
            }

            // 删除规格书
            ProProductionSolutionSpecificationSheet proProductionSolutionSpecificationSheet = proProductionSolutionSpecificationSheetMapper.selectSpecificationSheetByProductionSolutionId(productionSolutionId);
            if(proProductionSolutionSpecificationSheet!=null){
                i = proProductionSolutionSpecificationSheetMapper.deleteProProductionSolutionSpecificationSheetBySpecificationSheetId(proProductionSolutionSpecificationSheet.getSpecificationSheetId());
                if (i != 1) {
                    return 4;
                }
            }
        }
        return i;
    }

    /**
     * 接收EP生产版本数据
     */
    @Override
    @Transactional
    public int productionSolutionCreate(ProProductionSolutionVo productionSolutionVo) {

        // 判断标识
        char updateLog = productionSolutionVo.getUpdateLog();
        ProProductionSolution proProductionSolution = new ProProductionSolution();
        BeanUtils.copyProperties(productionSolutionVo, proProductionSolution);
        int i;
        if (updateLog == 'I') {

            // 新增
            i = insertProProductionSolution(productionSolutionVo);
        } else if (updateLog == 'D') {
            // 删除
            i = deleteProProductionSolutionByProductionSolutionId(productionSolutionVo.getProductionSolutionId());
        } else {
            // 修改
            i = updateProProductionSolution(productionSolutionVo);
        }

        return i;

    }

    @Override
    public int submitProProductionSolution(ProProductionSolutionVo proProductionSolutionVo) {
        return 0;
    }

    /**
     * 转为生产版本
     */
    public int buildProductionSolution(Object object) {

        ProProductionSolutionVo proProductionSolutionVo = new ProProductionSolutionVo();
        BeanUtils.copyProperties(object, proProductionSolutionVo);
        return insertProProductionSolution(proProductionSolutionVo);
    }

    @Override
    public ProProductionSolution selectByGroupKeyAndGroupCounterAndSapItemCode(String groupKey, String groupCounter, String sapItemCode) {
        return proProductionSolutionMapper.selectByGroupKeyAndGroupCounterAndSapItemCode(groupKey, groupCounter, sapItemCode);
    }

}
