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 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.IBdCubasdocDao;
import com.hzya.frame.plugin.lets.entity.BdCorpEntity;
import com.hzya.frame.plugin.lets.entity.BdCubasdocEntity;
import com.hzya.frame.plugin.lets.entity.BdInvbasdocEntity;
import com.hzya.frame.plugin.lets.queryvo.CustDocAssginVo;
import com.hzya.frame.plugin.lets.queryvo.CustdocRequestVo;
import com.hzya.frame.plugin.lets.resultvo.CbdocResultVo;
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.dto.ofsBaseSearch.OfsShopDto;
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;

/**
 * @Author
 * @Date 2024/8/12 13:57
 * @PackageName:com.hzya.frame.plugin.lets.plugin.base
 * @ClassName: CustdocAutoAllotPluginInitializer
 * @Description: 客商档案自动分配
 */
public class CustdocAutoAllotPluginInitializer extends PluginBaseEntity {

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

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

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

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

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

    @Override
    public JsonResultEntity executeBusiness(JSONObject requestJson) throws Exception {
        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 integration_task_living_details_id = (String) requestJson.get("integration_task_living_details_id");
            IntegrationTaskLivingDetailsEntity integrationTaskLivingDetailsEntity = saveOrUpdateBusinessLogUtil.queryIntegrationTaskLivingDetailsEntity(integration_task_living_details_id);
            start(integrationTaskLivingDetailsEntity.getRootAppPk());
        } else if (ProfilesActiveConstant.LETS_PROFILES_ACTIVE.equals(prod)) {
            start();
        }
        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");

            //查询要分配的客商
            BdCubasdocEntity bdCubasdocEntity = new BdCubasdocEntity();
            bdCubasdocEntity.setDataSourceCode(ProfilesActiveConstant.LETS_DATE_SOURCE);
            bdCubasdocEntity.setModifytime_start_time(startTimeStr);
            bdCubasdocEntity.setModifytime_end_time(endTimeStr);

            List<BdCubasdocEntity> list = bdCubasdocDao.query(bdCubasdocEntity);
            if (list == null || list.isEmpty()) {
                return;
            }
            List<BdCubasdocEntity> requestVoList = filterShopEntity(list);
            if (requestVoList == null || requestVoList.isEmpty()) {
                return;
            }
            //推送：自动分配
            implement(requestVoList);

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


