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.BdCorpEntity;
import com.hzya.frame.plugin.lets.entity.BdInvbasdocEntity;
import com.hzya.frame.plugin.lets.entity.BdInvmandocEntity;
import com.hzya.frame.plugin.lets.ofsvo.QueryOfsKitRequestVO;
import com.hzya.frame.plugin.lets.u8cdto.ReusltStrDto;
import com.hzya.frame.plugin.lets.u8cdto.SetpartVO;
import com.hzya.frame.plugin.lets.util.PushDataByU8cUtil;
import com.hzya.frame.plugin.lets.util.QueryU8CEntityUtil;
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.dto.InterfaceParamByU8CApiDto;
import com.hzya.frame.ttxofs.dto.kit.OfsKitOrderSearchResponse;
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.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

/**
 * OFS实物组套同步U8C成套件档案
 * <p>
 * U8C成套件没有修改，，只有删除和新增
 * 真的是日了狗了！！！！这个接口千万不要使用code模式，单个公司没问题，多个公司生成的管理档案有问题。
 */
public class KitPluginInitializer extends PluginBaseEntity {
    Logger logger = LoggerFactory.getLogger(KitPluginInitializer.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.KitPluginInitializer";
    }

    @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;
    @Autowired
    private QueryU8CEntityUtil queryU8CEntityUtil;

