package com.yunfeiyun.agmp.fms.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import com.yunfeiyun.agmp.common.constant.ErrorCode;
import com.yunfeiyun.agmp.common.core.domain.AjaxResult;
import com.yunfeiyun.agmp.common.enums.*;
import com.yunfeiyun.agmp.common.utils.DateUtils;
import com.yunfeiyun.agmp.common.utils.DictUtils;
import com.yunfeiyun.agmp.common.utils.SecurityUtils;
import com.yunfeiyun.agmp.common.utils.StringUtils;
import com.yunfeiyun.agmp.common.utils.serialno.NoGenerator;
import com.yunfeiyun.agmp.common.utils.uuid.IdUtils;
import com.yunfeiyun.agmp.common.web.system.mapper.SysResMapper;
import com.yunfeiyun.agmp.fms.domain.*;
import com.yunfeiyun.agmp.fms.mapper.*;
import com.yunfeiyun.agmp.fms.domain.reqvo.AddAgmTaskPickReqVo;
import com.yunfeiyun.agmp.fms.domain.reqvo.AddMppTaskReqVo;
import com.yunfeiyun.agmp.fms.domain.resvo.WmsFinishgoodsStockResVo;
import com.yunfeiyun.agmp.fms.service.IMppTaskService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 农产品生产任务Service业务层处理
 * 
 * @author 杨晓辉
 * @date 2023-07-03
 */
@Service
public class MppTaskServiceImpl implements IMppTaskService
{
    @Autowired
    private MppTaskMapper mppTaskMapper;
    @Resource
    private WmsGoodsMapper wmsGoodsMapper;
    @Resource
    private WmsFinishgoodsMapper wmsFinishgoodsMapper;
    @Autowired
    private WmsStockMapper wmsStockMapper;
    @Resource
    private WmsChangeMapper wmsChangeMapper;
    @Resource
    private WmsChangeapplyMapper wmsChangeapplyMapper;
    @Resource
    private WmsChangeapplyitemMapper wmsChangeapplyitemMapper;
    @Resource
    private AgmTaskpickServiceImpl agmTaskpickServiceImpl;
    @Autowired
    private SysResMapper sysResMapper;
    @Autowired
    private MppMaterialMapper mppMaterialMapper;
    @Autowired
    private SysWarnMapper sysWarnMapper;
    @Autowired
    private MppQualitycheckMapper mppQualitycheckMapper;
    @Resource
    NoGenerator noGenerator;


    /**
     * 查询农产品生产任务
     * 
     * @param taskId 农产品生产任务主键
     * @return 农产品生产任务
     */
    @Override
    public MppTask selectMppTaskByTaskId(String taskId)
    {
        return mppTaskMapper.selectMppTaskByTaskId(taskId);
    }

    /**
     * 查询农产品生产任务列表
     * 
     * @param mppTask 农产品生产任务
     * @return 农产品生产任务
     */
    @Override
    public List<MppTask> selectMppTaskList(MppTask mppTask)
    {
        return mppTaskMapper.selectMppTaskList(mppTask);
    }

