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

import cn.hutool.core.collection.CollUtil;
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.data.StringUtils;
import com.ximai.mes.md.domain.MdItem;
import com.ximai.mes.md.mapper.MdItemMapper;
import com.ximai.mes.pro.domain.ProMaterialReturn;
import com.ximai.mes.pro.domain.proWorkOrder.ProWorkOrderProcess;
import com.ximai.mes.pro.domain.proWorkOrder.ProWorkOrderProcessItem;
import com.ximai.mes.pro.domain.proWorkOrder.ProWorkorder;
import com.ximai.mes.pro.domain.task.ProTask;
import com.ximai.mes.pro.domain.vo.ProMaterialReturnVo;
import com.ximai.mes.pro.mapper.ProMaterialReturnMapper;
import com.ximai.mes.pro.mapper.proWorkOrder.ProWorkOrderProcessItemMapper;
import com.ximai.mes.pro.mapper.proWorkOrder.ProWorkOrderProcessMapper;
import com.ximai.mes.pro.mapper.proWorkOrder.ProWorkorderMapper;
import com.ximai.mes.pro.mapper.task.ProTaskMapper;
import com.ximai.mes.pro.service.IProMaterialReturnService;
import com.ximai.mes.pro.service.proWorkOrder.IProWorkOrderProcessItemService;
import com.ximai.mes.pro.service.proWorkOrder.IProWorkOrderProcessService;
import com.ximai.mes.wm.domain.WmIssueLine;
import com.ximai.mes.wm.domain.vo.WmIssueVo;
import com.ximai.mes.wm.mapper.WmIssueHeaderMapper;
import com.ximai.mes.wm.mapper.WmIssueLineMapper;
import com.ximai.mes.wm.service.IWmIssueLineService;
import com.ximai.system.strategy.AutoCodeUtil;
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.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 退料申请Service业务层处理
 *
 * @author generator
 * @date 2024-02-22
 */
@Service
public class ProMaterialReturnServiceImpl implements IProMaterialReturnService {

    @Autowired
    private ProMaterialReturnMapper proMaterialReturnMapper;

    @Autowired
    private AutoCodeUtil autoCodeUtil;

    @Autowired
    private IWmIssueLineService iWmIssueLineService;


    @Autowired
    private WmIssueLineMapper wmIssueLineMapper;

    @Autowired
    private WmIssueHeaderMapper wmIssueHeaderMapper;

    @Autowired
    private ProWorkorderMapper proWorkorderMapper;

    @Autowired
    private IProWorkOrderProcessService proWorkOrderProcessService;

    @Autowired
    private ProWorkOrderProcessMapper proWorkOrderProcessMapper;

    @Autowired
    private ProWorkOrderProcessItemMapper proWorkOrderProcessitemMapper;

    @Autowired
    private IProWorkOrderProcessItemService proWorkOrderProcessItemService;

    @Autowired
    private ProTaskMapper proTaskMapper;

    @Autowired
    private MdItemMapper mdItemMapper;

    /**
     * 查询退料申请
     *
     * @param materialReturnId 退料申请主键
     * @return 退料申请
     */
    @Override
    public ProMaterialReturn selectProMaterialReturnByMaterialReturnId(Long materialReturnId) {
        return proMaterialReturnMapper.selectProMaterialReturnByMaterialReturnId(materialReturnId);
    }

    /**
     * 查询退料申请列表
     *
     * @param proMaterialReturn 退料申请
     * @return 退料申请
     */
    @Override
    public List<ProMaterialReturn> selectProMaterialReturnList(ProMaterialReturn proMaterialReturn) {
        return proMaterialReturnMapper.selectProMaterialReturnList(proMaterialReturn);
    }

    /**
     * 新增退料申请
     *
     * @param proMaterialReturn 退料申请
     * @return 结果
     */
    @Override
    public int insertProMaterialReturn(ProMaterialReturn proMaterialReturn) {
        proMaterialReturn.createAction();
        return proMaterialReturnMapper.insertProMaterialReturn(proMaterialReturn);
    }

