package com.hzya.frame.plugin.lets.plugin.base;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hzya.frame.base.PluginBaseEntity;
import com.hzya.frame.plugin.lets.constant.OverallConstant;
import com.hzya.frame.plugin.lets.constant.ProfilesActiveConstant;
import com.hzya.frame.plugin.lets.dao.IBdInvbasdocDao;
import com.hzya.frame.plugin.lets.entity.BdInvbasdocEntity;
import com.hzya.frame.plugin.lets.entity.BdInvclEntity;
import com.hzya.frame.plugin.lets.ofsvo.QueryOfsSKURequestVO;
import com.hzya.frame.plugin.lets.u8cdto.InvBasDocVO;
import com.hzya.frame.plugin.lets.u8cdto.ReusltStrDto;
import com.hzya.frame.plugin.lets.util.PushDataByU8cUtil;
import com.hzya.frame.plugin.lets.util.SaveOrUpdateBusinessLogUtil;
import com.hzya.frame.plugin.lets.util.pushData.Attribute;
import com.hzya.frame.plugin.lets.util.pushData.PushU8CByApiCode;
import com.hzya.frame.plugin.lets.util.pushData.ZTResult;
import com.hzya.frame.sysnew.integtationTaskLivingDetails.dao.IIntegrationTaskLivingDetailsDao;
import com.hzya.frame.sysnew.integtationTaskLivingDetails.entity.IntegrationTaskLivingDetailsEntity;
import com.hzya.frame.ttxofs.basics.ReturnMessageBasics;
import com.hzya.frame.ttxofs.dto.InterfaceParamByU8CApiDto;
import com.hzya.frame.ttxofs.dto.ofsBaseSearch.OFSSKUSearchResponse;
import com.hzya.frame.ttxofs.service.OfsUnifiedService;
import com.hzya.frame.web.entity.JsonResultEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * OFS->U8C货品档案 新增，修改，删除
 * add by zyd 20240802
 * <p>
 * 存货基本档案新增     /u8cloud/api/uapbd/invbasdoc/insert
 * 存货基本档案修改     /u8cloud/api/uapbd/invbasdoc/update
 * 存货基本档案封存     /u8cloud/api/uapbd/invbasdoc/seal
 * 存货基本档案取消封存  /u8cloud/api/uapbd/invbasdoc/unseal
 */
public class SKUPluginInitializer extends PluginBaseEntity {

    Logger logger = LoggerFactory.getLogger(SKUPluginInitializer.class);

    private static final ReentrantLock LOCK = new ReentrantLock(true);

    @Override
    public void initialize() {
        logger.info(getPluginLabel() + "執行初始化方法initialize()");
    }

    @Override
    public void destroy() {
        logger.info(getPluginLabel() + "執行銷毀方法destroy()");
    }

    @Override
    public String getPluginId() {
        return "base.GoodsPluginInitializer";
    }

    @Override
    public String getPluginName() {
        return "丽知：OFS货品档案--->U8C货品档案";
    }

    @Override
    public String getPluginLabel() {
        return "丽知：OFS货品档案--->U8C货品档案";
    }

    @Override
    public String getPluginType() {
        return "1";
    }

    @Autowired
    private IIntegrationTaskLivingDetailsDao iIntegrationTaskLivingDetailsDao;
    @Autowired
    private PushDataByU8cUtil pushDataByU8cUtil;
    @Autowired
    private PushU8CByApiCode pushU8CByApiCode;
    @Autowired
    private SaveOrUpdateBusinessLogUtil saveOrUpdateBusinessLogUtil;

    @Autowired
    private OfsUnifiedService ofsUnifiedService;

    @Autowired
    private IBdInvbasdocDao bdInvbasdocDao;