    /**
     * 新增农产品生产任务
     * 
     * @param reqVo 农产品生产任务
     * @return 结果
     */
    @Override
    public AjaxResult insertMppTask(AddMppTaskReqVo reqVo)
    {
        //生成任务
        MppTask mppTask = new MppTask();
        BeanUtils.copyProperties(reqVo, mppTask);
        mppTask.setTaskId(mppTask.getId());
        mppTask.setTaskNo(IdUtils.fastSimpleUUID());


        //生成原材料
        WmsFinishgoodsStockResVo wmsFinishgoodsStockResVo = new WmsFinishgoodsStockResVo();
        List<WmsStock> wmsStocks = new ArrayList<>();
        List<MppMaterial> mppMaterials = reqVo.getMppMaterials();
        for (MppMaterial material : mppMaterials) {
            material.setMaterialId(material.getId());
            material.setTaskId(mppTask.getTaskId());
            if ("1".equals(material.getMaterialStatus())) {
                wmsFinishgoodsStockResVo = wmsFinishgoodsMapper.selectWmsFinishgoodsStockResVoByStockId(material.getStockId());
            }
            //对原材料库存进行扣除
            WmsStock wmsStock = wmsStockMapper.selectWmsStockByStockId(material.getStockId());
            BigDecimal changeOldNum = wmsStock.getStockAmount();
            wmsStock.setStockAmount(wmsStock.getStockAmount().subtract(material.getMaterialCostnum()));
            if (wmsStock.getStockAmount().compareTo(new BigDecimal("0")) < 0) {
                return AjaxResult.error(ErrorCode.WMS_STOCK_NOT_ENOUGH.getCode(), ErrorCode.WMS_STOCK_NOT_ENOUGH.getMessage());
            }
            wmsStocks.add(wmsStock);

            // 保存变动申请
            WmsChangeapply wmsChangeapply1 = agmTaskpickServiceImpl.generateWmsChangeApply(ChangeBizType.LOSSES_APPLY.getCode());
            wmsChangeapplyMapper.insertWmsChangeapply(wmsChangeapply1);
            // 保存变动申请物件(原材料)
            WmsFinishgoodsStockResVo wmsFinishgoodsStockResVo1 = wmsFinishgoodsMapper.selectWmsFinishgoodsStockResVoByStockId(material.getStockId());
            WmsGoods wmsGoods = new WmsGoods();
            wmsGoods.setGoodsId(wmsFinishgoodsStockResVo1.getGoodsId());
            wmsGoods.setGoodsSpec(wmsFinishgoodsStockResVo1.getGoodsSpec());
            wmsGoods.setGoodsUnit(wmsFinishgoodsStockResVo1.getGoodsUnit());
            WmsFinishgoods wmsFinishgoods = new WmsFinishgoods();
            wmsFinishgoods.setFinishgoodsType(wmsFinishgoodsStockResVo1.getFinishgoodsType());
            AddAgmTaskPickReqVo addAgmTaskPickReqVo1 = new AddAgmTaskPickReqVo();
            BeanUtils.copyProperties(reqVo, addAgmTaskPickReqVo1);
            addAgmTaskPickReqVo1.setStockAmount(reqVo.getTaskdetailNum());
            WmsChangeapplyitem wmsChangeapplyitem1 = agmTaskpickServiceImpl.generateWmsChangeApplyItem(wmsGoods, wmsFinishgoods, wmsChangeapply1, addAgmTaskPickReqVo1);
            wmsChangeapplyitemMapper.insertWmsChangeapplyitem(wmsChangeapplyitem1);
            // 保存变动记录
            WmsChange wmsChange = generateWmsChange(wmsStock, wmsChangeapply1, ChangeWay.OUT.getCode(), material.getMaterialCostnum(), changeOldNum);
            wmsChangeMapper.insertWmsChange(wmsChange);

            //如果原材料未质检，生成预警
            generateSysWarn(material.getStockId(), reqVo.getTaskType());
        }
        mppMaterialMapper.insertMppMaterialBatch(mppMaterials);
        wmsStockMapper.updateWmsStockByBatch(wmsStocks);

        // 生成货物
        WmsGoods wmsGoods = new WmsGoods();
        wmsGoods.setGoodsName(DictUtils.getDictLabel("agm_mpp_product", reqVo.getProductValue()));
        wmsGoods.setGoodsUnit(reqVo.getGoodsUnit());
        wmsGoods.setGoodsId(wmsGoods.getId());
        wmsGoods.setGoodsSpec(reqVo.getGoodsSpec());
        // 保存
        wmsGoodsMapper.insertWmsGoods(wmsGoods);

        //生成农产品货物
        WmsFinishgoods wmsFinishgoods = new WmsFinishgoods();
        wmsFinishgoods.setFinishgoodsId(wmsFinishgoods.getId());
        wmsFinishgoods.setGoodsId(wmsGoods.getGoodsId());
        if (CommonEnums.TASK_TYPE_PROCESS.getCode().equals(reqVo.getTaskType())) {
            wmsFinishgoods.setFinishgoodNo(noGenerator.getProcessNo());
        } else if (CommonEnums.TASK_TYPE_PACKAGE.getCode().equals(reqVo.getTaskType())) {
            wmsFinishgoods.setFinishgoodNo(noGenerator.getPackNo());
        } else {
            return AjaxResult.error(ErrorCode.TASK_TYPE_ERROR.getCode(), ErrorCode.TASK_TYPE_ERROR.getMessage());
        }
        wmsFinishgoods.setFinishgoodPickno(wmsFinishgoodsStockResVo.getFinishgoodPickno());
        wmsFinishgoods.setFinishgoodCreateddate(DateUtils.dateTimeNow());
        wmsFinishgoods.setFinishgoodsType(reqVo.getTaskType());
        wmsFinishgoods.setFinishgoodscode(reqVo.getProductValue());
        wmsFinishgoods.setSourceinfoId(reqVo.getSourceinfoId());
        wmsFinishgoods.setFinishgoodsExpense(reqVo.getFinishgoodsExpense());
        wmsFinishgoodsMapper.insertWmsFinishgoods(wmsFinishgoods);

        // 生成库存
        WmsStock wmsStock = new WmsStock();
        wmsStock.setStockAmount(reqVo.getTaskdetailNum());
        wmsStock.setWarehouseId(reqVo.getWarehouseId());
        wmsStock.setStockId(wmsStock.getId());
        wmsStock.setGoodsId(wmsGoods.getGoodsId());
        // 保存
        wmsStockMapper.insertWmsStock(wmsStock);

        mppTask.setStockId(wmsStock.getStockId());
        mppTaskMapper.insertMppTask(mppTask);

        // 保存变动申请
        WmsChangeapply wmsChangeapply;
        if (CommonEnums.TASK_TYPE_PROCESS.getCode().equals(reqVo.getTaskType())) {
            wmsChangeapply = agmTaskpickServiceImpl.generateWmsChangeApply(ChangeBizType.PROCESS.getCode());
        } else if (CommonEnums.TASK_TYPE_PACKAGE.getCode().equals(reqVo.getTaskType())) {
            wmsChangeapply = agmTaskpickServiceImpl.generateWmsChangeApply(ChangeBizType.PARK.getCode());
        } else {
            return AjaxResult.error(ErrorCode.TASK_TYPE_ERROR.getCode(), ErrorCode.TASK_TYPE_ERROR.getMessage());
        }
        wmsChangeapplyMapper.insertWmsChangeapply(wmsChangeapply);

        // 保存变动申请物件
        AddAgmTaskPickReqVo addAgmTaskPickReqVo = new AddAgmTaskPickReqVo();
        BeanUtils.copyProperties(reqVo, addAgmTaskPickReqVo);
        addAgmTaskPickReqVo.setStockAmount(reqVo.getTaskdetailNum());
        WmsChangeapplyitem wmsChangeapplyitem = agmTaskpickServiceImpl.generateWmsChangeApplyItem(wmsGoods, wmsFinishgoods, wmsChangeapply, addAgmTaskPickReqVo);
        wmsChangeapplyitemMapper.insertWmsChangeapplyitem(wmsChangeapplyitem);


        // 保存变动记录
        WmsChange wmsChange = agmTaskpickServiceImpl.generateWmsChange(wmsStock, wmsChangeapply);
        wmsChangeMapper.insertWmsChange(wmsChange);

        //保存图片
        if (!StringUtils.isEmpty(reqVo.getProcessResIds())) {
            String[] quaResIds = reqVo.getProcessResIds().split(",");
            if (quaResIds.length > 0) {
                sysResMapper.updateSysResByResIdes(quaResIds, wmsFinishgoods.getFinishgoodsId());
            }
        }

        return AjaxResult.success();
    }

