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.queryvo.CustdocRequestVo;
import com.hzya.frame.plugin.lets.resultvo.CbdocResultVo;
import com.hzya.frame.plugin.lets.u8cdto.CustdocEntityDto;
import com.hzya.frame.plugin.lets.u8cdto.DefdocRequestVo;
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.OfsShopDto;
import com.hzya.frame.ttxofs.dto.ofsBaseSearch.OfsShopReturnMessageDto;
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: 店铺->U8C客商档案
 */

public class ShopPluginInitializer extends PluginBaseEntity {
    Logger logger = LoggerFactory.getLogger(ShopPluginInitializer.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.ShopPluginInitializer";
    }

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

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

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


//    @Autowired
//    private IShopDao shopDao;

    @Autowired
    private SaveOrUpdateBusinessLogUtil saveOrUpdateBusinessLogUtil;
    @Autowired
    private IIntegrationTaskLivingDetailsDao iIntegrationTaskLivingDetailsDao;

    @Autowired
    private PushDataByU8cUtil pushDataByU8cUtil;

    @Autowired
    private OfsUnifiedService ofsUnifiedService;

    @Autowired
    private PushU8CByApiCode pushU8CByApiCode;


    @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(String startDate, String endDate) {
        try {
            Date business_start = DateUtil.parse(startDate);
            Date business_end = DateUtil.parse(endDate);
            String start = DateUtil.format(business_start, "yyyy-MM-dd") + " 00:00:00";
            String end = DateUtil.format(business_end, "yyyy-MM-dd") + " 23:59:59";

            OfsShopDto shopEntity = new OfsShopDto();
            shopEntity.setLastUpdated_start(start);
            shopEntity.setLastUpdated_end(end);
            shopEntity.setPageNo("1");

            List<OfsShopDto> list = queryfromofs(shopEntity);
            //过滤数据
            List<OfsShopDto> shopEntities = filterShopEntity(list);
            implementcustdoc(shopEntities);

            List<OfsShopDto> list1 = filterShopEntityDef(list);
            implementdef(list1);

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

    /**
     * 默认推送
     */
    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");


            OfsShopDto shopEntity = new OfsShopDto();
            shopEntity.setLastUpdated_start(startTimeStr);
            shopEntity.setLastUpdated_end(endTimeStr);
            shopEntity.setPageNo("1");
            shopEntity.setClientCode("LETS");
            List<OfsShopDto> list = queryfromofs(shopEntity);

            List<OfsShopDto> shopEntities = filterShopEntity(list);
            //同步到客商档案
            implementcustdoc(shopEntities);

            List<OfsShopDto> list1 = filterShopEntityDef(list);
            //同步到自定义档案
            implementdef(list1);

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


    /**
     * 按编码名称
     */
    public void startImplement(String code) {
        try {
            OfsShopDto shopEntity = new OfsShopDto();
            shopEntity.setBizCode(code);
            shopEntity.setClientCode("LETS");
            shopEntity.setPageNo("1");
            List<OfsShopDto> list = queryfromofs(shopEntity);
            //过滤数据
            List<OfsShopDto> shopEntities = filterShopEntity(list);
            //同步到客商档案
            implementcustdoc(shopEntities);
            List<OfsShopDto> list1 = filterShopEntityDef(list);
            //同步到自定义档案
            implementdef(list1);

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


    public void implementcustdoc(List<OfsShopDto> 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 (OfsShopDto shopEntity : shopEntityList) {
            String response = "";
            try {

                CustdocEntityDto parentvo = new CustdocEntityDto();
                CustdocRequestVo custdocRequestVo = new CustdocRequestVo();
                parentvo.setCustname(shopEntity.getName());
                parentvo.setCustshortname(shopEntity.getName());
//                parentvo.setPk_corp("0001");
//
//                parentvo.setPk_areacl("A");
                //业务编码
                parentvo.setDef1(shopEntity.getBizCode());
                custdocRequestVo.setParentvo(parentvo);
                //同步u8c
                ArrayList<CustdocRequestVo> list = new ArrayList<>();
                list.add(custdocRequestVo);
                HashMap<String, Object> param = new HashMap<>();

                param.put("cbdocvo", list);
                String jsonString = JSONObject.toJSONString(param);
//                 response = pushDataByU8cUtil.pushU8CByCode(OverallConstant.getOverAllValue("custdocSave"), jsonString);
                ZTResult ztResult = pushU8CByApiCode.pushByCode(OverallConstant.getOverAllValue("custdocSaveCode"), jsonString);

                Attribute attribute = ztResult.getAttribute();

                if ("false".equals(ztResult.getFlag())) {
                    //转发失败
                    response = JSONUtil.toJsonStr(ztResult.getAttribute());
                    Assert.state(false, "丽知：OFS店铺档案--->U8C客商档案，中台转发失败,失败原因:{}", ztResult.getAttribute());
                }


                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 = attribute.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(shopEntity.getBizCode());
                integrationTaskLivingDetailsEntity.setRootAppBill(shopEntity.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(shopEntity));
                integrationTaskLivingDetailsEntity.setNewTransmitInfo(ErrMessage);
                integrationTaskLivingDetailsEntity.setNewPushDate(new Date());
                integrationTaskLivingDetailsEntity.setBusinessDate(businessFormat);
                integrationTaskLivingDetailsEntity.setRootAppPk(shopEntity.getBizCode());
                integrationTaskLivingDetailsEntity.setRootAppBill(shopEntity.getName());
                integrationTaskLivingDetailsEntity.setPluginId(getPluginId());
                saveOrUpdateBusinessLogUtil.saveOrUpdate(integrationTaskLivingDetailsEntity);

            }
        }
    }


    public void implementdef(List<OfsShopDto> 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 (OfsShopDto shopEntity : shopEntityList) {
            String response = "";
            try {

                DefdocRequestVo defdocRequestVo = new DefdocRequestVo();
                defdocRequestVo.setDoccode(shopEntity.getBizCode());
                defdocRequestVo.setDocname(shopEntity.getName());
                defdocRequestVo.setPk_corp("0001");
                //店铺自定义档案主键
                defdocRequestVo.setPk_defdoclist("0001A210000000000XZX");
                //TOB C
                defdocRequestVo.setMemo(shopEntity.getBusiness());
                ArrayList<DefdocRequestVo> requestVos = new ArrayList<>();
                requestVos.add(defdocRequestVo);
                HashMap<String, List> map = new HashMap<>();
                map.put("defdoc", requestVos);

                //同步u8c
                String jsonString = JSONObject.toJSONString(map);
//                String response = pushDataByU8cUtil.pushU8CByCode(OverallConstant.getOverAllValue("bddefdoclistsaveCode"), jsonString);
                ZTResult ztResult = pushU8CByApiCode.pushByCode(OverallConstant.getOverAllValue("bddefdoclistsaveCode"), jsonString);
                Attribute attribute = ztResult.getAttribute();
                if ("false".equals(ztResult.getFlag())) {
                    //转发失败
                    response = JSONUtil.toJsonStr(ztResult.getAttribute());
                    Assert.state(false, "丽知：OFS店铺档案--->U8C自定义档案，中台转发失败,失败原因:{}", ztResult.getAttribute());
                }

                String taskNumber = null;
                boolean isSuccess = false;
                if ("success".equals(attribute.getStatus())) {

                    isSuccess = true;
//                    String string = attribute.getData();
//                    CbdocResultVo cbdocResultVo = JSONObject.parseObject(string, 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("defdoc" + shopEntity.getBizCode());
                integrationTaskLivingDetailsEntity.setRootAppBill(shopEntity.getName());
                integrationTaskLivingDetailsEntity.setPluginId(getPluginId());
                saveOrUpdateBusinessLogUtil.saveOrUpdate(integrationTaskLivingDetailsEntity);


            } catch (Exception e) {
                logger.error("丽知：OFS店铺档案--->自定义档案,implement()方法报错：", e);
                String ErrMessage = e.getMessage();
                IntegrationTaskLivingDetailsEntity integrationTaskLivingDetailsEntity = new IntegrationTaskLivingDetailsEntity();
                integrationTaskLivingDetailsEntity.setNewState(ProfilesActiveConstant.LOG_STATUS_N);
                integrationTaskLivingDetailsEntity.setRootAppNewData(JSONObject.toJSONString(shopEntity));
                integrationTaskLivingDetailsEntity.setNewTransmitInfo(ErrMessage);
                integrationTaskLivingDetailsEntity.setNewPushDate(new Date());
                integrationTaskLivingDetailsEntity.setBusinessDate(businessFormat);
                integrationTaskLivingDetailsEntity.setRootAppPk("defdoc" + shopEntity.getBizCode());
                integrationTaskLivingDetailsEntity.setRootAppBill(shopEntity.getName());
                integrationTaskLivingDetailsEntity.setPluginId(getPluginId());
                saveOrUpdateBusinessLogUtil.saveOrUpdate(integrationTaskLivingDetailsEntity);

            }
        }
    }

    public List<OfsShopDto> filterShopEntity(List<OfsShopDto> list) {
        Assert.notNull(list, "不能为空！");
        List<OfsShopDto> shopEntityList = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                OfsShopDto ofsShopDto = list.get(i);

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

    }


    public List<OfsShopDto> filterShopEntityDef(List<OfsShopDto> list) {
        Assert.notNull(list, "不能为空！");
        List<OfsShopDto> shopEntityList = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                OfsShopDto ofsShopDto = list.get(i);

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

    public List<OfsShopDto> queryfromofs(OfsShopDto shopEntity) {
        InterfaceParamByU8CApiDto interfaceParamDto = new InterfaceParamByU8CApiDto();
        interfaceParamDto.setApi("ofs.store.search");
        interfaceParamDto.setData(JSON.toJSONString(shopEntity));
        try {
            OfsShopReturnMessageDto unified = (OfsShopReturnMessageDto) ofsUnifiedService.unifiedByU8CApi(interfaceParamDto);
            List<OfsShopDto> list = unified.getData();
            return list;
        } catch (Exception e) {
            logger.error("丽知：OFS店铺档案查询失败，queryfromofs()方法报错：", e);
            return null;
        }
    }
}
