package com.cim.idm.service.Impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cim.idm.dao.CostCenterDao;
import com.cim.idm.data.ErpMessageLog;
import com.cim.idm.exception.GlobalException;
import com.cim.idm.framework.util.time.TimeStampUtil;
import com.cim.idm.model.CostCenter;
import com.cim.idm.model.po.MaterialReceiveRequest;
import com.cim.idm.model.vo.MaterialInfo;
import com.cim.idm.service.CostCenterService;
import com.cim.idm.service.impl.ToSAPServiceImpl;
import com.cim.idm.util.MessageLogUtil;
import com.cim.idm.util.ToSAPMessageUtil;
import com.cim.idm.wmspackage.materialpacking.management.data.MaterialPacking;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

@Service("CostCenterService")
@Slf4j
public class CostCenterServiceImpl implements CostCenterService {
    @Autowired
    private CostCenterDao costCenterDao;

    @Autowired
    private ToSAPServiceImpl toSAPService;

    @Override
    public List<CostCenter> getCostCenter(String erpFactory) {
        return costCenterDao.getCostCenter(erpFactory);
    }

    @Override
    public List<Map<String, Object>> getUserInfo() {
        return costCenterDao.getUserInfo();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateCareerAssistanceNew(JSONObject in) {
        MaterialReceiveRequest sl = JSON.toJavaObject(in, MaterialReceiveRequest.class);
        List<MaterialPacking> boxList = sl.getBoxList();
        String SALESHIPREQUESTNAME = sl.getSALESHIPREQUESTNAME();
        String SALESHIPREQUESTDETAILNAME = sl.getSALESHIPREQUESTDETAILNAME();
        String user = sl.getUser();
        String commitDate = sl.getCommitDate() != null ? sl.getCommitDate() : DateUtil.now();

        String siteName = sl.getSiteName();
        // 借用人
        String career_ASSISTANCE = sl.getRemark();
        // 审核主表id
        String id = UUID.randomUUID().toString();
        List<String> sapBoxList = new ArrayList<>();
        for (MaterialPacking materialPacking : boxList) {
            // 条码
            String materialPackingName = materialPacking.getMaterialPackingName();
            // 原销售订单号
            String saleshiprequestname = materialPacking.getSaleShipRequestName();
            // 原销售订单行号
            String saleShipRequestDetailName = materialPacking.getSaleShipRequestDetailName();
            // 物料编号
            String materialSpecName = materialPacking.getMaterialSpecName();
            // 批次号
            String charge = materialPacking.getCharge();
            // 阶段
            String phase = materialPacking.getPHASE();
            // 客户
            String customno = materialPacking.getCUSTOMNO();

            if(saleshiprequestname != null && saleshiprequestname.equals(SALESHIPREQUESTNAME)) {
                throw new GlobalException(SALESHIPREQUESTNAME + "销售订单号不能相等");
            }

            // 过账状态 移动类型
            String POSTSTATUS = "";
            if (StringUtils.isEmpty(saleshiprequestname) && StringUtils.isNotEmpty(SALESHIPREQUESTNAME)){
                POSTSTATUS = "413";//从非限制转E库存
            }
            else if (StringUtils.isNotEmpty(saleshiprequestname) && StringUtils.isEmpty(SALESHIPREQUESTNAME)){
                POSTSTATUS = "411E"; //从E库存转非限制
            }
            else if (StringUtils.isNotEmpty(saleshiprequestname) && StringUtils.isNotEmpty(SALESHIPREQUESTNAME) && !saleshiprequestname.equals(SALESHIPREQUESTNAME)){
                POSTSTATUS = "413E";  //从E库存转E库存
            }

            if (StringUtils.isEmpty(materialPacking.getCAREER_ASSISTANCE())
                    || materialPacking.getCAREER_ASSISTANCE().equals(career_ASSISTANCE)){
                // 更新
                costCenterDao.updatePacking(SALESHIPREQUESTNAME, SALESHIPREQUESTDETAILNAME,
                        POSTSTATUS, materialPackingName, saleshiprequestname, saleShipRequestDetailName);
                sapBoxList.add( materialPackingName);
            } else {
                // 新增
                costCenterDao.insertPackingChenk(SALESHIPREQUESTNAME, SALESHIPREQUESTDETAILNAME,
                        materialPackingName, siteName, materialSpecName, charge,phase,
                        customno, career_ASSISTANCE,POSTSTATUS, id, saleshiprequestname, saleShipRequestDetailName);
            }

        }
        String status = "";
        // 选中数据中的业助是否全部与借用人相同，相同是 true
        boolean exist = boxList.stream().allMatch(item -> career_ASSISTANCE.equals(item.getCAREER_ASSISTANCE()) ||
                StringUtils.isEmpty(item.getCAREER_ASSISTANCE()));
        if (exist) {
            status = "1"; // 完成
        } else {
            status = "0"; // 创建
        }
        // 新增审核主表
        costCenterDao.insertPackingChenkMain(id, status, career_ASSISTANCE,
                SALESHIPREQUESTNAME, SALESHIPREQUESTDETAILNAME);
        if(sapBoxList.size() > 0) {
            String undoId = toSAPService.careerAssistance(sapBoxList,siteName,user,SALESHIPREQUESTNAME,SALESHIPREQUESTDETAILNAME,commitDate);
        }


    }

    @Override
    public void updateCheckMain(String mainId) {
        costCenterDao.updateCheckMain(mainId);
    }

    @Override
    public void editMaterialPackingName(com.cim.idm.model.MaterialPacking materialPacking) {
        // 批次号
        String charge = materialPacking.getCharge();
        String siteName = materialPacking.getSiteName();
        String remark = materialPacking.getRemark();
        // 原标签
        String materialPackingName = materialPacking.getMaterialPackingName();
        String regex = "\\|\\|(.*?)\\|";
        // 新标签
        String materialPackingNameNew = materialPackingName.replaceAll(regex, "||" + charge + "|");
        costCenterDao.editMaterialPackingName(siteName,materialPackingName,charge,materialPackingNameNew,remark);
        //将log写到表里
        ErpMessageLog erplog = new ErpMessageLog();
        erplog.setEventUser(materialPacking.getUser());
        erplog.setServerName("WmsToWms");
        erplog.setEventName("在库属性变更");
        erplog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
        erplog.setMessageId(java.util.UUID.randomUUID().toString());
        erplog.setSendMsg(materialPacking.toString());
        erplog.setSendMsg2(materialPacking.toString());
        erplog.setReturnMsg2(materialPacking.toString());
        MessageLogUtil.writeMessageLog(erplog);
    }

    @Override
    public MaterialInfo getMaterialInfo(String materialSpecName) {
        return costCenterDao.getMaterialInfo(materialSpecName);
    }

    @Override
    public List<LinkedHashMap<String, Object>> getMaterialPacking(String materialSpecName, String siteName, String erpFactory, String erpLocation, String location, String nums) {
        return costCenterDao.getMaterialPacking(materialSpecName,siteName,erpFactory,
                erpLocation, location, nums);
    }

    @Override
    public List<HashMap<String, Object>> getByMaterialPackingName(String newBoxId) {
        return costCenterDao.getByMaterialPackingName(newBoxId);
    }

    @Override
    public void updateQty(String materialPackingName, BigDecimal materialQuantityFont, String user) {
        costCenterDao.updateQty(materialPackingName, materialQuantityFont, user);
    }
}