    @Override
    @Transactional
    public void insertProMaterialReturns(List<ProMaterialReturn> appendList) {
        for (ProMaterialReturn materialReturn : appendList) {
            if (StringUtils.isNull(materialReturn.getWorkorderCode())) {
                if (materialReturn.getBackNum() != null) {
                    QueryWrapper<ProMaterialReturn> itemQuest = new QueryWrapper<>();
                    itemQuest.eq("batch_no", materialReturn.getBatchNo());
                    itemQuest.eq("pack_no", materialReturn.getPackNo());
                    itemQuest.eq("item_id", materialReturn.getItemId());
                    List<ProMaterialReturn> tempLists = proMaterialReturnMapper.selectProMaterialReturnList2(itemQuest);
                    WmIssueLine wmIssueLine = iWmIssueLineService.selectWmIssueLineByLineId(materialReturn.getIssueLineId());
                    BigDecimal totalReturn = BigDecimal.ZERO;
                    for (ProMaterialReturn s : tempLists) {
                        totalReturn = totalReturn.add(s.getBackNum());
                    }

                    if (totalReturn.add(materialReturn.getBackNum()).compareTo(wmIssueLine.getQuantityIssued()) > 0) {
                        throw new ServiceException(MessageUtils.message("pro.return.material.error1", materialReturn.getBatchNo(), materialReturn.getPackNo()));
                    }

                    QueryWrapper<WmIssueLine> query = new QueryWrapper<>();
                    //根据物料id和批次号查了领料单行表
                    //query.eq("batch_code", materialReturn.getBatchNo());
                    query.eq("item_id", materialReturn.getItemId());
                    List<WmIssueLine> tempList = wmIssueLineMapper.selectListByQw(query);
                    List<WmIssueVo> wmIssueVos = new ArrayList<>();
                    if (CollUtil.isNotEmpty(tempList)) {
                        for (WmIssueLine tm : tempList) {
                            WmIssueVo wmIssueVo = new WmIssueVo();
                            BeanUtils.copyProperties(tm, wmIssueVo);
                            wmIssueVos.add(wmIssueVo);
                        }
                        //将相同工单的领料数量合并
                        ArrayList<WmIssueVo> wmIssueVos1 = new ArrayList<>();
                        for (WmIssueVo wmIssue : wmIssueVos) {
                            if (CollUtil.isEmpty(wmIssueVos1)) {
                                wmIssueVos1.add(wmIssue);
                            } else {
                                boolean a = false;
                                for (WmIssueVo wm : wmIssueVos1) {
                                    if (Objects.equals(wm.getWorkorderCode(), wmIssue.getWorkorderCode())) {
                                        BigDecimal add = wm.getQuantityIssued().add(wmIssue.getQuantityIssued());
                                        wm.setQuantityIssued(add);
                                        a = true;
                                    }
                                }
                                if (a == false) {
                                    wmIssueVos1.add(wmIssue);
                                }
                            }
                        }
                        //判断是否只有一个工单
                        if (wmIssueVos1.size() == 1) {
                            for (WmIssueVo wm : wmIssueVos1) {
                                //判断是否大于领料数量
                                //根据工单判断工序下bom物料的预留号和预留项目编号
                                ProWorkorder proWorkorder = proWorkorderMapper.selectProWorkorderWorderCode(wm.getWorkorderCode());
                                if (StringUtils.isNull(proWorkorder)) {
                                    continue;
                                }
                                //根据工单判断工序下bom物料的预留号和预留项目编号
                                ProTask proTask = proTaskMapper.selectProTaskByTaskId(materialReturn.getTaskId());
                                //查看工序id
                                QueryWrapper<ProWorkOrderProcess> queryProcess = new QueryWrapper<>();
                                queryProcess.eq("workorder_id", proWorkorder.getWorkorderId());
                                queryProcess.eq("process_id", proTask.getProcessId());
                                List<ProWorkOrderProcessItem> proWorkOrderProcessItems = proWorkOrderProcessMapper.selectProWorkOrderProcessOrWorkorder(queryProcess);
                                if (CollUtil.isNotEmpty((proWorkOrderProcessItems))) {
                                    for (ProWorkOrderProcessItem pro : proWorkOrderProcessItems) {
                                        if (Objects.equals(pro.getItemId(), materialReturn.getItemId())) {
                                            materialReturn.setRequirementNumber(pro.getRequirementNumber());
                                            materialReturn.setRequirementProjectNumber(pro.getRequirementProjectNumber());
                                        }
                                    }
                                }
                                materialReturn.setWorkorderCode(wm.getWorkorderCode());
                                materialReturn.setWindCase("N");
                                materialReturn.setApplyNo(materialReturn.getApplyNo());
                                this.insertProMaterialReturn(materialReturn);
                            }
                        } else {
                            //有多个工单
                            BigDecimal reduce = wmIssueVos1.stream()
                                    .map(WmIssueVo::getQuantityIssued)
                                    .reduce(BigDecimal.ZERO, BigDecimal::add);
                            BigDecimal result = materialReturn.getBackNum().divide(reduce, 5, RoundingMode.HALF_UP);
                            for (WmIssueVo wm : wmIssueVos1) {
                                BigDecimal multiply = wm.getQuantityIssued().multiply(result);
                                BigDecimal bigDecimal = multiply.setScale(4, RoundingMode.DOWN);


                                //根据工单判断工序下bom物料的预留号和预留项目编号
                                ProWorkorder proWorkorder = proWorkorderMapper.selectProWorkorderWorderCode(wm.getWorkorderCode());
                                if (StringUtils.isNull(proWorkorder)) {
                                    continue;
                                }

                                ProTask proTask = proTaskMapper.selectProTaskByTaskId(materialReturn.getTaskId());
                                //查看工序id
                                QueryWrapper<ProWorkOrderProcess> queryProcess = new QueryWrapper<>();
                                queryProcess.eq("workorder_id", proWorkorder.getWorkorderId());
                                queryProcess.eq("process_id", proTask.getProcessId());
                                List<ProWorkOrderProcessItem> proWorkOrderProcessItems = proWorkOrderProcessMapper.selectProWorkOrderProcessOrWorkorder(queryProcess);
                                if (CollUtil.isNotEmpty((proWorkOrderProcessItems))) {
                                    for (ProWorkOrderProcessItem pro : proWorkOrderProcessItems) {
                                        if (pro.getItemId().equals(materialReturn.getItemId())) {
                                            materialReturn.setRequirementNumber(pro.getRequirementNumber());
                                            materialReturn.setRequirementProjectNumber(pro.getRequirementProjectNumber());
                                        }
                                    }
                                }
                                //根据任务单号查询工单关联的对应工序
                                materialReturn.setBackNum(bigDecimal);
                                materialReturn.setWorkorderCode(wm.getWorkorderCode());
                                materialReturn.setWorkorderCode(wm.getWorkorderCode());
                                materialReturn.setWindCase("N");
                                materialReturn.setApplyNo(materialReturn.getApplyNo());
                                this.insertProMaterialReturn(materialReturn);

                            }
                        }
                    }
                }
            }else {
                if (materialReturn.getBackNum() != null) {
                    QueryWrapper<ProMaterialReturn> itemQuest = new QueryWrapper<>();
                    itemQuest.eq("batch_no", materialReturn.getBatchNo());
                    itemQuest.eq("pack_no", materialReturn.getPackNo());
                    itemQuest.eq("item_id", materialReturn.getItemId());
                    List<ProMaterialReturn> tempLists = proMaterialReturnMapper.selectProMaterialReturnList2(itemQuest);
                    WmIssueLine wmIssueLine = iWmIssueLineService.selectWmIssueLineByLineId(materialReturn.getIssueLineId());
                    BigDecimal totalReturn = BigDecimal.ZERO;
                    for (ProMaterialReturn s : tempLists) {
                        totalReturn = totalReturn.add(s.getBackNum());
                    }

                    if (totalReturn.add(materialReturn.getBackNum()).compareTo(wmIssueLine.getQuantityIssued()) > 0) {
                        throw new ServiceException(MessageUtils.message("pro.return.material.error1",materialReturn.getBatchNo(),materialReturn.getPackNo()));
                    }
                    ProWorkorder proWorkorder = proWorkorderMapper.selectProWorkorderWorderCode(materialReturn.getWorkorderCode());
                    if (StringUtils.isNull(proWorkorder)) {
                        continue;
                    }
                    //根据工单判断工序下bom物料的预留号和预留项目编号
                    ProTask proTask = proTaskMapper.selectProTaskByTaskId(materialReturn.getTaskId());
                    //查看工序id
                    QueryWrapper<ProWorkOrderProcess> queryProcess = new QueryWrapper<>();
                    queryProcess.eq("workorder_id", proWorkorder.getWorkorderId());
                    queryProcess.eq("process_id", proTask.getProcessId());
                    List<ProWorkOrderProcessItem> proWorkOrderProcessItems = proWorkOrderProcessMapper.selectProWorkOrderProcessOrWorkorder(queryProcess);
                    if (CollUtil.isNotEmpty((proWorkOrderProcessItems))) {
                        for (ProWorkOrderProcessItem pro : proWorkOrderProcessItems) {
                            if (Objects.equals(pro.getItemId(), materialReturn.getItemId())) {
                                materialReturn.setRequirementNumber(pro.getRequirementNumber());
                                materialReturn.setRequirementProjectNumber(pro.getRequirementProjectNumber());
                            }
                        }
                    }
                    materialReturn.setWindCase("N");
                    this.insertProMaterialReturn(materialReturn);
                }
            }


        }
    }

