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.queryvo.BankVo;
import com.hzya.frame.plugin.lets.queryvo.CustdocRequestVo;

import com.hzya.frame.plugin.lets.resultvo.CbdocResultVo;
import com.hzya.frame.plugin.lets.u8cdto.CustdocEntityDto;
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.InterfaceParamByU8CApiDto;

import com.hzya.frame.ttxofs.dto.ofsBaseSearch.OfsSupplierDto;
import com.hzya.frame.ttxofs.dto.ofsBaseSearch.OfsSupplierReturnMessageDto;
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.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author
 * @Date 2024/8/6 14:36
 * @PackageName:com.hzya.frame.plugin.lets.plugin.base
 * @ClassName: ShopPluginInitializer
 * @Description: 供应商档案->客商档案
 */
public class SupplierPluginInitializer extends PluginBaseEntity {
    Logger logger = LoggerFactory.getLogger(SupplierPluginInitializer.class);

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

    @Autowired
    private OfsUnifiedService ofsUnifiedService;
    @Autowired
    private PushU8CByApiCode pushU8CByApiCode;

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

    @Override
    public void destroy() {
        logger.info(getPluginLabel() + "执行销毁方法destroy()");
    }

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

    @Override
    public String getPluginName() {
        return "丽知：OFS供应商档案--->U8C客商档案";
    }

    @Override
    public String getPluginLabel() {
        return "丽知：OFS供应商档案--->U8C客商档案";
    }

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


    @Autowired
    private SaveOrUpdateBusinessLogUtil saveOrUpdateBusinessLogUtil;

    @Autowired
    private IIntegrationTaskLivingDetailsDao iIntegrationTaskLivingDetailsDao;


    @Autowired
    private PushDataByU8cUtil pushDataByU8cUtil;

