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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ximai.common.constant.UserConstants;
import com.ximai.common.utils.data.DateUtils;
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.mapper.ProRouteProcessMapper;
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.mapper.task.ProTaskWorkorderMapper;
import com.ximai.mes.pro.service.IProMaterialRequestService;
import com.ximai.mes.wm.domain.WmIssueHeader;
import com.ximai.mes.wm.domain.WmIssueLine;
import com.ximai.mes.wm.domain.tx.IssueTxBean;
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.mapper.WmIssueRecordMapper;
import com.ximai.mes.wm.service.IWmIssueHeaderService;
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 java.util.List;
import java.util.Objects;

/**
 * 生产领料单头Service业务层处理
 *
 * @date 2022-07-14
 */
@Service
public class WmIssueHeaderServiceImpl implements IWmIssueHeaderService {
    @Autowired
    private WmIssueHeaderMapper wmIssueHeaderMapper;

    @Autowired
    private WmIssueLineMapper wmIssueLineMapper;

    @Autowired
    private ProTaskWorkorderMapper proTaskWorkorderMapper;

    @Autowired
    private ProTaskMapper proTaskMapper;

    @Autowired
    private ProRouteProcessMapper proRouteProcessMapper;

    @Autowired
    private ProWorkorderMapper proWorkorderMapper;

    @Autowired
    private ProWorkOrderProcessMapper proWorkOrderProcessMapper;

    @Autowired
    private ProWorkOrderProcessItemMapper proWorkOrderProcessItemMapper;

    @Autowired
    private AutoCodeUtil autoCodeUtil;

    @Autowired
    private IWmIssueLineService wmIssueLineService;

    @Autowired
    private WmIssueRecordMapper wmIssueRecordMapper;

    @Autowired
    private IProMaterialRequestService proMaterialRequestService;

    @Autowired
    private MdItemMapper mdItemMapper;


    /**
     * 查询生产领料单头
     *
     * @param issueId 生产领料单头主键
     * @return 生产领料单头
     */
    @Override
    public WmIssueHeader selectWmIssueHeaderByIssueId(Long issueId) {
        return wmIssueHeaderMapper.selectWmIssueHeaderByIssueId(issueId);
    }

    /**
     * 查询生产领料单头列表
     *
     * @param wmIssueHeader 生产领料单头
     * @return 生产领料单头
     */
    @Override
    public List<WmIssueHeader> selectWmIssueHeaderList(WmIssueHeader wmIssueHeader) {
        return wmIssueHeaderMapper.selectWmIssueHeaderList(wmIssueHeader);
    }

