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.google.common.collect.Lists;
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.u8cdto.GoodsAutoAllotVO;
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.u8c.ax.entity.Ass;
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;

/**
 * U8C->存货基本档案自动分配全公司
 * add by zyd 20240808
 * <p>
 * 存货基本档案分配     /u8cloud/api/uapbd/invbasdoc/assign
 */
public class GoodsAutoAllotPluginInitializer extends PluginBaseEntity {

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

    @Override
    public String getPluginName() {
        return "丽知：U8C->存货基本档案自动分配全公司";
    }

    @Override
    public String getPluginLabel() {
        return "丽知：U8C->存货基本档案自动分配全公司";
    }

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

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

    @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");

            BdInvbasdocEntity bdInvbasdocEntity = new BdInvbasdocEntity();
            bdInvbasdocEntity.setModifytime_start_time(startTimeStr);
            bdInvbasdocEntity.setModifytime_end_time(endTimeStr);
            bdInvbasdocEntity.setDataSourceCode(ProfilesActiveConstant.LETS_DATE_SOURCE);

            List<BdInvbasdocEntity> bdInvbasdocEntityList = bdInvbasdocDao.query(bdInvbasdocEntity);
            if (bdInvbasdocEntityList.size() == 0) {
                return;
            }
            //过滤日志
            List<BdInvbasdocEntity> filterInvbasdocList = filter(bdInvbasdocEntityList);
            if (filterInvbasdocList.size() == 0 || filterInvbasdocList == null) {
                return;
            }

