package com.shkj.wms.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shkj.common.core.domain.Result;
import com.shkj.common.utils.DateUtils;
import com.shkj.common.utils.SecurityUtils;
import com.shkj.system.service.ISysParameterService;
import com.shkj.wms.bo.*;
import com.shkj.wms.constants.ParameterConstants;
import com.shkj.wms.domain.*;
import com.shkj.wms.enums.TaskStatusEnum;
import com.shkj.wms.enums.TaskTypeEnum;
import com.shkj.wms.mapper.BaseDeriveMapper;
import com.shkj.wms.mapper.BasePointDeviceMapper;
import com.shkj.wms.mapper.BusinDataTaskDetailMapper;
import com.shkj.wms.mapper.BusinDataTaskMapper;
import com.shkj.wms.service.*;
import com.shkj.wms.utils.TunnelTaskUtil;
import com.shkj.wms.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 任务管理Service业务层处理
 *
 * @author zjx
 * @date 2023-04-07
 */
@Slf4j
@Service
public class PutInOutStorageServiceImpl extends ServiceImpl<BasePointDeviceMapper,BasePointDevice > implements IPutInOutStorageService
{
    @Resource
    private BusinDataTaskMapper businDataTaskMapper;

    @Resource
    private BusinDataTaskDetailMapper businDataTaskDetailMapper;

    @Resource
    RedisTemplate redisTemplate;

    @Resource
    IBaseBarcodesInService iBaseBarcodesInService;


    @Resource
    IBusinDataTaskGoodsService iBusinDataTaskGoodsService;

    @Autowired
    private ISysParameterService sysParameterService;


    @Resource
    private  IBusinDataTaskService iBusinDataTaskService;



    @Resource
    private  ISysStockService iSysStockService;

    @Resource
    private  IBusinBillheadService iBusinBillheadService;

    @Resource
    IBusinBillbodyService iBusinBillbodyService;

    @Autowired
    BaseLocationServiceImpl baseLocationService;

    @Autowired
    IBaseBarcodesOutService iBaseBarcodesOutService;

    @Autowired
    ISysStockDetailService iSysStockDetailService;