    @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");
            QueryOfsKitRequestVO queryOfsKitRequestVO = new QueryOfsKitRequestVO();
            queryOfsKitRequestVO.setLastUpdated_start(startTimeStr);
            queryOfsKitRequestVO.setLastUpdated_end(endTimeStr);
            List<OfsKitOrderSearchResponse.OfsKit> ofsKits = queryOfsKits(queryOfsKitRequestVO);
            if (ofsKits.size() == 0) {
                return;
            }
            //过滤
            List<OfsKitOrderSearchResponse.OfsKit> filterKits = filterData(ofsKits);
            if(filterKits.size()==0){
                return;
            }
            //实现
            implement(filterKits);
        } catch (Exception e) {
            logger.error("丽知：OFS实物组套--->U8C成套件档案,start()方法报错：", e);
        }
    }

    public void start(String SkuCode) {
        try {
            QueryOfsKitRequestVO queryOfsKitRequestVO = new QueryOfsKitRequestVO();
            queryOfsKitRequestVO.setSkuCode(SkuCode);
            List<OfsKitOrderSearchResponse.OfsKit> ofsKits = queryOfsKits(queryOfsKitRequestVO);
            if(ofsKits.size()==0){
                Assert.state(false,"根据OFS实物组套sku编码：{}，未查询到OFS实物组套，请检查。",SkuCode);
            }
            //过滤
            List<OfsKitOrderSearchResponse.OfsKit> filterKits = filterData(ofsKits);
            if(filterKits.size()==0){
                Assert.state(false,"根据OFS实物组套sku编码：{}，已被推送成功，请勿重新推送。",SkuCode);
            }
            //实现
            implement(filterKits);
        } catch (Exception e) {
            logger.error("丽知：OFS实物组套--->U8C成套件档案,start(String SkuCode)方法报错：", 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";
            QueryOfsKitRequestVO queryOfsKitRequestVO = new QueryOfsKitRequestVO();
            queryOfsKitRequestVO.setLastUpdated_start(start);
            queryOfsKitRequestVO.setLastUpdated_end(end);
            List<OfsKitOrderSearchResponse.OfsKit> ofsKits = queryOfsKits(queryOfsKitRequestVO);
            if(ofsKits.size()==0){
                Assert.state(false, "丽知：OFS实物组套--->U8C成套件档案根据日期期间[开始时间]-[结束时间]：{}-{}，未查询到OFS实物组套", startTime, endTime);
            }
            //过滤
            List<OfsKitOrderSearchResponse.OfsKit> filterKits = filterData(ofsKits);
            if(filterKits.size()==0){
                Assert.state(false, "丽知：OFS实物组套--->U8C成套件档案根据日期期间[开始时间]-[结束时间]：{}-{}，该期间OFS实物组套已被推送成功，请勿重新推送", startTime, endTime);
            }
            //实现
            implement(filterKits);
        } catch (Exception e) {
            logger.error("丽知：OFS实物组套--->U8C成套件档案,start(String startTime, String endTim)方法报错：", e);
        }
    }


    /**
     * 过滤成功日志
     *
     * @param ofsKits
     * @return
     */
    public List<OfsKitOrderSearchResponse.OfsKit> filterData(List<OfsKitOrderSearchResponse.OfsKit> ofsKits) {
        List<OfsKitOrderSearchResponse.OfsKit> filterKits = new ArrayList<>();
        for (OfsKitOrderSearchResponse.OfsKit ofsKit : ofsKits) {
            String rootAppPk = ofsKit.getHeader().getSkuCode();
            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) {
                filterKits.add(ofsKit);
            }
        }
        return filterKits;
    }

    /**
     * 全公司分配，，，
     *
     * pk_corp 公司
     * childsnum 父含子数
     * partpercent 单件单价权数
     * pk_invmandocpart 配件编码
     * pk_invmandocset 成套件编码
     * @param filterKits
     */
    public void implement(List<OfsKitOrderSearchResponse.OfsKit> filterKits){

        //查询所有公司
        List<BdCorpEntity> bdCorpEntities = queryU8CEntityUtil.queryBdCorp();
        System.out.println(bdCorpEntities);

        //ofsKit列表
        for (OfsKitOrderSearchResponse.OfsKit ofsKit : filterKits) {
            System.out.println(ofsKit);

            String mapStr="";
            String response="";
            String format=ofsKit.getHeader().getLastUpdated();

            //套件编码
            String setKkuCode = ofsKit.getHeader().getSkuCode();
            //套件 存货基本档案
            BdInvbasdocEntity bdInvbasdocSet = queryU8CEntityUtil.queryBdInvbasdocByCode(setKkuCode);
            if (bdInvbasdocSet == null) {
                Assert.state(false,"套件编码：{}，没有查询到U8C存货基本档案，请维护。",setKkuCode);
            }

            List<SetpartVO> setpartVOS=new ArrayList<>();
            try {
                //ofsKit表体
                for (OfsKitOrderSearchResponse.OfsKit.KitDetail detail : ofsKit.getDetails()) {
                    //配件
                    String partSkuCode = detail.getSkuCode();
                    BdInvbasdocEntity bdInvbasdocPart = queryU8CEntityUtil.queryBdInvbasdocByCode(partSkuCode);
                    if (bdInvbasdocPart == null) {
                        Assert.state(false,"配件编码：{}，没有查询到U8C存货基本档案，请维护。",partSkuCode);
                    }

                    //每个物料，给每个公司一份
                    for (BdCorpEntity bdCorpEntity : bdCorpEntities) {
                        SetpartVO setpart = new SetpartVO();
                        //childsnum 父含子数
                        setpart.setChildsnum(detail.getQuantity());
                        //partpercent 单件单价权数,妮妮姐说的：全传1
                        setpart.setPartpercent("1");
                        //pk_corp 公司
                        setpart.setPk_corp(bdCorpEntity.getPkCorp());


                        //套件 存货管理档案
                        BdInvmandocEntity bdInvmandocSet = queryU8CEntityUtil.queryBdInvmandocByPkInvbasdocAndPkCorp(bdInvbasdocSet.getPkInvbasdoc(), bdCorpEntity.getPkCorp());
                        if(bdInvmandocSet==null){
                            Assert.state(false,"套件编码：{}，公司：{}，没有查询到U8C存货管理档案，请维护。",setKkuCode,bdCorpEntity.getPkCorp());

                        }

                        //配件 存货管理档案
                        BdInvmandocEntity bdInvmandocPart = queryU8CEntityUtil.queryBdInvmandocByPkInvbasdocAndPkCorp(bdInvbasdocPart.getPkInvbasdoc(), bdCorpEntity.getPkCorp());
                        if(bdInvmandocPart==null){
                            Assert.state(false,"套件编码：{}，公司：{}，没有查询到U8C存货管理档案，请维护。",partSkuCode,bdCorpEntity.getPkCorp());

                        }
                        //pk_invmandocset 成套件编码
                        setpart.setPk_invmandocset(bdInvmandocSet.getPkInvmandoc());
                        //pk_invmandocpart 配件编码
                        setpart.setPk_invmandocpart(bdInvmandocPart.getPkInvmandoc());

                        setpartVOS.add(setpart);
                    }

//                    SetpartVO setpart = new SetpartVO();
//                    //pk_invmandocset 成套件编码
//                    setpart.setPk_invmandocset(ofsKit.getHeader().getSkuCode());
//                    //pk_invmandocpart 配件编码
//                    setpart.setPk_invmandocpart(detail.getSkuCode());
//                    //childsnum 父含子数
//                    setpart.setChildsnum(detail.getQuantity());
//                    System.out.println(detail.getQuantity());
//                    //partpercent 单件单价权数,妮妮姐说的：全传1
//                    setpart.setPartpercent("1");
//                    //pk_corp 公司
//                    setpart.setPk_corp("SHXM");
//                    setpartVOS.add(setpart);


                }

                System.out.println(setpartVOS);
                System.out.println(JSONUtil.toJsonStr(setpartVOS));
                String jsonStr = JSONUtil.toJsonStr(setpartVOS);

                mapStr= "{\"setpartvo\":" + jsonStr + "}";
//                ZTResult ztResult = pushU8CByApiCode.pushByCode(OverallConstant.getOverAllValue("setpartInsertCode"), mapStr);
                ZTResult ztResult = pushU8CByApiCode.pushByPK(OverallConstant.getOverAllValue("setpartInsertCode"), 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;
                if ("success".equals(attribute.getStatus())) {
                    isSuccess = true;
                    String data = attribute.getData();
                }
                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(ofsKit.getHeader().getSkuCode());
                integrationTaskLivingDetailsEntity.setRootAppBill(ofsKit.getHeader().getSkuCode());
                integrationTaskLivingDetailsEntity.setPluginId(getPluginId());
                integrationTaskLivingDetailsEntity.setDef1(ofsKit.getHeader().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(ofsKit.getHeader().getSkuCode());
                integrationTaskLivingDetailsEntity.setRootAppBill(ofsKit.getHeader().getSkuCode());
                integrationTaskLivingDetailsEntity.setPluginId(getPluginId());
                integrationTaskLivingDetailsEntity.setDef1(ofsKit.getHeader().getId());
                saveOrUpdateBusinessLogUtil.saveOrUpdate(integrationTaskLivingDetailsEntity);
            }
        }


    }


    public List<OfsKitOrderSearchResponse.OfsKit> queryOfsKits(QueryOfsKitRequestVO queryOfsKitRequestVO) throws Exception {
        int pageNo = 1;
        int pageSize = 500;

        List<OfsKitOrderSearchResponse.OfsKit> all = new ArrayList<>();

        InterfaceParamByU8CApiDto interfaceParamDto = new InterfaceParamByU8CApiDto();
        interfaceParamDto.setApi("ofs.actual.bom.search");
        queryOfsKitRequestVO.setClientCode("LETS");
        queryOfsKitRequestVO.setPageNo(String.valueOf(pageNo));
        queryOfsKitRequestVO.setPageSize(String.valueOf(pageSize));
        interfaceParamDto.setData(JSON.toJSONString(queryOfsKitRequestVO));
        OfsKitOrderSearchResponse ofsKitOrderSearchResponse = (OfsKitOrderSearchResponse) ofsUnifiedService.unifiedByU8CApi(interfaceParamDto);
        System.out.println(ofsKitOrderSearchResponse);

        all.addAll(ofsKitOrderSearchResponse.getData());

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

        while (count >= pageSize) {//>=500,可能还有下一页。
            //还有下一页
            pageNo++;
            queryOfsKitRequestVO.setPageNo(String.valueOf(pageNo));
            interfaceParamDto.setData(JSON.toJSONString(queryOfsKitRequestVO));
            OfsKitOrderSearchResponse ofsKitOrderSearchResponse1 = (OfsKitOrderSearchResponse) ofsUnifiedService.unifiedByU8CApi(interfaceParamDto);

            all.addAll(ofsKitOrderSearchResponse1.getData());
            count = ofsKitOrderSearchResponse1.getData().size();
        }
        if (all == null || all.size() == 0) {
            return null;
        }
        return all;
    }
}