    public void generateSysWarn(String stockId, String type){
        WmsStock wmsStock = wmsStockMapper.selectWmsStockByStockId(stockId);
        WmsFinishgoods fg = new WmsFinishgoods();
        fg.setGoodsId(wmsStock.getGoodsId());
        List<WmsFinishgoods> wmsFinishgoods = wmsFinishgoodsMapper.selectWmsFinishgoodsList(fg);
        WmsFinishgoods finishgood = wmsFinishgoods.get(0);
        MppQualitycheck qc = new MppQualitycheck();
        qc.setFinishgoodsId(finishgood.getFinishgoodsId());
        List<MppQualitycheck> mppQualitychecks = mppQualitycheckMapper.selectMppQualitycheckList(qc);
        if (mppQualitychecks.size() == 0) {
            //记录预警信息
            SysWarn sysWarn = new SysWarn();
            sysWarn.setWarnId(sysWarn.getId());
            sysWarn.setWarnClass(SysWarnEnum.SysWarnClass.QUALITY_INSPECTION_PROCESS.getCode());
            sysWarn.setWarnType(SysWarnEnum.SysWarnType.UNQUALIFIED.getCode());
            String warnRamark = "";
            if (CommonEnums.FINISH_GOODS_TYPE_PROCESS.getCode().equals(type)) {
                warnRamark = "产品批次号为：" + finishgood.getFinishgoodNo() + " " +
                        DictUtils.getDictLabel(DictTypeEnums.AGM_MPP_PRODUCT.getCode(), finishgood.getFinishgoodscode())
                        + "未提交质检报告，流入到加工环节进行加工；";
            } else if (CommonEnums.FINISH_GOODS_TYPE_PACKAGE.getCode().equals(type)) {
                warnRamark = "产品批次号为：" + finishgood.getFinishgoodNo() + " " +
                        DictUtils.getDictLabel(DictTypeEnums.AGM_MPP_PRODUCT.getCode(), finishgood.getFinishgoodscode())
                        + "未提交质检报告，流入到包装环节进行包装；";
            }

            sysWarn.setWarnRemark(warnRamark);
            sysWarn.setWarnCreateddate(DateUtils.dateTimeNow());
            sysWarnMapper.insertSysWarn(sysWarn);
        }
    }