    @Autowired
    ISysParameterService iSysParameterService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Long> saveBusinBillTaskData(MachineHandAddBo bo) {
        String firstBarcode = bo.getFirstBarcode();
        String secondBarcode = bo.getSecondBarcode();
        String thirdBarcode = bo.getThirdBarcode();
        Long containerCode = bo.getContainerCode();
        Long plcIP = bo.getPlcIP();
        BaseBarcodesIn barcodes_f =null;
        BaseBarcodesIn barcodes_s =null;
        BaseBarcodesIn barcodes_t =null;

        List<BaseBarcodesIn> barcodesIns = new ArrayList<>();
        if (!firstBarcode.equals("NG")) {
            barcodes_f = iBaseBarcodesInService.getBaseBarcodesByQrCode(firstBarcode);
            barcodes_f.setInStatus("1");
        }

        if (secondBarcode !=null && !secondBarcode.equals("NG")&&!secondBarcode.isEmpty()) {
            barcodes_s = iBaseBarcodesInService.getBaseBarcodesByQrCode(secondBarcode);
            barcodes_s.setInStatus("1");
        }

        if ( thirdBarcode !=null && !thirdBarcode.equals("NG")&&!secondBarcode.isEmpty()) {
            barcodes_t = iBaseBarcodesInService.getBaseBarcodesByQrCode(thirdBarcode);
            barcodes_t.setInStatus("1");
        }

        //需维修逻辑
        String isRepair_f ="0";
        String isRepair_s ="0";
        String isRepair_t ="0";
        //冲孔数据
        String isPunching_f="0";
        String isPunching_s="0";
        String isPunching_t="0";

        //冲孔结果数据
        String punchingResult_f="0";
        String punchingResult_s="0";
        String punchingResult_t="0";

        if(barcodes_f !=null){
            isRepair_f = barcodes_f.getIsRepair();
            isPunching_f = barcodes_f.getIsPunching();
            punchingResult_f = barcodes_f.getPunchingResult();
            barcodesIns.add(barcodes_f);
        }

        if(barcodes_s !=null){
            isRepair_s = barcodes_s.getIsRepair();
            isPunching_s = barcodes_s.getIsPunching();
            punchingResult_s = barcodes_s.getPunchingResult();
            barcodesIns.add(barcodes_s);
        }

        if(barcodes_t !=null){
            isRepair_t = barcodes_t.getIsRepair();
            isPunching_t = barcodes_t.getIsPunching();
            punchingResult_t = barcodes_t.getPunchingResult();
            barcodesIns.add(barcodes_t);
        }
        //获取下料点点位
        String taskCode = "T_" + DateUtils.dateTimeNow();
        String transId = com.shkj.common.utils.uuid.UUID.randomUUID().toString();
        BusinTaskAddBo businTaskAddBo =new BusinTaskAddBo();
        businTaskAddBo.setTaskCode(taskCode);
        businTaskAddBo.setPlcId(plcIP);
        businTaskAddBo.setTaskStatus(TaskStatusEnum.wait_put.getValue());
        businTaskAddBo.setCreateTime(DateUtils.getNowDate());
        businTaskAddBo.setBatch(DateUtils.getDate());
        businTaskAddBo.setTransId(transId);
        businTaskAddBo.setContainerId(containerCode);
        businTaskAddBo.setTaskPath(bo.getPointNO());

        //扫码异常 生成任务单，统一调度内容呼叫AGV
        if("NG".equals(firstBarcode) || "NG".equals(secondBarcode) || "NG".equals(thirdBarcode)){
            businTaskAddBo.setTaskType(TaskTypeEnum.scancode_err.getValue());
        }else  if ("1".equals(isRepair_f) || "1".equals(isRepair_s) || "1".equals(isRepair_t)) {
            businTaskAddBo.setTaskType(TaskTypeEnum.upkeep_err.getValue());
        }else if(("1".equals(isPunching_f)&& "0".equals(punchingResult_f))
                 || ("1".equals(isPunching_s)&& "0".equals(punchingResult_s))
                || ("1".equals(isPunching_t)&& "0".equals(punchingResult_t))){
            businTaskAddBo.setTaskType(TaskTypeEnum.putin_punching.getValue());
        }else {
            //正常业务，生成入库单及入库任务
            businTaskAddBo.setTaskType(bo.getTaskType());
        }
        //新增任务
        BusinDataTask businDataTask = BeanUtil.toBean(businTaskAddBo, BusinDataTask.class);
        iBusinDataTaskService.insertBusinDataTask(businDataTask);
        Long taskId=businDataTask.getId();
        //新增任务物料明细
        List<BusinDataTaskGoods> goods = new ArrayList<>();
        if (firstBarcode != "" && firstBarcode !=null){
            BusinDataTaskGoods firstGoods = new BusinDataTaskGoods();
            firstGoods.setQrCode(firstBarcode);
            firstGoods.setBranchId(SecurityUtils.getCurrentBranchId());
            firstGoods.setTaskCode(taskId);
            firstGoods.setCreateTime(DateUtils.getNowDate());
            if (!"NG".equals(firstBarcode)){
                firstGoods.setGoodsNo(barcodes_f.getGoodsNo());
                firstGoods.setIsPunching(barcodes_f.getIsPunching());
                firstGoods.setIsRepair(barcodes_f.getIsRepair());
            }
            goods.add(firstGoods);
        }

        if (secondBarcode != null && !secondBarcode.isEmpty()){
            BusinDataTaskGoods secondGoods = new BusinDataTaskGoods();
            secondGoods.setQrCode(secondBarcode);
            secondGoods.setBranchId(SecurityUtils.getCurrentBranchId());
            secondGoods.setTaskCode(taskId);
            secondGoods.setCreateTime(DateUtils.getNowDate());
            if (!"NG".equals(secondBarcode)){
                secondGoods.setGoodsNo(barcodes_s.getGoodsNo());
                secondGoods.setIsPunching(barcodes_s.getIsPunching());
                secondGoods.setIsRepair(barcodes_s.getIsRepair());
            }
            goods.add(secondGoods);
        }

        if (thirdBarcode != null && !secondBarcode.isEmpty()){
            BusinDataTaskGoods thirdGoods = new BusinDataTaskGoods();
            thirdGoods.setQrCode(secondBarcode);
            thirdGoods.setBranchId(SecurityUtils.getCurrentBranchId());
            thirdGoods.setTaskCode(taskId);
            thirdGoods.setCreateTime(DateUtils.getNowDate());
            if (!"NG".equals(thirdBarcode)) {
                thirdGoods.setGoodsNo(barcodes_t.getGoodsNo());
                thirdGoods.setIsPunching(barcodes_t.getIsPunching());
                thirdGoods.setIsRepair(barcodes_t.getIsRepair());
            }
            goods.add(thirdGoods);
        }
        //新增物料明细
        boolean b = iBusinDataTaskGoodsService.saveOrUpdateBatch(goods);
        //更新条码表的入库状态
        boolean b1 = iBaseBarcodesInService.saveOrUpdateBatch(barcodesIns);

        return Result.ok().data(taskId);
    }