    @Override
    public JsonResultEntity executeBusiness(JSONObject requestJson) throws Exception {
        try {
            logger.info("调用：" + getPluginName() + "-插件");
            String prod = "prod";
            String param = String.valueOf(requestJson.get("param"));
            if (requestJson != null && ProfilesActiveConstant.TYPE_DATE.equals(requestJson.get("type"))) {
                //按日期
                if (param != null && !"".equals(param)) {
                    String[] split = param.split("/");
                    if (!(split.length == 2)) {
                        Assert.state(false, "时间格式传递不正确");
                    }
                    Assert.notNull(split[0], "开始时间不能为空");
                    Assert.notNull(split[1], "结束时间不能为空");
                    start(split[0], split[1]);
                }
            } else if (requestJson != null && ProfilesActiveConstant.TYPE_VBILLCODE.equals(requestJson.get("type"))) {
                //按单号
                if (param != null && !"".equals(param)) {
                    start(param);
                }
            } else if (ProfilesActiveConstant.TYPE_DETAIL_ERROR.equals(requestJson.get("type"))) {
                String integrationTaskLivingDetails = (String) requestJson.get("integration_task_living_details_id");
                IntegrationTaskLivingDetailsEntity integrationTaskLivingDetailsEntity = saveOrUpdateBusinessLogUtil.queryIntegrationTaskLivingDetailsEntity(integrationTaskLivingDetails);
                start(integrationTaskLivingDetailsEntity.getRootAppPk());
            } else if (ProfilesActiveConstant.LETS_PROFILES_ACTIVE.equals(prod)) {
                //默认
                start();
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("executeBusiness方法抛出异常", e);
        }
        return null;
    }


    /**
     * 默认推送
     */
    public void start() {
        try {
            //获取当前时间
            Date currentDate = new Date();
            Date startTime = DateUtil.offset(currentDate, DateField.MINUTE, -10);
            Date endTime = DateUtil.offset(currentDate, DateField.MINUTE, -2);
            String startTimeStr = DateUtil.format(startTime, "yyyy-MM-dd HH:mm:ss");
            String endTimeStr = DateUtil.format(endTime, "yyyy-MM-dd HH:mm:ss");

            QueryOfsSKURequestVO queryOfsSKURequestVO = new QueryOfsSKURequestVO();
            queryOfsSKURequestVO.setLastUpdated_start(startTimeStr);
            queryOfsSKURequestVO.setLastUpdated_end(endTimeStr);
            List<OFSSKUSearchResponse.OFSSKU> ofsskuList = queryOfsSKUs(queryOfsSKURequestVO);
            if (ofsskuList == null || ofsskuList.size() == 0) {
                return;
            }
            //分组排序,
            List<OFSSKUSearchResponse.OFSSKU> sortSkuList = groupAndSort(ofsskuList);

            //过滤日志
            List<OFSSKUSearchResponse.OFSSKU> filterSkus = filterData(sortSkuList);
            if (filterSkus.size() == 0) {
                return;
            }
            //具体实现
            implement(filterSkus);


        } catch (Exception e) {
            logger.error("丽知：OFS货品档案--->U8C货品档案,start()方法报错：", e);
        }
    }

    /**
     * 按sku名称
     * 存在 编码相同，名称不一样的情况
     * 先根据code分组，在根据修改时间倒排
     * 按修改时间倒排，取最新的修改时间
     */
    public void start(String goodsCode) {
        String[] split = goodsCode.split("_");
        try {
            QueryOfsSKURequestVO queryOfsSKURequestVO = new QueryOfsSKURequestVO();
            queryOfsSKURequestVO.setCode(split[0]);
            List<OFSSKUSearchResponse.OFSSKU> ofsskuList = queryOfsSKUs(queryOfsSKURequestVO);
            if (ofsskuList == null || ofsskuList.size() == 0) {
                Assert.state(false, "根据OFS SKU主档编码：{}，未查询到SKU主档，请检查入参或者OFS SKU主档。", split[0]);
            }
            //分组排序,
            List<OFSSKUSearchResponse.OFSSKU> sortSkuList = groupAndSort(ofsskuList);

            //过滤日志
            List<OFSSKUSearchResponse.OFSSKU> filterSkus = filterData(sortSkuList);
            if (filterSkus.size() == 0) {
                Assert.state(false, "根据OFS SKU主档编码：{}，已被推送成功，请勿重新推送。", split[0]);
            }
            //具体实现
            implement(filterSkus);

        } catch (Exception e) {
            logger.error("丽知：OFS货品档案--->U8C货品档案,start(String goodsName)方法报错：", e);
        }

    }

    /**
     * 按时间区间
     */
    public void start(String startTime, String endTime) {
        try {
            Date business_start = DateUtil.parse(startTime);
            Date business_end = DateUtil.parse(endTime);
            String start = DateUtil.format(business_start, "yyyy-MM-dd") + " 00:00:00";
            String end = DateUtil.format(business_end, "yyyy-MM-dd") + " 23:59:59";

            QueryOfsSKURequestVO queryOfsSKURequestVO = new QueryOfsSKURequestVO();
            queryOfsSKURequestVO.setLastUpdated_start(start);
            queryOfsSKURequestVO.setLastUpdated_end(end);
            List<OFSSKUSearchResponse.OFSSKU> ofsskuList = queryOfsSKUs(queryOfsSKURequestVO);
            if (ofsskuList == null || ofsskuList.size() == 0) {
                Assert.state(false, "根据期间：{} - {} 内，未查询到OFS系统中SKU主档信息，请检查。");
            }
            //分组排序,
            List<OFSSKUSearchResponse.OFSSKU> sortSkuList = groupAndSort(ofsskuList);

            //过滤日志
            List<OFSSKUSearchResponse.OFSSKU> filterSkus = filterData(sortSkuList);
            if (filterSkus.size() == 0) {
                Assert.state(false, "根据期间：{} - {} 内询到OFS系统中SKU主档信息已全部推送，请勿重新推送。");
            }
            //具体实现
            implement(filterSkus);

        } catch (Exception e) {
            logger.error("丽知：OFS货品档案--->U8C货品档案,start(String startTime, String endTime)方法报错：", e);
        }
    }

    /**
     * 过滤成功日志
     * rootAppPk
     * [code]_[lastUpdated]
     *
     * @param ofsskuList
     * @return
     */
    public List<OFSSKUSearchResponse.OFSSKU> filterData(List<OFSSKUSearchResponse.OFSSKU> ofsskuList) {
        List<OFSSKUSearchResponse.OFSSKU> filterSkus = new ArrayList<>();
        for (OFSSKUSearchResponse.OFSSKU ofssku : ofsskuList) {
            String rootAppPk = ofssku.getCode() + "_" + ofssku.getLastUpdated();
            boolean isExis = true;
            IntegrationTaskLivingDetailsEntity integrationTaskLivingDetailsEntity = new IntegrationTaskLivingDetailsEntity();
            integrationTaskLivingDetailsEntity.setRootAppPk(rootAppPk);
            integrationTaskLivingDetailsEntity.setNewState(ProfilesActiveConstant.LOG_STATUS_Y_H);
            integrationTaskLivingDetailsEntity.setPluginId(getPluginId());
            List<IntegrationTaskLivingDetailsEntity> integrationTaskLivingDetailsEntities = iIntegrationTaskLivingDetailsDao.query(integrationTaskLivingDetailsEntity);
            if (integrationTaskLivingDetailsEntities == null || integrationTaskLivingDetailsEntities.size() == 0) {
                isExis = false;
            }
            if (!isExis) {
                filterSkus.add(ofssku);
            }

        }
        return filterSkus;
    }

    /**
     * 推送
     * 注意：
     * 可能一家公司封存则，则取消分配这家公司的存货管理档案
     */
    public void implement(List<OFSSKUSearchResponse.OFSSKU> filterSkus) {
        for (OFSSKUSearchResponse.OFSSKU sku : filterSkus) {

            String PkInvbasdoc = "";
            String url = "";
            String mapStr = "";
            String format = sku.getLastUpdated();
            String response = "";

            try {
                InvBasDocVO invbasdoc = new InvBasDocVO();
                //主表
                InvBasDocVO.Parent parentvo = new InvBasDocVO.Parent();

                //查询是否存在，返回pkInvbasdoc,如果有则是修改，null则为新增
                //查询该id再u8c是否有数据，没有则是新增，有则是修改 存货基本档案：def2-》ofs主键
                PkInvbasdoc = queryInvbasDocIsExist(sku);
                if (PkInvbasdoc != null) {
                    //修改
                    parentvo.setPk_invbasdoc(PkInvbasdoc);
                    url = OverallConstant.getOverAllValue("bdinvclUpdateCode");
                } else if (PkInvbasdoc == null) {
                    //新增
                    url = OverallConstant.getOverAllValue("bdinvclSaveCode");
                }

                //def2 ofs id
                parentvo.setDef2(sku.getId());
                //invcode 存货编码
                parentvo.setInvcode(sku.getCode());
                //invmnecode 助记码
                parentvo.setInvmnecode(sku.getCode());
                //invname 存货名称
                parentvo.setInvname(sku.getName());
                //invshortname 存货简称
                parentvo.setInvshortname(sku.getName());
                //pk_invcl 分类
                parentvo.setPk_invcl(sku.getCInvCCode());

                //def1 ofs品牌
                parentvo.setDef1(sku.getBrandCode());

                //pk_measdoc 主计量单位，ofs没有单位，默认个，20240830万万同意
                parentvo.setPk_measdoc("EA");

                //pk_taxitems 税率 4001	商业（13 % )	13.00000000
                parentvo.setPk_taxitems("4001");

                //creator 创建人
                parentvo.setCreator("tbadmin");

                //memo 备注
                parentvo.setMemo(sku.getRemark());

                //setpartsflag 成套件，默认都是true
                parentvo.setSetpartsflag("true");

                invbasdoc.setParentvo(parentvo);
                //子表,暂时没有要传的值
                String jsonStr = JSONUtil.toJsonStr(invbasdoc);
                mapStr = "{\"invbasdoc\":" + jsonStr + "}";
                ZTResult ztResult = pushU8CByApiCode.pushByCode(url, mapStr);
                //两层判断,一层中台转发,一层u8c返回
                Attribute attribute = ztResult.getAttribute();

                if ("false".equals(ztResult.getFlag())) {
                    //转发失败
                    response = JSONUtil.toJsonStr(ztResult.getAttribute());
                    Assert.state(false, "丽知：OFS货品档案--->U8C货品档案，中台转发失败,失败原因:{}", ztResult.getAttribute());
                }
                boolean isSuccess = false;
                String invbascode = "";
                if ("success".equals(attribute.getStatus())) {
                    isSuccess = true;
                    String data = attribute.getData();
                    InvBasDocVO resInvBasDocVO = resultDataHandle(data);
                    invbascode = resInvBasDocVO.getParentvo().getInvcode();
                }
                if (!isSuccess) {
                    Assert.state(false, "丽知：OFS货品档案--->U8C货品档案 失败 接口返回结果：{} 接口入参:{}", attribute.getErrormsg(), mapStr);
                }

                //成功
                IntegrationTaskLivingDetailsEntity integrationTaskLivingDetailsEntity = new IntegrationTaskLivingDetailsEntity();
                integrationTaskLivingDetailsEntity.setNewState(ProfilesActiveConstant.LOG_STATUS_Y);
                integrationTaskLivingDetailsEntity.setRootAppNewData(mapStr);
                integrationTaskLivingDetailsEntity.setNewTransmitInfo(attribute.getData());
                integrationTaskLivingDetailsEntity.setNewPushDate(new Date());
                integrationTaskLivingDetailsEntity.setBusinessDate(format);
                integrationTaskLivingDetailsEntity.setRootAppPk(sku.getCode() + "_" + sku.getLastUpdated());
                integrationTaskLivingDetailsEntity.setRootAppBill(sku.getCode());
                integrationTaskLivingDetailsEntity.setPluginId(getPluginId());
                integrationTaskLivingDetailsEntity.setDef1(sku.getId());
                saveOrUpdateBusinessLogUtil.saveOrUpdate(integrationTaskLivingDetailsEntity);

            } catch (Exception e) {
                e.printStackTrace();
                logger.error("推送U8C，丽知：OFS货品档案--->U8C货品档案失败，失败原因：" + e);
                //失败
                ReusltStrDto reusltStrDto = JSON.parseObject(response, ReusltStrDto.class);
                String ErrMessage = "推送U8C，丽知：OFS货品档案--->U8C货品档案失败，失败原因：" + reusltStrDto.getErrormsg();
                //失败
                IntegrationTaskLivingDetailsEntity integrationTaskLivingDetailsEntity = new IntegrationTaskLivingDetailsEntity();
                integrationTaskLivingDetailsEntity.setNewState(ProfilesActiveConstant.LOG_STATUS_N);
                integrationTaskLivingDetailsEntity.setRootAppNewData(mapStr);
                integrationTaskLivingDetailsEntity.setNewTransmitInfo(ErrMessage);
                integrationTaskLivingDetailsEntity.setNewPushDate(new Date());
                integrationTaskLivingDetailsEntity.setBusinessDate(format);
                integrationTaskLivingDetailsEntity.setRootAppPk(sku.getCode() + "_" + sku.getLastUpdated());
                integrationTaskLivingDetailsEntity.setRootAppBill(sku.getCode());
                integrationTaskLivingDetailsEntity.setPluginId(getPluginId());
                integrationTaskLivingDetailsEntity.setDef1(sku.getId());
                saveOrUpdateBusinessLogUtil.saveOrUpdate(integrationTaskLivingDetailsEntity);

            }

        }
    }

    public String queryInvbasDocIsExist(OFSSKUSearchResponse.OFSSKU sku) {
        String PkInvbasdoc = "";
        BdInvbasdocEntity bdInvbasdocEntity = new BdInvbasdocEntity();
        bdInvbasdocEntity.setDr(0L);
        bdInvbasdocEntity.setDef2(sku.getId());
        bdInvbasdocEntity.setDataSourceCode(ProfilesActiveConstant.LETS_DATE_SOURCE);
        List<BdInvbasdocEntity> bdInvbasdocEntityList = bdInvbasdocDao.query(bdInvbasdocEntity);//根据ofs id
        if (bdInvbasdocEntityList.size() == 0) {
            bdInvbasdocEntity.setDef2(null);
            bdInvbasdocEntity.setInvcode(sku.getCode());
            bdInvbasdocEntity.setInvname(sku.getName());
            List<BdInvbasdocEntity> bdInvbasdocEntityList1 = bdInvbasdocDao.query(bdInvbasdocEntity);//根据编码+名称
            if (bdInvbasdocEntityList1.size() == 0) {
                bdInvbasdocEntity.setInvname(null);
                List<BdInvbasdocEntity> bdInvbasdocEntityList2 = bdInvbasdocDao.query(bdInvbasdocEntity);//进查询编码
                if (bdInvbasdocEntityList2.size() == 0) {//编码不存在
                    return null;
                } else if (bdInvbasdocEntityList2.size() == 1) {//编码存在
                    PkInvbasdoc = bdInvbasdocEntityList2.get(0).getPkInvbasdoc();//主键
                }
            } else if (bdInvbasdocEntityList1.size() == 1) {
                //修改
                PkInvbasdoc = bdInvbasdocEntityList1.get(0).getPkInvbasdoc();//主键
            }
        } else if (bdInvbasdocEntityList.size() == 1) {
            //修改
            PkInvbasdoc = bdInvbasdocEntityList.get(0).getPkInvbasdoc();//主键
        } else {
            //异常,存在多个
            Assert.state(false, "SKU主档编码：{}，id：{}。U8C存货基本档案def2（OFS中SKU主档id）存在多个，请检查。", sku.getCode(), sku.getId());
        }
        return PkInvbasdoc;
    }

    /**
     * 按code分组，并按lastUpdated排序
     *
     * @param ofsskuList
     * @return
     */
    public List<OFSSKUSearchResponse.OFSSKU> groupAndSort(List<OFSSKUSearchResponse.OFSSKU> ofsskuList) {
        List<OFSSKUSearchResponse.OFSSKU> sortSkus = new ArrayList<>();

        //根据code进行分组
        Map<String, List<OFSSKUSearchResponse.OFSSKU>> collectMapByCode =
                ofsskuList.stream().collect(Collectors.groupingBy(OFSSKUSearchResponse.OFSSKU::getCode));

        collectMapByCode.forEach((k, v) -> {
            //降序排序 (从新到旧),根据最后修改时间倒排
            List<OFSSKUSearchResponse.OFSSKU> sorted =
                    v.stream().sorted(Comparator.comparing(OFSSKUSearchResponse.OFSSKU::getLastUpdated).reversed()).collect(Collectors.toList());

            //排除status==0的
            for (int i = 0; i < sorted.size(); i++) {
                if ("0".equals(sorted.get(i).getStatus())) {
                    sorted.remove(i);
                }
            }

            if (sorted.size() != 0) {
                sortSkus.add(sorted.get(0));//只取最后修改的一个
            }
        });
        return sortSkus;
    }

    /**
     * 封存存货基本档案
     */
    public void sealImplement(String code) {

    }

    /**
     * 查询OFS SKU档案
     * status 0禁用 1启用
     */
    public List<OFSSKUSearchResponse.OFSSKU> queryOfsSKUs(QueryOfsSKURequestVO queryOfsSKURequestVO) throws Exception {

        int pageNo = 1;
        int pageSize = 500;

        List<OFSSKUSearchResponse.OFSSKU> all = new ArrayList<>();

        InterfaceParamByU8CApiDto interfaceParamDto = new InterfaceParamByU8CApiDto();
        interfaceParamDto.setApi("ofs.sku.search");
        queryOfsSKURequestVO.setClientCode("LETS");
        queryOfsSKURequestVO.setStatus("1");
        queryOfsSKURequestVO.setPageNo(String.valueOf(pageNo));
        queryOfsSKURequestVO.setPageSize(String.valueOf(pageSize));
        interfaceParamDto.setData(JSON.toJSONString(queryOfsSKURequestVO));
        OFSSKUSearchResponse ofsskuSearchResponse = (OFSSKUSearchResponse) ofsUnifiedService.unifiedByU8CApi(interfaceParamDto);

        all.addAll(ofsskuSearchResponse.getData());

        int count = ofsskuSearchResponse.getData().size();

        while (count >= pageSize) {//>=500,可能还有下一页。
            //还有下一页
            pageNo++;
            queryOfsSKURequestVO.setPageNo(String.valueOf(pageNo));
            interfaceParamDto.setData(JSON.toJSONString(queryOfsSKURequestVO));
            OFSSKUSearchResponse ofsskuSearchResponse1 = (OFSSKUSearchResponse) ofsUnifiedService.unifiedByU8CApi(interfaceParamDto);
            all.addAll(ofsskuSearchResponse1.getData());
            count = ofsskuSearchResponse1.getData().size();
        }
        if (all == null || all.size() == 0) {
            return null;
        }
        return all;
    }

    private InvBasDocVO resultDataHandle(String resultData) {
        try {
            if (resultData != null && !"".equals(resultData)) {
                if (resultData.contains("[")) {
                    resultData = resultData.substring(1, resultData.length() - 1);
                }
                return JSON.parseObject(resultData, InvBasDocVO.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("解析返回参数失败的错误", e);
            //如果解析失败，记录原因，但是不能影响结果的记录
        }
        return null;
    }

}