            //推送：自动分配
            implement(filterInvbasdocList);


        } catch (Exception e) {
            logger.error("丽知：U8C->存货基本档案自动分配全公司,start()方法报错：", e);
        }
    }

    /**
     * 按存货基本档案code
     */
    public void start(String invcode) {
        String[] split = invcode.split("_");
        try {
            BdInvbasdocEntity bdInvbasdocEntity = new BdInvbasdocEntity();
            bdInvbasdocEntity.setInvcode(split[0]);
            bdInvbasdocEntity.setDataSourceCode(ProfilesActiveConstant.LETS_DATE_SOURCE);
            List<BdInvbasdocEntity> bdInvbasdocEntityList = bdInvbasdocDao.query(bdInvbasdocEntity);
            if (bdInvbasdocEntityList.size() == 0) {
                Assert.state(false, "U8C->存货基本档案自动分配全公司,存货基本档案编码：{}，不存在。", invcode);
            }
            //过滤日志
            List<BdInvbasdocEntity> filterInvbasdocList = filter(bdInvbasdocEntityList);
            if (filterInvbasdocList.size() == 0 || filterInvbasdocList == null) {
                Assert.state(false, "U8C->存货基本档案自动分配全公司,存货基本档案编码：{}，已被分配,请检查。", invcode);
            }
            //推送：自动分配
            implement(filterInvbasdocList);

        } catch (Exception e) {
            logger.error("丽知：U8C->存货基本档案自动分配全公司,start(String pkInvbasdoc)方法报错：", 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";

            BdInvbasdocEntity bdInvbasdocEntity = new BdInvbasdocEntity();
            bdInvbasdocEntity.setModifytime_start_time(start);
            bdInvbasdocEntity.setModifytime_end_time(end);
            bdInvbasdocEntity.setDataSourceCode(ProfilesActiveConstant.LETS_DATE_SOURCE);
            List<BdInvbasdocEntity> bdInvbasdocEntityList = bdInvbasdocDao.query(bdInvbasdocEntity);
            if (bdInvbasdocEntityList.size() == 0) {
                Assert.state(false, "U8C->存货基本档案自动分配全公司,按日期：{} - {}，未查到存货基本档案。", startTime, endTime);
            }
            //过滤日志
            List<BdInvbasdocEntity> filterInvbasdocList = filter(bdInvbasdocEntityList);
            if (filterInvbasdocList.size() == 0 || filterInvbasdocList == null) {
                Assert.state(false, "U8C->存货基本档案自动分配全公司,按日期：{} - {}，已被分配,请检查。", startTime, endTime);
            }
            //推送：自动分配
            implement(filterInvbasdocList);

        } catch (Exception e) {
            logger.error("丽知：U8C->存货基本档案自动分配全公司,start(String startTime, String endTime)方法报错：", e);
        }
    }

    /**
     * 过滤成功日志
     *
     * @return
     */
    public List<BdInvbasdocEntity> filter(List<BdInvbasdocEntity> bdInvbasdocEntityList) {
        List<BdInvbasdocEntity> filterInvbasdocList = new ArrayList<>();
        for (BdInvbasdocEntity bdInvbasdocEntity : bdInvbasdocEntityList) {
            String rootAppPk = bdInvbasdocEntity.getInvcode()+"_"+bdInvbasdocEntity.getTs();
            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) {
                filterInvbasdocList.add(bdInvbasdocEntity);
            }

        }
        return filterInvbasdocList;
    }

    /**
     * U8C->存货基本档案自动分配全公司
     *
     * @param filterInvbasdocList
     */
    public void implement(List<BdInvbasdocEntity> filterInvbasdocList) {
        for (BdInvbasdocEntity bdInvbasdocEntity : filterInvbasdocList) {
            //创建日期
            String createtime = bdInvbasdocEntity.getCreatetime();

            //存货档案主键
            String pkInvbasdoc = bdInvbasdocEntity.getInvcode();

            String mapStr = "";
            String response = "";

            try {
                GoodsAutoAllotVO goodsAutoAllotVO = new GoodsAutoAllotVO();
                //存货基本档案主键
                goodsAutoAllotVO.setPk_invbasdoc(pkInvbasdoc);


                String jsonStr = JSONUtil.toJsonStr(goodsAutoAllotVO);
                mapStr = "{\"invbasdocvo\":["+jsonStr+"]}";

                ZTResult ztResult = pushU8CByApiCode.pushByCode(OverallConstant.getOverAllValue("bdinvclAllotCode"), mapStr);
                //两层判断,一层中台转发,一层u8c返回
                Attribute attribute = ztResult.getAttribute();

                if ("false".equals(ztResult.getFlag())) {
                    //转发失败
                    response=JSONUtil.toJsonStr(ztResult.getAttribute());
                    Assert.state(false, "丽知：U8C->存货基本档案自动分配全公司，中台转发失败,失败原因:{}", ztResult.getAttribute());
                }
                boolean isSuccess = false;
                if ("success".equals(attribute.getStatus())) {
                    isSuccess = true;
                    String data = attribute.getData();
                    System.out.println(data);
                }
                if (!isSuccess) {
                    Assert.state(false, "丽知：U8C->存货基本档案自动分配全公司 失败 接口返回结果：{} 接口入参:{}", attribute.getErrormsg(), mapStr);
                }

                //成功
                IntegrationTaskLivingDetailsEntity integrationTaskLivingDetailsEntity = new IntegrationTaskLivingDetailsEntity();
                integrationTaskLivingDetailsEntity.setNewState(ProfilesActiveConstant.LOG_STATUS_Y);
                integrationTaskLivingDetailsEntity.setRootAppNewData(mapStr);
                integrationTaskLivingDetailsEntity.setNewTransmitInfo(response);
                integrationTaskLivingDetailsEntity.setNewPushDate(new Date());
                integrationTaskLivingDetailsEntity.setBusinessDate(createtime);
                integrationTaskLivingDetailsEntity.setRootAppPk(pkInvbasdoc+"_"+bdInvbasdocEntity.getTs());
                integrationTaskLivingDetailsEntity.setRootAppBill(bdInvbasdocEntity.getInvcode());
                integrationTaskLivingDetailsEntity.setPluginId(getPluginId());
                saveOrUpdateBusinessLogUtil.saveOrUpdate(integrationTaskLivingDetailsEntity);
            } catch (Exception e) {
                logger.error("U8C->存货基本档案自动分配全公司implement(List<BdInvbasdocEntity> filterInvbasdocList)方法失败");
                //失败
                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(createtime);
                integrationTaskLivingDetailsEntity.setRootAppPk(pkInvbasdoc+"_"+bdInvbasdocEntity.getTs());
                integrationTaskLivingDetailsEntity.setRootAppBill(bdInvbasdocEntity.getInvcode());
                integrationTaskLivingDetailsEntity.setPluginId(getPluginId());
                saveOrUpdateBusinessLogUtil.saveOrUpdate(integrationTaskLivingDetailsEntity);
            }
        }
    }
}
