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.IBdInvclDao;
import com.hzya.frame.plugin.lets.dao.impl.BdInvclDaoImpl;
import com.hzya.frame.plugin.lets.entity.BdInvclEntity;
import com.hzya.frame.plugin.lets.ofsvo.QueryOfsSKUClassRequestVO;
import com.hzya.frame.plugin.lets.u8cdto.GeneralBillVO_4IDto;
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.OFSSKUClassSearchResponse;
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;

/**
 * OFS->U8C货品档案分类 新增，修改，删除
 * add by zyd 20240802
 *
 * 存货分类新增     /u8cloud/api/uapbd/bdinvcl/save
 * 存货分类修改     /u8cloud/api/uapbd/bdinvcl/update
 * 存货分类删除     /u8cloud/api/uapbd/bdinvcl/delete
 *
 * U8C分类规则 XX-XXX-XX，自动截断
 * eg：
 *  一级：AA
 *      二级：AA001,自动识别为AA的下级
 *          三级：AA00101自动识别为AA001的下级
 */
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 丽知：OFS货品档案分类--->U8C货品档案分类(XX-XXX-XXXX)
 * 传递时需要区分上下级，需要先XX 在XXXXX 最后XXXXXXXXX
 * 分组匹配查询。
 */
public class SKUClassPluginInitializer extends PluginBaseEntity {

    Logger logger = LoggerFactory.getLogger(SKUClassPluginInitializer.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.SKUClassPluginInitializer";
    }

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

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

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

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

    @Autowired
    private IBdInvclDao bdInvclDao;