    /**
     * 修改退料申请
     *
     * @param proMaterialReturn 退料申请
     * @return 结果
     */
    @Override
    public int updateProMaterialReturn(ProMaterialReturn proMaterialReturn) {
        proMaterialReturn.updateAction();
        return proMaterialReturnMapper.updateProMaterialReturn(proMaterialReturn);
    }

    /**
     * 批量删除退料申请
     *
     * @param materialReturnIds 需要删除的退料申请主键
     * @return 结果
     */
    @Override
    public int deleteProMaterialReturnByMaterialReturnIds(Long[] materialReturnIds) {
        return proMaterialReturnMapper.deleteProMaterialReturnByMaterialReturnIds(materialReturnIds);
    }

    /**
     * 删除退料申请信息
     *
     * @param materialReturnId 退料申请主键
     * @return 结果
     */
    @Override
    public int deleteProMaterialReturnByMaterialReturnId(Long materialReturnId) {
        return proMaterialReturnMapper.deleteProMaterialReturnByMaterialReturnId(materialReturnId);
    }

    @Override
    public List<ProMaterialReturnVo> selectProMaterialReturnLis(QueryWrapper<ProMaterialReturn> query) {
        List<ProMaterialReturnVo> pro = proMaterialReturnMapper.selectProMaterialReturnList3(query);
        return pro;
    }