    /**
     * 修改农产品生产任务
     * 
     * @param mppTask 农产品生产任务
     * @return 结果
     */
    @Override
    public int updateMppTask(MppTask mppTask)
    {
        return mppTaskMapper.updateMppTask(mppTask);
    }

    /**
     * 批量删除农产品生产任务
     * 
     * @param taskIds 需要删除的农产品生产任务主键
     * @return 结果
     */
    @Override
    public int deleteMppTaskByTaskIds(String[] taskIds)
    {
        return mppTaskMapper.deleteMppTaskByTaskIds(taskIds);
    }

    /**
     * 删除农产品生产任务信息
     * 
     * @param taskId 农产品生产任务主键
     * @return 结果
     */
    @Override
    public int deleteMppTaskByTaskId(String taskId)
    {
        return mppTaskMapper.deleteMppTaskByTaskId(taskId);
    }

    public WmsChange generateWmsChange(WmsStock wmsStock, WmsChangeapply wmsChangeapply, String changeWay, BigDecimal changeNum, BigDecimal changeOldnum) {
        WmsChange wmsChange = new WmsChange();
        wmsChange.setChangeapplyId(wmsChangeapply.getChangeapplyId());
        wmsChange.setChangeId(wmsChange.getId());
        wmsChange.setStockId(wmsStock.getStockId());
        wmsChange.setChangeId(wmsChange.getId());
        wmsChange.setChangeBiztype(wmsChangeapply.getChangeapplyBiztype());
        wmsChange.setChangeWay(changeWay);
        wmsChange.setChangeNum(changeNum);
        wmsChange.setChangeOldnum(changeOldnum);
        wmsChange.setChangeNewnum(wmsStock.getStockAmount());
        wmsChange.setChangeAuditor(SecurityUtils.getUserId());
        wmsChange.setChangeAuditeddate(DateUtils.dateTimeNow());
//        wmsChange.setChangeRemark(reqVo.getChangeapplyRemark());
        return wmsChange;
    }
}
