package com.malk.diwei.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.base.Strings;
import com.malk.diwei.entity.*;
import com.malk.diwei.mapper.*;
import com.malk.diwei.service.GoodsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.server.common.McR;
import com.malk.server.dingtalk.DDR_New;
import com.malk.service.aliwork.YDClient;
import com.malk.utils.UtilHttp;
import com.malk.utils.UtilList;
import com.malk.utils.UtilMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author WZY
 * @since 2025-03-12
 */
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {
    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private GoodsCategoryMapper goodsCategoryMapper;

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private GoodsUnitMapper goodsUnitMapper;

    @Autowired
    private UnitMapper unitMapper;

    @Autowired
    private GoodsColorMapper goodsColorMapper;

    @Autowired
    private ColorMapper colorMapper;

    @Autowired
    private GoodsSizeMapper goodsSizeMapper;

    @Autowired
    private SizeMapper sizeMapper;

    @Autowired
    private GoodsStockMapper goodsStockMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private BomMapper bomMapper;

    @Autowired
    private YDClient ydClient;

    public McR syncGoods() {
        //查询昨天修改的物料
        LambdaQueryWrapper<Goods> goodsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        goodsLambdaQueryWrapper.ge(Goods::getGoodsUpdateDatetime,"2025-03-12 00:00:00")
                .or()
                .ge(Goods::getGoodsCreateDatetime,"2025-03-12 00:00:00");
        //DateUtil.beginOfDay(DateUtil.yesterday())
        List<Goods> goods = goodsMapper.selectList(goodsLambdaQueryWrapper);

        for (Goods good : goods) {
            Map formData = new HashMap();
            formData.put("numberField_m85b219y",good.getGoodsID());//物料id
            formData.put("textField_m82g94gl",good.getGoodsCode());//货号
            formData.put("textField_m82g94gm",good.getGoodsName());//货品名称
            formData.put("textField_m82g94gn",good.getGoodsIngredients());//成分
            formData.put("textField_m82g94gt",good.getGoodsShortCode());//助记码
            formData.put("textField_m82g94gu",good.getGoodsAliasName());//货品别名
            formData.put("textField_m82g94gv",good.getGoodsSpecs());//货品规格
            formData.put("textField_m82g94h2",good.getGoodsShortName());//货品简称

            //货品类别
            LambdaQueryWrapper<GoodsCategory> goodsCategoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
            goodsCategoryLambdaQueryWrapper.eq(GoodsCategory::getGoodsCategoryID,good.getGoodsCategoryID());
            GoodsCategory goodsCategory = goodsCategoryMapper.selectOne(goodsCategoryLambdaQueryWrapper);
            if (Objects.nonNull(goodsCategory)){
                formData.put("textField_m82g94h3",goodsCategory.getGoodsCategoryName());
            }

            //货品属性
            if (Objects.nonNull(good.getGoodsProperty())){
                switch (good.getGoodsProperty()){
                    case 0 : formData.put("textField_m82g94h4","不限");break;
                    case 1 : formData.put("textField_m82g94h4","成品");break;
                    case 2 : formData.put("textField_m82g94h4","半成品");break;
                    case 3 : formData.put("textField_m82g94h4","原料");break;
                    case 4 : formData.put("textField_m82g94h4","辅料");break;
                    case 5 : formData.put("textField_m82g94h4","办公用品");break;
                    case 6 : formData.put("textField_m82g94h4","低值易耗品");break;
                    case 7 : formData.put("textField_m82g94h4","劳务/服务");break;
                    default : break;
                }
            }

            //品牌名称
            LambdaQueryWrapper<Brand> brandLambdaQueryWrapper = new LambdaQueryWrapper<>();
            brandLambdaQueryWrapper.eq(Brand::getBrandId,good.getBrandId());
            Brand brand = brandMapper.selectOne(brandLambdaQueryWrapper);
            if (Objects.nonNull(brand)){
                formData.put("textField_m82g94h9",brand.getBrandName());
            }

            formData.put("textField_m82g94ho",good.getGoodsNeedleType());//针型
            formData.put("textField_m82g94hp",good.getGoodsMachineType());//机型
            formData.put("numberField_m85b21a3",good.getGoodsGWeight());//克重

            //启用/停用
            if (Objects.nonNull(good.getGoodsDisable())){
                switch (good.getGoodsDisable()){
                    case 0 : formData.put("selectField_m82g94hh","启用");break;
                    case 1 : formData.put("selectField_m82g94hh","停用");break;
                    default : break;
                }
            }

            //库存预警
            if (Objects.nonNull(good.getGoodsCheckStatus())){
                switch (good.getGoodsCheckStatus()){
                    case 0 : formData.put("selectField_m82g94hv","关闭");break;
                    case 1 : formData.put("selectField_m82g94hv","开启");break;
                    default : break;
                }
            }

            formData.put("textareaField_m85b21a2",good.getGoodsDescription());//备注

            //单位名称
            LambdaQueryWrapper<GoodsUnit> goodsUnitLambdaQueryWrapper = new LambdaQueryWrapper<>();
            goodsUnitLambdaQueryWrapper.eq(GoodsUnit::getGoodsID,good.getGoodsID());
            GoodsUnit goodsUnit = goodsUnitMapper.selectOne(goodsUnitLambdaQueryWrapper);
            if (Objects.nonNull(goodsUnit)){
                LambdaQueryWrapper<Unit> unitLambdaQueryWrapper = new LambdaQueryWrapper<>();
                unitLambdaQueryWrapper.eq(Unit::getUnitID,goodsUnit.getUnitID());
                Unit unit = unitMapper.selectOne(unitLambdaQueryWrapper);
                if (Objects.nonNull(unit)){
                    formData.put("textField_m85b218v",unit.getUnitName());
                }
            }

            //颜色
            LambdaQueryWrapper<GoodsColor> goodsColorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            goodsColorLambdaQueryWrapper.eq(GoodsColor::getGoodsID,good.getGoodsID());
            List<GoodsColor> goodsColorList = goodsColorMapper.selectList(goodsColorLambdaQueryWrapper);
            if(Objects.nonNull(goodsColorList) && !goodsColorList.isEmpty()){
                List<Map> colorList = new ArrayList<>();
                for (GoodsColor goodsColor : goodsColorList) {
                    Map colorMap = new HashMap();

                    LambdaQueryWrapper<Color> colorLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    colorLambdaQueryWrapper.eq(Color::getColorID,goodsColor.getColorID());
                    Color color = colorMapper.selectOne(colorLambdaQueryWrapper);
                    if (Objects.nonNull(color)){
                        colorMap.put("numberField_m8o7fxr6",color.getColorID());
                        colorMap.put("textField_m85b219g",color.getColorName());
                    }
                    colorList.add(colorMap);
                }
                formData.put("tableField_m85b219h",colorList);
            }

            //尺码
            LambdaQueryWrapper<GoodsSize> goodsSizeLambdaQueryWrapper = new LambdaQueryWrapper<>();
            goodsSizeLambdaQueryWrapper.eq(GoodsSize::getGoodsID,good.getGoodsID());
            List<GoodsSize> goodsSizeList = goodsSizeMapper.selectList(goodsSizeLambdaQueryWrapper);
            if(Objects.nonNull(goodsSizeList) && !goodsSizeList.isEmpty()){
                List<Map> sizeList = new ArrayList<>();
                for (GoodsSize goodsSize : goodsSizeList) {
                    Map sizeMap = new HashMap();
                    LambdaQueryWrapper<Size> sizeLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    sizeLambdaQueryWrapper.eq(Size::getSizeID,goodsSize.getSizeID());
                    Size size = sizeMapper.selectOne(sizeLambdaQueryWrapper);
                    if (Objects.nonNull(size)){
                        sizeMap.put("numberField_m8o7fxr7",size.getSizeID());
                        sizeMap.put("textField_m85b219m",size.getSizeName());
                    }
                    sizeMap.put("textField_m85b219o",goodsSize.getGoodsSizeDes());//备注
                    sizeList.add(sizeMap);
                }
                formData.put("tableField_m85b219n",sizeList);
            }

            //精准匹配
            List<Map> searchCondition = new ArrayList<>();
            searchCondition.add(UtilMap.map("key, value, type, operator, componentName","textField_m82g94gl",good.getGoodsCode(),"TEXT","eq","TextField"));
            ydClient.operateData(YDParam.builder()
                    .formUuid("FORM-06568CCD028F45278F6D571FDD5B91A5X2FX")
                    .searchCondition(JSONObject.toJSONString(searchCondition))
                    .formDataJson(JSONObject.toJSONString(formData))
                    .build(), YDConf.FORM_OPERATION.upsert);

            //临时更新数据
            /*List<Map> data = (List<Map>) ydClient.queryData(YDParam.builder()
                    .formUuid("FORM-06568CCD028F45278F6D571FDD5B91A5X2FX")
                    .searchCondition(JSONObject.toJSONString(searchCondition))
                    .build(), YDConf.FORM_QUERY.retrieve_list).getData();

            if(Objects.nonNull(data) && !data.isEmpty()){
                String formInstId = data.get(0).get("formInstanceId").toString();
                ydClient.operateData(YDParam.builder()
                        .formInstId(formInstId)
                        .updateFormDataJson(JSONObject.toJSONString(formData))
                        .useLatestVersion(true)
                        .build(), YDConf.FORM_OPERATION.update);
            }*/


        }

        return McR.success();
    }

    @Override
    public McR queryGoodsStock(Integer goodsId, Integer colorId, Integer sizeId) {
        LambdaQueryWrapper<GoodsStock> goodsStockLambdaQueryWrapper = new LambdaQueryWrapper<>();
        goodsStockLambdaQueryWrapper.eq(GoodsStock::getGoodsID,goodsId)
                .eq(GoodsStock::getColorID,colorId)
                .eq(GoodsStock::getSizeID,sizeId);
        GoodsStock goodsStock = goodsStockMapper.selectOne(goodsStockLambdaQueryWrapper);
        if (Objects.nonNull(goodsStock)){
            BigDecimal goodsStockInQty = goodsStock.getGoodsStockInQty();
            return McR.success(goodsStockInQty);
        }else {
            return McR.success(-1);
        }
    }

    @Override
    public McR addBom(Map map) {
        if (Objects.isNull(map.get("formInstId"))){
            return McR.errorParam("实例id为空！");
        }
        String formInstId = map.get("formInstId").toString();

        Map formData = ydClient.queryData(YDParam.builder()
                .formInstId(formInstId)
                .build(), YDConf.FORM_QUERY.retrieve_id).getFormData();

        Map data = new HashMap();

        data.put("BomCode",formData.get("textField_m85ngbmt"));//单据编码
        data.put("BomGoodsCode",formData.get("textField_m913mbyz"));//款号
        data.put("BomProcessPrice",formData.get("numberField_m85ngbna"));//其他工费
        data.put("BomOtherFeePrice",formData.get("numberField_m85ngbnb"));//其他费用

        String creator = formData.get("textField_m913mbz1").toString();
        LambdaQueryWrapper<Employee> employeeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        employeeLambdaQueryWrapper.eq(Employee::getEmpName,creator)
                        .or().eq(Employee::getEmpGamUserID,creator);
        Employee employee = employeeMapper.selectOne(employeeLambdaQueryWrapper);
        if (Objects.nonNull(employee)){
            data.put("BomCreatEmp",creator);//制单人
        }else {
            data.put("BomCreatEmp","蒂维");//制单人
        }
        data.put("BomOrgName","总部");//组织机构
        data.put("BomDes",formData.get("textareaField_m85ngbnc"));//备注
        data.put("BomProofingRequirement",formData.get("textareaField_m85ngbne"));//工艺要求

        //获取所有子表明细（大于50条）
        //原料明细
        List<Map> materialDetails2 = getInnerTable("FORM-9A64B193700349F6A090D0D0D38A7F5CK8BG",formInstId,"tableField_m85ngbnd",1,50);
        //原料分码明细
        List<Map> materialDetails3 = getInnerTable("FORM-9A64B193700349F6A090D0D0D38A7F5CK8BG",formInstId,"tableField_m8cg47od",1,50);
        //辅料明细
        List<Map> sMaterialDetails2 = getInnerTable("FORM-9A64B193700349F6A090D0D0D38A7F5CK8BG",formInstId,"tableField_m8i5xg6k",1,50);
        //辅料分码明细
        List<Map> sMaterialDetails3 = getInnerTable("FORM-9A64B193700349F6A090D0D0D38A7F5CK8BG",formInstId,"tableField_m8ih0mhc",1,50);



        //原料明细
        List<Map> materialItems = new ArrayList<>();

        for (Map materialDetail : materialDetails2) {
            Map detail = new HashMap();

            if (Strings.isNullOrEmpty(materialDetail.get("textField_m8i5xg6m").toString())){
                continue;
            }

            String uuid = materialDetail.get("textField_m8cg47ol").toString();
            detail.put("GoodsPartsName",materialDetail.get("selectField_m88elwmx"));//部件
            detail.put("GoodsColorName",materialDetail.get("textField_m88elwlo"));//成品颜色
            detail.put("GoodsColorWay",materialDetail.get("textField_m85ngbni"));//色位

            boolean isSplit = false;
            if (materialDetail.get("radioField_m85ngbnp") != null && materialDetail.get("radioField_m85ngbnp").toString().equals("是")) {
                isSplit = true;
            }

            detail.put("GoodsColorIsSplitSize",isSplit);//分码
            detail.put("MaterialCode",materialDetail.get("textField_m8i5xg6m"));//原料货号
            detail.put("MaterialColorName",materialDetail.get("textField_m88elwmt"));//原料颜色
            detail.put("MaterialColorNo",materialDetail.get("textField_m85ngbnn"));//原料色号
            detail.put("MaterialDes",materialDetail.get("textareaField_m85ngbnu"));//明细备注

            //分码
            if (isSplit) {
                List<Map> collect2 = materialDetails3.stream().filter(item ->
                                item.get("textField_m8cg47of").toString().contains(uuid))
                        .collect(Collectors.toList());

                for (Map map1 : collect2) {
                    Map detail2 = new HashMap(detail);
                    detail2.put("GoodsSizeName",map1.get("textField_m8cg47og"));//成品尺码
                    detail2.put("MaterialQty",map1.get("numberField_m8cg47oh"));//需求数
                    detail2.put("MaterialLossRate",map1.get("numberField_m8cg47oi"));//损耗率
                    detail2.put("MaterialPrice",map1.get("numberField_m8cg47oj"));//成本单价
                    detail2.put("MaterialVendorName",map1.get("textField_m913mbza"));//供应商

                    materialItems.add(detail2);
                }
            }else {
                detail.put("MaterialQty",materialDetail.get("numberField_m85ngbnq"));//需求数
                detail.put("MaterialLossRate",materialDetail.get("numberField_m85ngbns"));//损耗率
                detail.put("MaterialPrice",materialDetail.get("numberField_m85ngbnr"));//成本单价
                detail.put("MaterialVendorName",materialDetail.get("textField_m913mbz6"));//供应商

                materialItems.add(detail);
            }

        }

        data.put("MaterialItems",materialItems);//原料明细

        //辅料明细
        List<Map> sMaterialItems = new ArrayList<>();

        for (Map sMaterialDetail : sMaterialDetails2) {
            Map detail = new HashMap();

            if (Strings.isNullOrEmpty(sMaterialDetail.get("textField_m8i5xg69").toString())){
                continue;
            }

            String uuid = sMaterialDetail.get("textField_m8i5xg65").toString();
            detail.put("GoodsColorName",sMaterialDetail.get("textField_m8i5xg66"));//成品颜色

            boolean isSplit = false;
            if (sMaterialDetail.get("radioField_m8i5xg6c") != null && sMaterialDetail.get("radioField_m8i5xg6c").toString().equals("是")) {
                isSplit = true;
            }

            detail.put("GoodsColorIsSplitSize",isSplit);//分码
            detail.put("SMaterialCode",sMaterialDetail.get("textField_m8i5xg69"));//辅料货号
            detail.put("SMaterialColorName",sMaterialDetail.get("selectField_m96or1zu"));//辅料颜色
            detail.put("SMaterialDes",sMaterialDetail.get("textareaField_m8i5xg6j"));//明细备注

            //分码
            if (isSplit) {
                List<Map> collect2 = sMaterialDetails3.stream().filter(item ->
                                item.get("textField_m8ih0mh5").toString().contains(uuid))
                        .collect(Collectors.toList());

                for (Map map1 : collect2) {
                    Map detail2 = new HashMap(detail);

                    detail2.put("GoodsSizeName",map1.get("textField_m8ih0mh6"));//成品尺码
                    detail2.put("SMaterialQty",map1.get("numberField_m8ih0mh7"));//需求数
                    detail2.put("SMaterialLossRate",map1.get("numberField_m8ih0mh8"));//损耗率
                    detail2.put("SMaterialPrice",map1.get("numberField_m8ih0mh9"));//成本单价
                    detail2.put("SMaterialVendorName",map1.get("textField_m913mbzc"));//供应商

                    sMaterialItems.add(detail2);
                }
            }else {
                detail.put("SMaterialQty",sMaterialDetail.get("numberField_m8i5xg6e"));//需求数
                detail.put("SMaterialLossRate",sMaterialDetail.get("numberField_m8i5xg6g"));//损耗率
                detail.put("SMaterialPrice",sMaterialDetail.get("numberField_m8i5xg6f"));//成本单价
                detail.put("SMaterialVendorName",sMaterialDetail.get("textField_m913mbzb"));//供应商

                sMaterialItems.add(detail);
            }
        }

        data.put("SMaterialItems",sMaterialItems);

        //工序明细
        List<Map> stepItems = new ArrayList<>();

        List<Map> stepItemList = (List<Map>) formData.get("tableField_m85ngbmz");
        if (Objects.nonNull(stepItemList)){
            for (Map stepItem : stepItemList) {
                Map map1 = new HashMap();
                map1.put("StepName",stepItem.get("textField_m85ngbn0"));//工序名称
                map1.put("StepUseTime",stepItem.get("numberField_m85ngbn2"));//单间耗时
                map1.put("StepPrice",stepItem.get("numberField_m85ngbn3"));//工序单价
                map1.put("StepDes",stepItem.get("textareaField_m85ngbn4"));//备注

                stepItems.add(map1);
            }
        }

        //工序为空时也需传
        data.put("StepItems",stepItems);//工序明细


        String s = UtilHttp.doPost("http://47.98.200.166/EpiErp5_DiWei_2023/rest/SyncBom_DW", null, null, data);

        System.out.println(s);
        String[] jsonParts = s.split("(?<=})"); // 按 } 分割

        for (String jsonPart : jsonParts) {
            Map parse = (Map) JSONObject.parse(jsonPart);
            if(Objects.nonNull(parse.get("errcode"))){
                if (!parse.get("errcode").toString().equals("0")){
                    return McR.errorUnknown("新增失败！失败原因："+parse.get("errmsg").toString());
                }
            }
        }

        return McR.success();
    }

    @Override
    public McR queryGoodsNewBom(int goodsId) {
        LambdaQueryWrapper<Bom> bomLambdaQueryWrapper = new LambdaQueryWrapper<>();
        bomLambdaQueryWrapper.eq(Bom::getGoodsID,goodsId)
                        .orderByDesc(Bom::getBomID);



        List<Bom> bomList = bomMapper.selectList(bomLambdaQueryWrapper);

        if (Objects.nonNull(bomList) && !bomList.isEmpty()){
            return McR.success("当前货号存在最新启用BOM:"+bomList.get(0).getBomCode());
        }else {
            return McR.success("未查询到BOM信息!");
        }
    }

    @Override
    public McR queryBomIsExist(String bomCode) {
        LambdaQueryWrapper<Bom> bomLambdaQueryWrapper = new LambdaQueryWrapper<>();
        bomLambdaQueryWrapper.eq(Bom::getBomCode,bomCode);
        List<Bom> bomList = bomMapper.selectList(bomLambdaQueryWrapper);
        if (Objects.nonNull(bomList) && !bomList.isEmpty()){
            return McR.errorUnknown("当前BOM已存在!");
        }
        return McR.success();
    }

    private List<Map> getInnerTable(String formUuid, String formInstId, String tableField, int pageNumber, int pageSize) {
        List<Map> details = new ArrayList<>();
        DDR_New ddrNew = new DDR_New();

        do {
            ddrNew = ydClient.queryData(YDParam.builder()
                    .formUuid(formUuid)
                    .formInstId(formInstId)
                    .tableFieldId(tableField)
                    .pageNumber(pageNumber)
                    .pageSize(pageSize)
                    .build(), YDConf.FORM_QUERY.retrieve_details);
            details.addAll((List<Map>)ddrNew.getData());
            pageNumber++;
        }while (ddrNew.getTotalCount() > pageSize * ddrNew.getPageNumber());

        return details;
    }
}