    @Override
    public String checkIssueCodeUnique(WmIssueHeader wmIssueHeader) {
        WmIssueHeader header = wmIssueHeaderMapper.checkIssueCodeUnique(wmIssueHeader);
        Long headerId = wmIssueHeader.getIssueId() == null ? -1l : wmIssueHeader.getIssueId();
        if (StringUtils.isNotNull(header) && headerId.longValue() != header.getIssueId().longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 新增生产领料单头
     *
     * @param wmIssueHeader 生产领料单头
     * @return 结果
     */
    @Override
    public int insertWmIssueHeader(WmIssueHeader wmIssueHeader) {
        wmIssueHeader.createAction();
        return wmIssueHeaderMapper.insertWmIssueHeader(wmIssueHeader);
    }

    /**
     * 修改生产领料单头
     *
     * @param wmIssueHeader 生产领料单头
     * @return 结果
     */
    @Override
    public int updateWmIssueHeader(WmIssueHeader wmIssueHeader) {
        wmIssueHeader.updateAction();
        return wmIssueHeaderMapper.updateWmIssueHeader(wmIssueHeader);
    }

    /**
     * 批量删除生产领料单头
     *
     * @param issueIds 需要删除的生产领料单头主键
     * @return 结果
     */
    @Override
    public int deleteWmIssueHeaderByIssueIds(Long[] issueIds) {
        return wmIssueHeaderMapper.deleteWmIssueHeaderByIssueIds(issueIds);
    }

    /**
     * 删除生产领料单头信息
     *
     * @param issueId 生产领料单头主键
     * @return 结果
     */
    @Override
    public int deleteWmIssueHeaderByIssueId(Long issueId) {
        return wmIssueHeaderMapper.deleteWmIssueHeaderByIssueId(issueId);
    }

    @Override
    public List<IssueTxBean> getTxBeans(Long issueId) {
        return wmIssueHeaderMapper.getTxBeans(issueId);
    }

    /**
     * 排产自动生成领料单
     */
    @Override
    public void insertWmIssueHeaderByTaskId(Long taskId) {
        // 通用数据
//        Date nowDate = DateUtils.getNowDate();
//
//        // 查询任务单详细信息
//        ProTask proTask = proTaskMapper.selectProTaskByTaskId(taskId);
//        // 获取工序
//        Long processId = proTask.getProcessId();
//        Long routeId = proTask.getRouteId();
//
//        // 根据任务单id获取下属所有工单
//        ProTaskWorkorder proTaskWorkorder = new ProTaskWorkorder();
//        proTaskWorkorder.setTaskId(taskId);
//        List<ProTaskWorkorder> proTaskWorkorderList = proTaskWorkorderMapper.selectProTaskWorkorderList(proTaskWorkorder);
//
//        if (proTaskWorkorderList.size() == 0) {
//            return;
//        }
//        for (ProTaskWorkorder taskWorkorder : proTaskWorkorderList) {
//            Long workorderId = taskWorkorder.getWorkorderId(); // 工单id
//
//            // 获取工单主数据
//            ProWorkorder proWorkorder = proWorkorderMapper.selectProWorkorderByWorkorderId(workorderId);
//            if (!StringUtils.isNotNull(proWorkorder)) {
//                continue;
//            }
//
//            // 封装领料单头表
//            WmIssueHeader wmIssueHeader = new WmIssueHeader();
//            wmIssueHeader.setIssueCode(autoCodeUtil.genSerialCode(UserConstants.ISSUE_CODE, null)); // 领料单编码
//            wmIssueHeader.setTaskId(proTask.getTaskId());
//            wmIssueHeader.setWorkorderId(workorderId);
//            wmIssueHeader.setWorkstationId(proTask.getWorkstationId());
//            if (StringUtils.isNotNull(proWorkorder.getClientId())) {
//                wmIssueHeader.setClientId(proWorkorder.getClientId());
//            }
//            wmIssueHeader.setIssueDate(nowDate);
//            wmIssueHeader.setStatus(UserConstants.ORDER_STATUS_PREPARE);
//            wmIssueHeader.setCreateBy(getUsername());
//            wmIssueHeader.setCreateTime(nowDate);
//
//            // 查询工单工序下属所有工序物料
//            ProRouteProcess proRouteProcess = proRouteProcessMapper.selectProRouteProcessByRouteIdAndProcessId(routeId, processId);
//            if (!StringUtils.isNotNull(proRouteProcess)) {
//                continue;
//            }
//            Long recordId = proRouteProcess.getRecordId();
//            // 根据记录id查询工单工序表
//            ProWorkOrderProcessVo proWorkOrderProcess = proWorkOrderProcessMapper.selectProWorkOrderProcessByRecordId(workorderId, recordId);
//            if (!StringUtils.isNotNull(proWorkOrderProcess)) {
//                continue;
//            }
//
//            ProWorkOrderProcessItem proWorkOrderProcessItem = new ProWorkOrderProcessItem();
//            proWorkOrderProcessItem.setWorkorderProcessId(proWorkOrderProcess.getWorkorderProcessId());
//            List<ProWorkOrderProcessItem> proWorkOrderProcessItemList = proWorkOrderProcessItemMapper.selectProWorkOrderProcessItemList(proWorkOrderProcessItem);
//            if (proWorkOrderProcessItemList.size() == 0) {
//                continue;
//            }
//
//            // 保存头表
//            int i = wmIssueHeaderMapper.insertWmIssueHeader(wmIssueHeader);
//            Long issueId = wmIssueHeader.getIssueId(); // 获取返回的自增主键
//
//            for (ProWorkOrderProcessItem workOrderProcessItem : proWorkOrderProcessItemList) {
//
//                // 封装领料单
//                WmIssueLine wmIssueLine = new WmIssueLine();
//                wmIssueLine.setIssueId(issueId);
//                wmIssueLine.setItemId(workOrderProcessItem.getItemId());
//                wmIssueLine.setUnitOfMeasure(workOrderProcessItem.getUnitOfMeasure());
//                wmIssueLine.setQuantityIssued(workOrderProcessItem.getQuantity());
//                wmIssueLine.setCreateBy(getUsername());
//                wmIssueLine.setCreateTime(nowDate);
//
//                wmIssueLineMapper.insertWmIssueLine(wmIssueLine);
//
//            }
//
//            // 修改工单状态 -- 已生成领料单
//            proWorkorderMapper.updateWorkorderStatus(workorderId, UserConstants.ORDER_STATUS_ISSUEGENERATED);
//        }
//
//        proTaskMapper.updateProTaskStatus(taskId, UserConstants.ORDER_STATUS_ISSUEGENERATED);

    }

    /**
     * pad传mes领料单
     *
     * @param wmIssueVos
     */
    @Override
    public void sapCreateObj(List<WmIssueVo> wmIssueVos) {
        for (WmIssueVo wm : wmIssueVos) {
            WmIssueHeader issueHeader = wmIssueHeaderMapper.selectWmIssueHeaderCodes(wm.getIssueCode());
            if (Objects.isNull(issueHeader)) {
                //新增领料单头
                WmIssueHeader wmIssueHeader = wm.deepCopyObj(WmIssueHeader.class);
                wmIssueHeader.setIssueDate(DateUtils.getNowDate());
                insertWmIssueHeader(wmIssueHeader);
                WmIssueHeader wmIssueHeaders = wmIssueHeaderMapper.selectWmIssueHeaderCodes(wm.getIssueCode());
                //新增生产领料单行表，查看有没有存在数据，没有就新增
                addWmIssueLine(wm, wmIssueHeaders);
            } else {
                addWmIssueLine(wm, issueHeader);
            }
            //同步领料申请
            proMaterialRequestService.selectProMaterialRequestUpdateWindCaseGrantNum(wm);
        }
    }


    /**
     * pad传mes领料单
     *
     * @param wmIssueVos
     */
    @Override
    public void insertPadWmIssueHeader(List<WmIssueVo> wmIssueVos) {

        for (WmIssueVo wm : wmIssueVos) {
            WmIssueHeader wmIssueHeaders1 = wmIssueHeaderMapper.selectWmIssueHeaderCodes(wm.getIssueCode());

            if (Objects.isNull(wmIssueHeaders1)) {

                //新增领料单头
                WmIssueHeader wmIssueHeader = new WmIssueHeader();
                BeanUtils.copyProperties(wm, wmIssueHeader);
                wmIssueHeader.setIssueDate(DateUtils.getNowDate());
                insertWmIssueHeader(wmIssueHeader);
                WmIssueHeader wmIssueHeaders = wmIssueHeaderMapper.selectWmIssueHeaderCodes(wm.getIssueCode());
                WmIssueLine wmIssueLine = new WmIssueLine();
                wmIssueLine.setIssueId(wmIssueHeaders.getIssueId());
                List<WmIssueLine> wmIssueLines = wmIssueLineMapper.selectWmIssueLineList(wmIssueLine);
                if (CollUtil.isEmpty(wmIssueLines)) {
                    //新增生产领料单行表，查看有没有存在数据，没有就新增
                    addWmIssueLine(wm, wmIssueHeaders);

                }


            } else {
                boolean s = false;

                WmIssueLine wmIssues = new WmIssueLine();
                wmIssues.setIssueId(wmIssueHeaders1.getIssueId());
                List<WmIssueLine> wmIssueLines = wmIssueLineMapper.selectWmIssueLineList(wmIssues);
                //有生产领料单行表数据，就根据批次号进行修改
                for (WmIssueLine line : wmIssueLines) {
                    if (Objects.nonNull(line.getBatchCode())) {
                        if (line.getBatchCode().equals(wm.getBatchCode())) {
                            if (line.getItemCode().equals(wm.getSapItemCode())) {
                                if (line.getWorkorderCode().equals(wm.getWorkorderCode())) {
                                    WmIssueLine wmIssue = new WmIssueLine();
                                    BeanUtils.copyProperties(wm, wmIssue);
                                    wmIssue.setIssueId(wmIssueHeaders1.getIssueId());
                                    wmIssue.setLineId(line.getLineId());
                                    QueryWrapper<MdItem> queryWrapper = new QueryWrapper<>();
                                    queryWrapper.eq("sap_item_code", wmIssue.getSapItemCode());
                                    List<MdItem> mdItems = mdItemMapper.selectListByQw(queryWrapper);
                                    if (CollectionUtil.isNotEmpty(mdItems)) {
                                        MdItem mdItem = mdItems.get(0);
                                        wmIssue.setItemId(mdItem.getItemId());
                                    }
                                    wmIssue.setItemCode(wmIssue.getSapItemCode());
                                    wmIssueLineService.updateWmIssueLine(wmIssue);
                                    s = true;
                                }
                            }
                        }
                    }
                }
                //没有对应的批次号，就新增加
                if (s == false) {
                    addWmIssueLine(wm, wmIssueHeaders1);
                }


            }

            //同步领料申请
            proMaterialRequestService.selectProMaterialRequestUpdateWindCaseGrantNum(wm);


        }


    }


    private void addWmIssueLine(WmIssueVo wm, WmIssueHeader header) {
        WmIssueLine wmIssue = wm.deepCopyObj(WmIssueLine.class);
        wmIssue.setIssueId(header.getIssueId());

        QueryWrapper<MdItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sap_item_code", wmIssue.getSapItemCode());
        List<MdItem> mdItems = mdItemMapper.selectListByQw(queryWrapper);
        if (CollectionUtil.isNotEmpty(mdItems)) {
            MdItem mdItem = mdItems.get(0);
            wmIssue.setItemId(mdItem.getItemId());
        }

        MdItem mdItem = mdItemMapper.selectMdItemBySapItemCode(wm.getSapItemCode());
        if (StringUtils.isNotEmpty(mdItem.getSpecification())) {
            wmIssue.setSpecification(mdItem.getSpecification());
        }
        if (StringUtils.isNotEmpty(mdItem.getUnitOfMeasure())) {
            wmIssue.setUnitOfMeasure(mdItem.getUnitOfMeasure());
        }

        String plNum = wm.getPlNum();
        String substring = plNum.substring(10, 16);
        wmIssue.setPackNo(substring);
        wmIssue.setWarehouseName(wm.getWarehouseName());
        wmIssue.setItemCode(wmIssue.getSapItemCode());
        wmIssueLineService.insertWmIssueLine(wmIssue);
    }


}