    @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], "结束时间不能为空");
                startImplement(split[0], split[1]);
            }
        } else if (requestJson != null && ProfilesActiveConstant.TYPE_VBILLCODE.equals(requestJson.get("type"))) {
            if (param != null && !"".equals(param)) {
                startImplement(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);
            startImplement(integrationTaskLivingDetailsEntity.getRootAppPk());
        } else if (ProfilesActiveConstant.LETS_PROFILES_ACTIVE.equals(prod)) {
            startImplement();
        }
        return null;
    }


    /**
     * 默认推送
     */
    public void startImplement() {
        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");

            OfsSupplierDto supplierEntity = new OfsSupplierDto();
            supplierEntity.setClientCode("LETS");
            supplierEntity.setPageNo("1");
            supplierEntity.setLastUpdated_start(startTimeStr);
            supplierEntity.setLastUpdated_end(endTimeStr);

            List<OfsSupplierDto> list = queryfromofs(supplierEntity);
            //过滤数据
            List<OfsSupplierDto> supplierDtoList = filterSupplierEntity(list);
            //执行
            implement(supplierDtoList);

        } catch (Exception e) {
            logger.error("丽知：OFS供应商档案--->U8C客商档案,startImplement()方法报错：", e);
        }
    }


    /**
     * 按编码名称
     */
    public void startImplement(String code) {
        Assert.notNull(code, "code不能为空");
        try {
            OfsSupplierDto supplierEntity = new OfsSupplierDto();
            supplierEntity.setBizCode(code);
            supplierEntity.setClientCode("LETS");
            supplierEntity.setPageNo("1");

            List<OfsSupplierDto> list = queryfromofs(supplierEntity);
            //过滤数据
            List<OfsSupplierDto> supplierDtoList = filterSupplierEntity(list);
            //执行
            implement(supplierDtoList);

        } catch (Exception e) {
            logger.error("丽知：OFS供应商档案--->U8C客商档案,startImplement(String code)方法报错：", e);
        }
    }

    /**
     * 按时间区间
     */
    public void startImplement(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";
            OfsSupplierDto supplierDto = new OfsSupplierDto();
            supplierDto.setLastUpdated_start(start);
            supplierDto.setLastUpdated_end(end);
            supplierDto.setClientCode("LETS");
            supplierDto.setPageNo("1");
            List<OfsSupplierDto> queryfromofs = queryfromofs(supplierDto);
            //过滤数据
            List<OfsSupplierDto> supplierDtoList = filterSupplierEntity(queryfromofs);
            //执行
            implement(supplierDtoList);
        } catch (Exception e) {
            logger.error("丽知：OFS供应商档案--->U8C客商档案,startImplement(String startTime, String endTime)方法报错：", e);
        }
    }

    public void implement(List<OfsSupplierDto> shopEntityList) {

        Assert.notNull(shopEntityList, "shopEntityList不能为空");
        //业务时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(System.currentTimeMillis());
        String businessFormat = sdf.format(date);
        for (OfsSupplierDto supplierEntity : shopEntityList) {
            CustdocEntityDto parentvo = new CustdocEntityDto();
            BankVo bankVo = new BankVo();
            CustdocRequestVo CustdocEntityDto = new CustdocRequestVo();
            try {
                //设置parentvo
                parentvo.setCustname(supplierEntity.getName());
                parentvo.setCustshortname(supplierEntity.getName());

                parentvo.setDef1(supplierEntity.getBizCode());

                CustdocEntityDto.setParentvo(parentvo);

                // 同步u8c
                HashMap<String, Object> param = new HashMap<>();
                param.put("cbdocvo", CustdocEntityDto);

                String jsonString = JSONObject.toJSONString(param);


//                String response = pushDataByU8cUtil.pushU8CByCode(OverallConstant.getOverAllValue("custdocSave"), jsonString);
                ZTResult ztResult = pushU8CByApiCode.pushByCode(OverallConstant.getOverAllValue("custdocSaveCode"), jsonString);
                //两层判断,一层中台转发,一层u8c返回
                Attribute attribute = ztResult.getAttribute();
                if ("false".equals(ztResult.getFlag())) {
                    //转发失败
                    Assert.state(false, "丽知：OFS供应商档案分类--->U8C客商档案分类.中台转发失败,失败原因:{}", attribute.getErrormsg());
                }


                String taskNumber = null;
                boolean isSuccess = false;
                if ("success".equals(attribute.getStatus())) {
                    isSuccess = true;
//                    CbdocResultVo cbdocResultVo = JSONObject.parseObject(attribute.getData(), CbdocResultVo.class);
//                    taskNumber = cbdocResultVo.getTaskNumber();
//                    String data = cbdocResultVo.getData();
                }
                if (!isSuccess) {
                    Assert.state(false, "推送U8C，原因：{} 接口入参:{}", attribute.getErrormsg(), jsonString);
                }
                // 根据返回结果记录日志
                //成功
                IntegrationTaskLivingDetailsEntity integrationTaskLivingDetailsEntity = new IntegrationTaskLivingDetailsEntity();
                integrationTaskLivingDetailsEntity.setNewState(ProfilesActiveConstant.LOG_STATUS_Y);
                integrationTaskLivingDetailsEntity.setRootAppNewData(jsonString);
                integrationTaskLivingDetailsEntity.setNewTransmitInfo(attribute.getData());
                integrationTaskLivingDetailsEntity.setNewPushDate(new Date());
                integrationTaskLivingDetailsEntity.setBusinessDate(businessFormat);
                integrationTaskLivingDetailsEntity.setRootAppPk(supplierEntity.getBizCode());
                integrationTaskLivingDetailsEntity.setRootAppBill(supplierEntity.getName());
                integrationTaskLivingDetailsEntity.setPluginId(getPluginId());
                saveOrUpdateBusinessLogUtil.saveOrUpdate(integrationTaskLivingDetailsEntity);


            } catch (Exception e) {
                logger.error("丽知：OFS供应商档案--->U8C客商档案,implement()方法报错：", e);
                String ErrMessage = e.getMessage();
                IntegrationTaskLivingDetailsEntity integrationTaskLivingDetailsEntity = new IntegrationTaskLivingDetailsEntity();
                integrationTaskLivingDetailsEntity.setNewState(ProfilesActiveConstant.LOG_STATUS_N);
                integrationTaskLivingDetailsEntity.setRootAppNewData(JSONObject.toJSONString(CustdocEntityDto));
                integrationTaskLivingDetailsEntity.setNewTransmitInfo(ErrMessage);
                integrationTaskLivingDetailsEntity.setNewPushDate(new Date());
                integrationTaskLivingDetailsEntity.setBusinessDate(businessFormat);
                integrationTaskLivingDetailsEntity.setRootAppPk(supplierEntity.getBizCode());
                integrationTaskLivingDetailsEntity.setRootAppBill(supplierEntity.getName());
                integrationTaskLivingDetailsEntity.setPluginId(getPluginId());
                saveOrUpdateBusinessLogUtil.saveOrUpdate(integrationTaskLivingDetailsEntity);

            }
        }
    }

    //过滤数据
    public List<OfsSupplierDto> filterSupplierEntity(List<OfsSupplierDto> list) {

        Assert.notNull(list, "不能为空！");

        List<OfsSupplierDto> supplierDtoList = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                OfsSupplierDto ofsSupplierDto = list.get(i);

                if (ofsSupplierDto.getBizCode() != null && !"".equals(ofsSupplierDto.getBizCode().trim())) {
                    boolean isExis = true;
                    IntegrationTaskLivingDetailsEntity integrationTaskLivingDetailsEntity = new IntegrationTaskLivingDetailsEntity();
                    integrationTaskLivingDetailsEntity.setRootAppPk(ofsSupplierDto.getBizCode());
                    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) {
                        supplierDtoList.add(ofsSupplierDto);
                    }
                }
            }
        }
        return supplierDtoList;
    }

    public List<OfsSupplierDto> queryfromofs(OfsSupplierDto supplierEntity) {
        InterfaceParamByU8CApiDto interfaceParamDto = new InterfaceParamByU8CApiDto();
        interfaceParamDto.setApi("ofs.vendor.search");
        interfaceParamDto.setData(JSON.toJSONString(supplierEntity));
        try {
            OfsSupplierReturnMessageDto unified = (OfsSupplierReturnMessageDto) ofsUnifiedService.unifiedByU8CApi(interfaceParamDto);
            List<OfsSupplierDto> list = unified.getData();
            return list;
        } catch (Exception e) {
            logger.error("丽知：OFS供应商档案查询失败,queryfromofs()方法报错：", e);
            return null;
        }
    }
}
