package com.hzya.frame.plugin.lets.plugin.adjust;

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.IIcGeneralHDao;
import com.hzya.frame.plugin.lets.entity.BdCorpEntity;
import com.hzya.frame.plugin.lets.entity.IcGeneralHEntity;
import com.hzya.frame.plugin.lets.u8cdto.IcGeneralAuditVO;
import com.hzya.frame.plugin.lets.u8cdto.ReusltStrDto;
import com.hzya.frame.plugin.lets.u8cdto.SpecialbillVO;
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.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;

/**
 * 组装自动生成的其他出库单自动审核。
 * 自定义项15：ZZ的单子,查询ic_general_h(其他出入库单)
 *
 */
public class OtherOutPluginInitializer extends PluginBaseEntity {
    Logger logger = LoggerFactory.getLogger(OtherOutPluginInitializer.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 "adjust.OtherOutPluginInitializer";
    }

    @Override
    public String getPluginName() {
        return "丽知：其他出库单自动审核";
    }

    @Override
    public String getPluginLabel() {
        return "丽知：其他出库单自动审核";
    }

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

    @Autowired
    private OfsUnifiedService ofsUnifiedService;
    @Autowired
    private IIcGeneralHDao iIcGeneralHDao;
    @Autowired
    private QueryU8CEntityUtil queryU8CEntityUtil;

    @Override
    public String getPluginType() {
        return "1";
    }
    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(){
        //获取当前时间
        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");

        IcGeneralHEntity icGeneralHEntity = new IcGeneralHEntity();
        icGeneralHEntity.setVuserdef15("ZZ");
        icGeneralHEntity.setCbilltypecode("4I");//其他出库单
        icGeneralHEntity.setTmaketime_start(startTimeStr);
        icGeneralHEntity.setTmaketime_start(endTimeStr);
        icGeneralHEntity.setDataSourceCode(ProfilesActiveConstant.LETS_DATE_SOURCE);
        List<IcGeneralHEntity> icGeneralHList = iIcGeneralHDao.query(icGeneralHEntity);
        if(icGeneralHList.size()==0){
            return;
        }
        //过滤成功日志
        List<IcGeneralHEntity> filterIcGeneralHList=filterData(icGeneralHList);
        if (filterIcGeneralHList.size() == 0) {
            return;
        }

        //推送
        implement(filterIcGeneralHList);




    }
    public void start(String vbillcode){
        try {
            IcGeneralHEntity icGeneralHEntity = new IcGeneralHEntity();
            icGeneralHEntity.setVuserdef15("ZZ");
            icGeneralHEntity.setCbilltypecode("4I");//其他出库单
            icGeneralHEntity.setVbillcode(vbillcode);
            icGeneralHEntity.setDataSourceCode(ProfilesActiveConstant.LETS_DATE_SOURCE);
            List<IcGeneralHEntity> icGeneralHList = iIcGeneralHDao.query(icGeneralHEntity);
            if(icGeneralHList.size()==0){
                Assert.state(false, "丽知：其他出库单:{},查询到该单据", vbillcode);
            }
            //过滤成功日志
            List<IcGeneralHEntity> filterIcGeneralHList=filterData(icGeneralHList);
            if (filterIcGeneralHList.size() == 0) {
                Assert.state(false, "丽知：其他出库单:{},自动审核已被推送成功，请勿重新推送", vbillcode);
            }

            //推送
            implement(filterIcGeneralHList);
        }catch (Exception e){
            logger.error("丽知：其他出库单自动审核,start()方法报错："+e);
        }

    }
    public void start(String startTime, String endTime){
        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";

        IcGeneralHEntity icGeneralHEntity = new IcGeneralHEntity();
        icGeneralHEntity.setVuserdef15("ZZ");
        icGeneralHEntity.setCbilltypecode("4I");//其他出库单
        icGeneralHEntity.setTmaketime_start(start);
        icGeneralHEntity.setTmaketime_start(end);
        icGeneralHEntity.setDataSourceCode(ProfilesActiveConstant.LETS_DATE_SOURCE);
        List<IcGeneralHEntity> icGeneralHList = iIcGeneralHDao.query(icGeneralHEntity);
        if(icGeneralHList.size()==0){
            Assert.state(false, "丽知：其他出库单，根据日期期间[开始时间]-[结束时间]：{}-{}，未查询到其他出库单", startTime, endTime);
        }
        //过滤成功日志
        List<IcGeneralHEntity> filterIcGeneralHList=filterData(icGeneralHList);
        if (filterIcGeneralHList.size() == 0) {
            Assert.state(false, "丽知：其他出库单，根据日期期间[开始时间]-[结束时间]：{}-{}，该期间其他出库单已被推送成功，请勿重新推送", startTime, endTime);
        }

        //推送
        implement(filterIcGeneralHList);

    }