    @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;
    }


    /**
     * 全量拉取。ofs对比u8c，
     */
    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");

            QueryOfsSKUClassRequestVO queryOfsSKUClassRequestVO = new QueryOfsSKUClassRequestVO();
            queryOfsSKUClassRequestVO.setLastUpdated_start(startTimeStr);
            queryOfsSKUClassRequestVO.setLastUpdated_end(endTimeStr);
            List<OFSSKUClassSearchResponse.SKUClass> skuClasses = querySkuClass(queryOfsSKUClassRequestVO);
            if (skuClasses.size() == 0) {
                return;
            }

            //过滤日志
            List<OFSSKUClassSearchResponse.SKUClass> filterSKUClasss = filterData(skuClasses);
            if (filterSKUClasss.size() == 0) {
                return;
            }

            //推送
            implement(filterSKUClasss);


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

    /**
     * 按分类名称
     */
    public void start(String classCode) {
        try {
            QueryOfsSKUClassRequestVO queryOfsSKUClassRequestVO = new QueryOfsSKUClassRequestVO();
            queryOfsSKUClassRequestVO.setCInvCCode(classCode);
            List<OFSSKUClassSearchResponse.SKUClass> skuClasses = querySkuClass(queryOfsSKUClassRequestVO);
            if(skuClasses.size()==0){
                Assert.state(false, "根据OFS分类编码：{}，未查询到存货分类，请检查入参或者OFS存货分类。", skuClasses);
            }

            //过滤日志
            List<OFSSKUClassSearchResponse.SKUClass> filterGoodsClass = filterData(skuClasses);
            if(filterGoodsClass.size()==0){
                Assert.state(false, "根据OFS分类编码：{}，已被推送成功，请勿重新推送。", skuClasses);
            }

            //推送
            implement(filterGoodsClass);

        } catch (Exception e) {
            logger.error("丽知：OFS货品档案分类--->U8C货品档案分类,start(String className)方法报错：", 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";
            QueryOfsSKUClassRequestVO queryOfsSKUClassRequestVO = new QueryOfsSKUClassRequestVO();
            queryOfsSKUClassRequestVO.setLastUpdated_start(start);
            queryOfsSKUClassRequestVO.setLastUpdated_end(end);
            List<OFSSKUClassSearchResponse.SKUClass> skuClasses = querySkuClass(queryOfsSKUClassRequestVO);
            if(skuClasses.size()==0){
                Assert.state(false, "根据日期期间[开始时间]-[结束时间]：{}-{}，未查询到OFS存货分类。", startTime, endTime);
            }
            //过滤日志
            List<OFSSKUClassSearchResponse.SKUClass> filterGoodsClass = filterData(skuClasses);
            if (filterGoodsClass.size()==0) {
                Assert.state(false, "根据日期期间[开始时间]-[结束时间]：{}-{}，该调期已被推送成功，请勿重新推送。", startTime, endTime);

            }

            //推送
            implement(filterGoodsClass);

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

    public List<OFSSKUClassSearchResponse.SKUClass> filterData(List<OFSSKUClassSearchResponse.SKUClass> skuClasses) {
        List<OFSSKUClassSearchResponse.SKUClass> filterSKUClasss = new ArrayList<>();
        for (OFSSKUClassSearchResponse.SKUClass skuClass : skuClasses) {
            String rootAppPk = skuClass.getCInvCCode()+"_"+skuClass.getLastUpdated();
            boolean isExis = true;
            IntegrationTaskLivingDetailsEntity integrationTaskLivingDetailsEntity = new IntegrationTaskLivingDetailsEntity();
            integrationTaskLivingDetailsEntity.setRootAppPk(rootAppPk);
            integrationTaskLivingDetailsEntity.setNewState(ProfilesActiveConstant.LOG_STATUS_Y);
            integrationTaskLivingDetailsEntity.setPluginId(getPluginId());
            List<IntegrationTaskLivingDetailsEntity> integrationTaskLivingDetailsEntities = iIntegrationTaskLivingDetailsDao.query(integrationTaskLivingDetailsEntity);
            if (integrationTaskLivingDetailsEntities == null || integrationTaskLivingDetailsEntities.size() == 0) {
                isExis = false;
            }
            if (!isExis) {
                filterSKUClasss.add(skuClass);
            }
        }
        return filterSKUClasss;
    }

    /**
     * U8C分类规则 XX-XXX-XX，自动截断
     * eg：
     * 一级：AA
     * 二级：AA001,自动识别为AA的下级 的001
     * 三级：AA0010001自动识别为AA001的下级 的0001
     */
    public void implement(List<OFSSKUClassSearchResponse.SKUClass> filterSKUClasss) {
        String mapStr=null;
        String businessFormat=null;

        for (OFSSKUClassSearchResponse.SKUClass skuClass : filterSKUClasss) {
            businessFormat=skuClass.getLastUpdated();
            List<BdInvclEntity> bdInvclEntities = new ArrayList<>();
            try {
                String url = null;
                System.out.println(skuClass);
                String skuId = skuClass.getId();
                //查询该id再u8c是否有数据，没有则是新增，有则是修改
                BdInvclEntity bdInvclEntity = new BdInvclEntity();
                bdInvclEntity.setDr(0);
                bdInvclEntity.setForinvname(skuId);
                bdInvclEntity.setDataSourceCode(ProfilesActiveConstant.LETS_DATE_SOURCE);
                List<BdInvclEntity> bdInvclEntityList = bdInvclDao.query(bdInvclEntity);

                BdInvclEntity bdInvcl = new BdInvclEntity();
                if (bdInvclEntityList.size() == 0) {
                    bdInvclEntity.setForinvname(null);
                    bdInvclEntity.setInvclasscode(skuClass.getCInvCCode());
                    bdInvclEntity.setInvclassname(skuClass.getCInvCName());
                    List<BdInvclEntity> bdInvclEntityList1 = bdInvclDao.query(bdInvclEntity);
                    System.out.println(bdInvclEntityList1);
                    if (bdInvclEntityList1.size()==1) {
                        //修改
                        url = OverallConstant.getOverAllValue("bdinvUpdateCode");
                        bdInvclEntity.setPk_invcl(bdInvclEntityList1.get(0).getPkInvcl());
                    }else if (bdInvclEntityList1.size()==0) {
                        //新增
                        url = OverallConstant.getOverAllValue("bdinvSaveCode");
                    }
                } else if (bdInvclEntityList.size() == 1) {
                    //修改
                    url = OverallConstant.getOverAllValue("bdinvUpdateCode");
                    bdInvclEntity.setPk_invcl(bdInvclEntityList.get(0).getPkInvcl());
                } else {
                    Assert.state(false, "");
                }

                //组装数据
                //分类编码-invclasscode
                bdInvclEntity.setInvclasscode(skuClass.getCInvCCode());
                //分类名称-invclassname
                bdInvclEntity.setInvclassname(skuClass.getCInvCName());
                //公司编码-pk_corp
                bdInvclEntity.setPk_corp("0001");
                //外文名 forinvname（ofs存货分类id）
                bdInvclEntity.setForinvname(skuId);

                //推送
                bdInvclEntities.add(bdInvclEntity);
                String jsonStr = JSONUtil.toJsonStr(bdInvclEntities);
                mapStr="{\"invcl\":"+jsonStr+"}";
                ZTResult ztResult = pushU8CByApiCode.pushByCode(url, mapStr);
                //两层判断,一层中台转发,一层u8c返回
                Attribute attribute = ztResult.getAttribute();
                if ("false".equals(ztResult.getFlag())) {
                    //转发失败
                    Assert.state(false, "丽知：OFS货品档案分类--->U8C货品档案分类.中台转发失败,失败原因:{}", attribute.getErrormsg());
                }
                boolean isSuccess = false;
                String invclasscode = "";
                if ("success".equals(attribute.getStatus())) {
                    isSuccess = true;
                    String data = attribute.getData();
                    BdInvclEntity resBdInvclEntity = resultDataHandle(data);
                    System.out.println(resBdInvclEntity);
                    invclasscode = resBdInvclEntity.getInvclasscode();
                }
                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(businessFormat);
                integrationTaskLivingDetailsEntity.setRootAppPk(invclasscode+"_"+businessFormat);
                integrationTaskLivingDetailsEntity.setRootAppBill(invclasscode);
                integrationTaskLivingDetailsEntity.setPluginId(getPluginId());
                saveOrUpdateBusinessLogUtil.saveOrUpdate(integrationTaskLivingDetailsEntity);
            }catch (Exception e){
                e.printStackTrace();
                logger.error("丽知：OFS货品档案分类--->U8C货品档案分类,implement()方法报错：", e);
                //失败
                String ErrMessage = e.getMessage();

                //失败
                IntegrationTaskLivingDetailsEntity integrationTaskLivingDetailsEntity = new IntegrationTaskLivingDetailsEntity();
                integrationTaskLivingDetailsEntity.setNewState(ProfilesActiveConstant.LOG_STATUS_N);
                integrationTaskLivingDetailsEntity.setRootAppNewData(mapStr);
                integrationTaskLivingDetailsEntity.setNewTransmitInfo(ErrMessage);
                integrationTaskLivingDetailsEntity.setNewPushDate(new Date());
                integrationTaskLivingDetailsEntity.setBusinessDate(businessFormat);
                integrationTaskLivingDetailsEntity.setRootAppPk(skuClass.getCInvCCode()+"_"+businessFormat);
                integrationTaskLivingDetailsEntity.setRootAppBill(skuClass.getCInvCCode());
                integrationTaskLivingDetailsEntity.setPluginId(getPluginId());
                saveOrUpdateBusinessLogUtil.saveOrUpdate(integrationTaskLivingDetailsEntity);
            }


        }
    }

    /**
     * OFS存货分类查询
     */
    public List<OFSSKUClassSearchResponse.SKUClass> querySkuClass(QueryOfsSKUClassRequestVO queryOfsSKUClassRequestVO) throws Exception {

        int pageNo = 1;
        int pageSize = 500;

        List<OFSSKUClassSearchResponse.SKUClass> all = new ArrayList<>();

        InterfaceParamByU8CApiDto interfaceParamDto = new InterfaceParamByU8CApiDto();
        interfaceParamDto.setApi("ofs.inventory.class.search");
        queryOfsSKUClassRequestVO.setClientCode("LETS");
        queryOfsSKUClassRequestVO.setPageNo(pageNo);
        queryOfsSKUClassRequestVO.setPageSize(pageSize);
        interfaceParamDto.setData(JSON.toJSONString(queryOfsSKUClassRequestVO));
        OFSSKUClassSearchResponse ofsskuClassSearchResponse = (OFSSKUClassSearchResponse) ofsUnifiedService.unifiedByU8CApi(interfaceParamDto);

        all.addAll(ofsskuClassSearchResponse.getData());

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

    /**
     * 查询u8c中pk_corp=0001下的所有分类(集团)
     */
    public List<BdInvclEntity> queryU8CAllInvcl() {
        BdInvclEntity bdInvclEntity = new BdInvclEntity();
        bdInvclEntity.setDr(0);
        bdInvclEntity.setPkCorp("0001");
        bdInvclEntity.setDataSourceCode(ProfilesActiveConstant.LETS_DATE_SOURCE);
        List<BdInvclEntity> bdInvclEntityList = bdInvclDao.query(bdInvclEntity);
        return bdInvclEntityList;
    }

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