    /**
     * 按客商基本档案code
     */
    public void start(String code) {
        try {
            BdCubasdocEntity bdCubasdocEntity = new BdCubasdocEntity();
//            bdInvbasdocEntity.setPkInvbasdoc(invcode);
            bdCubasdocEntity.setCustcode(code);
            bdCubasdocEntity.setDataSourceCode(ProfilesActiveConstant.LETS_DATE_SOURCE);
            List<BdCubasdocEntity> query = bdCubasdocDao.query(bdCubasdocEntity);
            if (query.size() == 0) {
                Assert.state(false, "U8C->客商基本档案自动分配全公司,客商基本档案编码：{}，不存在。", code);
            }
            //过滤日志
            List<BdCubasdocEntity> list = filterShopEntity(query);
            if (list.size() == 0 || list == null) {
                Assert.state(false, "U8C->客商基本档案自动分配全公司,客商基本档案编码：{}，已被分配,请检查。", code);
            }
            //推送：自动分配
            implement(list);

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

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

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


    /**
     * 查询客商基本档案
     *
     * @return
     */
    private List<CustdocRequestVo> queryCustDoc() {
        List<CustdocRequestVo> list = null;
        try {
            String data = pushDataByU8cUtil.pushU8CByCode(OverallConstant.getOverAllValue("custdocQuery"), "{}");
            CbdocResultVo cbdocResultVo = JSONObject.parseObject(data, CbdocResultVo.class);
            String datastring = cbdocResultVo.getData();
            Map map = JSONObject.parseObject(datastring, Map.class);
            Object o = map.get("datas");
            String jsonString = JSONObject.toJSONString(o);
            list = JSONObject.parseArray(jsonString, CustdocRequestVo.class);

//            custdocRequestVos = filterShopEntity(list);
        } catch (Exception e) {
            logger.error("丽知：U8C->客商基本档案自动分配全公司,查询客商基本档案失败", e);
        }
        return list;
    }

    //过滤已经分配的
    public List<BdCubasdocEntity> filterShopEntity(List<BdCubasdocEntity> list) {
        Assert.notNull(list, "不能为空！");
        List<BdCubasdocEntity> shopEntityList = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                BdCubasdocEntity requestVo = list.get(i);
                String custcode = requestVo.getCustcode();
                if (custcode != null && !"".equals(custcode)) {
                    boolean isExis = true;
                    IntegrationTaskLivingDetailsEntity integrationTaskLivingDetailsEntity = new IntegrationTaskLivingDetailsEntity();
                    integrationTaskLivingDetailsEntity.setRootAppPk(custcode);
                    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) {
                        shopEntityList.add(requestVo);
                    }
                }
            }
        }
        return shopEntityList;
    }


    /**
     * U8C->客商基本档案自动分配全公司
     */
    public void implement(List<BdCubasdocEntity> list) {

        for (BdCubasdocEntity bdCubasdocEntity : list) {
            String assginjsonString = "";
            String custcode = bdCubasdocEntity.getCustcode();
            String createtime = bdCubasdocEntity.getCreatetime();
            try {

                ArrayList<CustDocAssginVo> assginvolist = new ArrayList<>();
                List<BdCorpEntity> bdCorpEntities = null;
                //查询公司档案
                try {
//                    String corpresponse = pushDataByU8cUtil.pushU8CByCode(OverallConstant.getOverAllValue("bdcorpQuery"), "{}");
                    ZTResult ztResult = pushU8CByApiCode.pushByCode(OverallConstant.getOverAllValue("bdcorpQueryCode"), "{}");
//                    CbdocResultVo cbdocResultVo = JSONObject.parseObject(corpresponse, CbdocResultVo.class);
                    Attribute attribute = ztResult.getAttribute();
                    if (!"success".equals(attribute.getStatus())) {
                        Assert.state(false, "查询公司档案失败");
                    }
                    String data = attribute.getData();
                    Map map = JSONObject.parseObject(data, Map.class);
                    Object o = map.get("datas");
                    bdCorpEntities = JSONObject.parseArray(JSON.toJSONString(o), BdCorpEntity.class);


                } catch (Exception e) {
                    throw new RuntimeException(e);
                }

                for (BdCorpEntity bdCorpEntity : bdCorpEntities) {
                    CustDocAssginVo custDocAssginVo = new CustDocAssginVo();
                    custDocAssginVo.setPk_cubasdoc(custcode);
                    //TODO
//                    custDocAssginVo.setCustprop(custprop);
                    custDocAssginVo.setPk_corp(bdCorpEntity.getUnitcode());
                    assginvolist.add(custDocAssginVo);
                }


                HashMap<String, List> map = new HashMap<>();
                map.put("custbasvo", assginvolist);
                assginjsonString = JSONObject.toJSONString(map);
//                String response = pushDataByU8cUtil.pushU8CByCode(OverallConstant.getOverAllValue("custdocAssign"), assginjsonString);
                ZTResult ztResult = pushU8CByApiCode.pushByCode(OverallConstant.getOverAllValue("custdocAssignCode"), assginjsonString);
                Attribute attribute = ztResult.getAttribute();
                if ("false".equals(ztResult.getFlag())) {
                    //转发失败
                    Assert.state(false, "丽知：U8C客商档案分配，中台转发失败,失败原因:{}", attribute.getErrormsg());
                }

                boolean isSuccess = false;
                if ("success".equals(attribute.getStatus())) {
                    isSuccess = true;
//                    ReusltStrDto reusltStrDto = JSON.parseObject(attribute.getData(), ReusltStrDto.class);
                }
                if (!isSuccess) {
                    Assert.state(false, "推送U8C--> U8C->客商基本档案自动分配全公司 失败 接口返回结果：{} 接口入参:{}", attribute.getErrormsg(), assginjsonString);
                }
                //成功
                IntegrationTaskLivingDetailsEntity integrationTaskLivingDetailsEntity = new IntegrationTaskLivingDetailsEntity();
                integrationTaskLivingDetailsEntity.setNewState(ProfilesActiveConstant.LOG_STATUS_Y);
                integrationTaskLivingDetailsEntity.setRootAppNewData(assginjsonString);
                integrationTaskLivingDetailsEntity.setNewTransmitInfo(attribute.getData());
                integrationTaskLivingDetailsEntity.setNewPushDate(new Date());
                integrationTaskLivingDetailsEntity.setBusinessDate(createtime);
                integrationTaskLivingDetailsEntity.setRootAppPk(custcode);
                integrationTaskLivingDetailsEntity.setRootAppBill(custcode);
                integrationTaskLivingDetailsEntity.setPluginId(getPluginId());
                saveOrUpdateBusinessLogUtil.saveOrUpdate(integrationTaskLivingDetailsEntity);
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("U8C->客商基本档案自动分配全公司implement(List<BdInvbasdocEntity> filterInvbasdocList)方法失败");
                //失败
                String ErrMessage = e.getMessage();
                IntegrationTaskLivingDetailsEntity integrationTaskLivingDetailsEntity = new IntegrationTaskLivingDetailsEntity();
                integrationTaskLivingDetailsEntity.setNewState(ProfilesActiveConstant.LOG_STATUS_N);
                integrationTaskLivingDetailsEntity.setRootAppNewData(assginjsonString);
                integrationTaskLivingDetailsEntity.setNewTransmitInfo(ErrMessage);
                integrationTaskLivingDetailsEntity.setNewPushDate(new Date());
                integrationTaskLivingDetailsEntity.setBusinessDate(createtime);
                integrationTaskLivingDetailsEntity.setRootAppPk(custcode);
                integrationTaskLivingDetailsEntity.setRootAppBill(custcode);
                integrationTaskLivingDetailsEntity.setPluginId(getPluginId());
                saveOrUpdateBusinessLogUtil.saveOrUpdate(integrationTaskLivingDetailsEntity);
            }
        }
    }

    private void updateDoc(CustdocRequestVo custdocRequestVo) {
        //已分配
        String pkCubasdoc = custdocRequestVo.getParentvo().getPk_cubasdoc();
        String createtime = custdocRequestVo.getParentvo().getCreatetime();

        custdocRequestVo.getParentvo().setDef10("Y");
        ArrayList<CustdocRequestVo> requestVos = new ArrayList<>();
        requestVos.add(custdocRequestVo);
        HashMap<String, List> map = new HashMap<>();
        map.put("custbasvo", requestVos);
        String data = JSONObject.toJSONString(map);
        try {
            String response = pushDataByU8cUtil.pushU8CByCode(OverallConstant.getOverAllValue("custdocUpdate"), data);

            boolean isSuccess = false;
            if (response != null && !"".equals(response)) {
                ReusltStrDto reusltStrDto = JSON.parseObject(response, ReusltStrDto.class);
                if ("success".equals(reusltStrDto.getStatus())) {
                    isSuccess = true;
                }
            }
            if (!isSuccess) {
                Assert.state(false, "推送U8C--> U8C->客商基本档案自动分配全公司 失败 接口返回结果：{} 接口入参:{}", response, data);
            }
            //成功
            IntegrationTaskLivingDetailsEntity integrationTaskLivingDetailsEntity = new IntegrationTaskLivingDetailsEntity();
            integrationTaskLivingDetailsEntity.setNewState(ProfilesActiveConstant.LOG_STATUS_Y);
            integrationTaskLivingDetailsEntity.setRootAppNewData(data);
            integrationTaskLivingDetailsEntity.setNewTransmitInfo(response);
            integrationTaskLivingDetailsEntity.setNewPushDate(new Date());
            integrationTaskLivingDetailsEntity.setBusinessDate(createtime);
            integrationTaskLivingDetailsEntity.setRootAppPk(pkCubasdoc);
            integrationTaskLivingDetailsEntity.setRootAppBill(pkCubasdoc);
            integrationTaskLivingDetailsEntity.setPluginId(getPluginId());
            saveOrUpdateBusinessLogUtil.saveOrUpdate(integrationTaskLivingDetailsEntity);

        } catch (Exception e) {
            //失败
            logger.error("U8C->客商基本档案更新updateDoc(CustdocRequestVo custdocRequestVo)方法失败");
            String ErrMessage = e.getMessage();
            IntegrationTaskLivingDetailsEntity integrationTaskLivingDetailsEntity = new IntegrationTaskLivingDetailsEntity();
            integrationTaskLivingDetailsEntity.setNewState(ProfilesActiveConstant.LOG_STATUS_N);
            integrationTaskLivingDetailsEntity.setRootAppNewData(data);
            integrationTaskLivingDetailsEntity.setNewTransmitInfo(ErrMessage);
            integrationTaskLivingDetailsEntity.setNewPushDate(new Date());
            integrationTaskLivingDetailsEntity.setBusinessDate(createtime);
            integrationTaskLivingDetailsEntity.setRootAppPk(pkCubasdoc);
            integrationTaskLivingDetailsEntity.setRootAppBill(pkCubasdoc);
            integrationTaskLivingDetailsEntity.setPluginId(getPluginId());
            saveOrUpdateBusinessLogUtil.saveOrUpdate(integrationTaskLivingDetailsEntity);
        }
    }
}