    /**
     * 根据单据号过滤
     * vbillcode+pk_corp
     * @param icGeneralHList
     * @return
     */
    public List<IcGeneralHEntity> filterData(List<IcGeneralHEntity> icGeneralHList){
        List<IcGeneralHEntity> filterIcGeneralHList=new ArrayList<>();
        for (IcGeneralHEntity icGeneralHEntity : icGeneralHList) {
            String rootAppPk =icGeneralHEntity.getVbillcode()+"_"+icGeneralHEntity.getPkCorp();
            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) {
                filterIcGeneralHList.add(icGeneralHEntity);
            }
        }
        if (filterIcGeneralHList.size() == 0) {
            return null;
        }
        return filterIcGeneralHList;
    }


    public void implement(List<IcGeneralHEntity> filterIcGeneralHList){
        for (IcGeneralHEntity icGeneralHEntity : filterIcGeneralHList) {

            String mapStr = "";
            String format = icGeneralHEntity.getDbilldate();
            String response = "";
            String ofsCode = "";

            try {
                System.out.println(icGeneralHEntity);

                IcGeneralAuditVO icGeneralAuditVO = new IcGeneralAuditVO();
                IcGeneralAuditVO.QueryInfo queryInfo = new IcGeneralAuditVO.QueryInfo();

                //单据号
                queryInfo.setBillcode(icGeneralHEntity.getVbillcode());
                //公司
                BdCorpEntity bdCorpEntity = queryU8CEntityUtil.queryBdCorpByPkCorp(icGeneralHEntity.getPkCorp());
                if (bdCorpEntity == null) {
                    Assert.state(false,"查询公司主键：{}，失败。请检查公司主键",icGeneralHEntity.getPkCorp());
                }
                queryInfo.setCorp(bdCorpEntity.getUnitcode());

                //审核人
                IcGeneralAuditVO.SignInfo signInfo = new IcGeneralAuditVO.SignInfo();
                signInfo.setCoperator(OverallConstant.getOverAllValue("u8cApiZdrCode"));

                icGeneralAuditVO.setQueryInfo(queryInfo);
                icGeneralAuditVO.setSignInfo(signInfo);

//                mapStr="{"+ JSONUtil.toJsonStr(icGeneralAuditVO)+"}";
                mapStr=JSONUtil.toJsonStr(icGeneralAuditVO);
                System.out.println(mapStr);

                //推送
                ZTResult ztResult = pushU8CByApiCode.pushByCode(OverallConstant.getOverAllValue("otheroutsignCode"), mapStr);
                //两层判断,一层中台转发,一层u8c返回
                if ("false".equals(ztResult.getFlag())) {
                    //转发失败
                    response = JSONUtil.toJsonStr(ztResult.getMsg());
                    Assert.state(false, "丽知：其他出库单自动审核，中台转发失败,失败原因:{}", ztResult.getAttribute());
                }
                Attribute attribute = ztResult.getAttribute();
                System.out.println(attribute);
                boolean isSuccess = false;
                if ("success".equals(attribute.getStatus())) {
                    isSuccess = true;
                }
                if (!isSuccess) {
                    Assert.state(false, "推送U8C--> 丽知：其他出库单自动审核 失败 接口返回结果：{} 接口入参:{}", response, mapStr);
                }

                //成功
                IntegrationTaskLivingDetailsEntity integrationTaskLivingDetailsEntity = new IntegrationTaskLivingDetailsEntity();
                integrationTaskLivingDetailsEntity.setNewState(ProfilesActiveConstant.LOG_STATUS_Y);
                integrationTaskLivingDetailsEntity.setRootAppNewData(mapStr);
                integrationTaskLivingDetailsEntity.setNewTransmitInfo(response);
                integrationTaskLivingDetailsEntity.setNewPushDate(new Date());
                integrationTaskLivingDetailsEntity.setBusinessDate(format);
                integrationTaskLivingDetailsEntity.setRootAppPk(icGeneralHEntity.getVbillcode()+"_"+icGeneralHEntity.getPkCorp());
                integrationTaskLivingDetailsEntity.setRootAppBill(icGeneralHEntity.getVbillcode());
                integrationTaskLivingDetailsEntity.setPluginId(getPluginId());
                saveOrUpdateBusinessLogUtil.saveOrUpdate(integrationTaskLivingDetailsEntity);

            }catch (Exception e){
                e.printStackTrace();
                logger.error("推送U8C--> 丽知：其他出库单自动审核失败，失败原因：" + e);

                //失败
                ReusltStrDto reusltStrDto = JSON.parseObject(response, ReusltStrDto.class);
                String ErrMessage = "推送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(icGeneralHEntity.getVbillcode()+"_"+icGeneralHEntity.getPkCorp());
                integrationTaskLivingDetailsEntity.setRootAppBill(icGeneralHEntity.getVbillcode());
                integrationTaskLivingDetailsEntity.setPluginId(getPluginId());
                saveOrUpdateBusinessLogUtil.saveOrUpdate(integrationTaskLivingDetailsEntity);
            }
        }
    }
}