    @Override
    public void insertPdaProMaterialReturn(List<ProMaterialReturn> proMaterialReturns) {
        for (ProMaterialReturn pro : proMaterialReturns) {
            MdItem mdItem = mdItemMapper.selectMdItemBySapItemCode(pro.getSapItemCode());
            List<ProMaterialReturn> proMaterialReturns1 = proMaterialReturnMapper.selectProMaterialReturnByApplyNoOrWorkorder(pro.getApplyNo(), pro.getWorkorderCode());
            for (ProMaterialReturn proMaterialReturn : proMaterialReturns1) {
                if (proMaterialReturn.getItemId().equals(mdItem.getItemId())) {
                    if (StringUtils.isNull(proMaterialReturn.getReturnNum())) {
                        proMaterialReturn.setReturnNum(pro.getReturnNum());
                        proMaterialReturn.setWindCase(pro.getWindCase());
                        proMaterialReturn.setMaterialReturnId(proMaterialReturn.getMaterialReturnId());
                        proMaterialReturnMapper.updateProMaterialReturn(proMaterialReturn);
                    } else {
                        BigDecimal add = proMaterialReturn.getReturnNum().add(pro.getReturnNum());
                        proMaterialReturn.setReturnNum(add);
                        proMaterialReturn.setWindCase(pro.getWindCase());
                        proMaterialReturn.setMaterialReturnId(proMaterialReturn.getMaterialReturnId());
                        proMaterialReturnMapper.updateProMaterialReturn(proMaterialReturn);
                    }

                }
            }
        }
    }
}