    @Override
    public Result<Boolean> productDeposit(Long taskId) {
        BusinBillHeadBodyQueryBo bodyQueryBo =new BusinBillHeadBodyQueryBo();
        bodyQueryBo.setTaskId(taskId);
        //获取要入库的物料信息
        List<BusinBillHeadbodyInVo> bodyInOutDatas = iBusinBillheadService.getBillHeadBodyInOutData(bodyQueryBo);
        Long locationCode=0L;
        String batch="";
        Long containerCode=0L;
        Long storageCode=0L;
        int isPunching=0;
        int isRepair=0;
        List goods = new ArrayList();
        for (BusinBillHeadbodyInVo bodyInOutData : bodyInOutDatas) {
            locationCode = bodyInOutData.getLocationCode();
            storageCode = bodyInOutData.getStorageCode();
            batch = bodyInOutData.getBatch();
            isRepair += Integer.valueOf(bodyInOutData.getIsRepair());
            isPunching += Integer.valueOf(bodyInOutData.getIsPunching());
            containerCode = bodyInOutData.getContainerCode();
            Map goodsMap =new HashMap();
            goodsMap.put("goodsNo",bodyInOutData.getGoodsNo());
            goodsMap.put("qrCode",bodyInOutData.getQrCode());
            goods.add(goodsMap);
        }

        return iSysStockService.productDeposit(locationCode,containerCode,batch,String.valueOf(isPunching),goods,storageCode);
    }

    @Override
    public Result<String> exeTaskPutinStorage(BusinTaskExeBo bo) {
        //生成入库单
        int lindId = 0;
        String transCode = DateUtils.dateTime();

        List<BusinBillbody> bodyList = new ArrayList<>();
        BusinBillHeadAddBo billhead = null;
        List<BusinDataTaskGoodsVo> businDataTaskGoodsVos = bo.getBusinDataTaskGoodsVo();
        for (BusinDataTaskGoodsVo dataTaskGoodsVo : businDataTaskGoodsVos) {
            //查询物料是否已经入库
            BusinBillHeadBodyQueryBo queryBo = new BusinBillHeadBodyQueryBo();
            queryBo.setQrCode(dataTaskGoodsVo.getQrCode());
            BusinBillHeadVo businBillHeadVo = iBusinBillheadService.queryBillHeadAndBody(queryBo);
            if (businBillHeadVo != null) {
                // return Result.err().msg("此 " + firstBarcode + "条码已入库");
                //写日志进行监控
            }

            Long tqty = Long.valueOf(businDataTaskGoodsVos.size());

            //生成入库信息
            billhead = new BusinBillHeadAddBo();
            billhead.setTransId(transCode);
            //1入库 2出库 3退回
            billhead.setTransNo(bo.getTransNo());
            //1入库 -1 出库
            billhead.setTransQual(bo.getTransQual());
            billhead.setTqty(tqty);
            billhead.setContainerCode(bo.getContainerId());
            billhead.setTaskCode(bo.getTaskCode());
            billhead.setBatch(DateUtils.getDate());
            billhead.setBranchId(SecurityUtils.getCurrentBranchId());
            billhead.setAuditFlg("0");
            billhead.setContainerCode(bo.getContainerId());

            BusinBillhead businBillhead = BeanUtil.toBean(billhead, BusinBillhead.class);

            iBusinBillheadService.insertBusinBillhead(businBillhead);
            Long transId = businBillhead.getId();

            BaseLocationVo locationVo = bo.getBaseLocationVo();
            lindId += 1;
            BusinBillbody body = new BusinBillbody();
            body.setLineId(lindId);
            body.setGoodsNo(dataTaskGoodsVo.getGoodsNo());
            body.setQty(1);
            body.setTransId(transId);
            body.setTaskCode(bo.getTaskCode());
            body.setIsPunching(dataTaskGoodsVo.getIsPunching());
            body.setIsRepair(dataTaskGoodsVo.getIsRepair());
            body.setBranchCode(locationVo.getBranchId());
            body.setLocationCode(locationVo.getId());
            body.setStorageCode(locationVo.getStorageId());
            body.setAreaCode(locationVo.getAreaId());
            body.setQrCode(dataTaskGoodsVo.getQrCode());
            bodyList.add(body);
        }
        return iBusinBillbodyService.saveBatch(bodyList)? Result.ok(): Result.err();
    }

    @Override
    public Result<Boolean> saveBillTaskIn(BillTaskAddbo billTaskAddbo) {
        //获取人工下料点位
        String startPoint = billTaskAddbo.getStartPoint();
        if (startPoint==null){
            startPoint = iSysParameterService.selectConfigByKey(SecurityUtils.getCurrentBranchId(), ParameterConstants.ParameterSystem.blanking_point);
        }

        MachineHandAddBo mhaddbo = new MachineHandAddBo();
        mhaddbo.setTaskType(billTaskAddbo.getTaskType());
        mhaddbo.setPointNO(startPoint);
        mhaddbo.setContainerCode(billTaskAddbo.getContainerCode());
        List<BasinBarcodeInAddBo> barcodesList = billTaskAddbo.getBarcodesList();
        int i =0;
        for (BasinBarcodeInAddBo barcode : barcodesList) {
            i++;
            if (i ==1){
                mhaddbo.setFirstBarcode(barcode.getQrCode());
            }else if (i == 2){
                mhaddbo.setSecondBarcode(barcode.getQrCode());
            }
            else if (i == 3){
                mhaddbo.setThirdBarcode(barcode.getQrCode());
            }
        }
        this.saveBusinBillTaskData(mhaddbo);
        return Result.ok();
    }


}
