package com.hzya.frame.seeyon.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hzya.frame.seeyon.entity.OAWorkflowEventDataEntity;
import com.hzya.frame.seeyon.service.ISeeyonExtService;
import com.hzya.frame.seeyon.util.OAU8Util;
import com.hzya.frame.sysnew.application.entity.SysExtensionApiEntity;
import com.hzya.frame.sysnew.integtationTaskLivingDetails.entity.IntegrationTaskLivingDetailsEntity;
import com.hzya.frame.sysnew.integtationTaskLivingDetails.service.IIntegrationTaskLivingDetailsService;
import com.hzya.frame.sysnew.messageManageLog.entity.SysMessageManageLogEntity;
import com.hzya.frame.sysnew.messageManageLog.entity.SysMessageManageLogStatusEnum;
import com.hzya.frame.uuid.UUIDLong;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description seeyon扩展类
 * @Author xiangerlin
 * @Date 2024/5/14 14:04
 **/
@Service(value = "seeyonExt")
public class SeeyonExtServiceImpl implements ISeeyonExtService {


    Logger logger = LogManager.getLogger(getClass());

    @Autowired
    private IIntegrationTaskLivingDetailsService taskLivingDetailsService;

    /**
     * 英德赛 OA档案传U8
     * 根据不同formApp来调U8不同接口
     * @Since 3.0
     * @param entity
     * @return
     */
    @Override
    public SysExtensionApiEntity ydcSeeyon2u8(SysExtensionApiEntity entity) {
        String bodys = entity.getBodys();
        if (StrUtil.isNotEmpty(bodys)){
            try {
                OAWorkflowEventDataEntity dataEntity = JSON.parseObject(bodys,OAWorkflowEventDataEntity.class);
                String businessDataStr = dataEntity.getBusinessDataStr();//oa表单参数
                JSONObject businessData = JSON.parseObject(businessDataStr);
                String formApp = dataEntity.getFormApp();
                SysExtensionApiEntity param = new SysExtensionApiEntity();
                Map<String, String> headerMap = entity.getHeaders();
                JSONObject hzyaExtData = dataEntity.getHzyaExtData();//扩展参数
                if (null == hzyaExtData){
                    hzyaExtData = new JSONObject();
                }
                //根据forApp组装不同参数
                switch (formApp){
                    case "-8691606453890363968"://
                        hzyaExtData.put("billCode", "cunhuoabc123456");
                        getInventory(businessData,param);
                        break;
                    case "6223456019738676230":
                        getSupplier(businessData,param,hzyaExtData);
                        break;
                    case "-9122508232154527168":
                        getCustomer(businessData,param,hzyaExtData);
                        break;
                    default:
                        param.setBodys("未匹配到表单！当前formID："+ formApp);
                        logger.error("未匹配到表单！当前formID："+formApp);
                }
                headerMap.put("hzyaExtData", JSON.toJSONString(hzyaExtData));
                return param;
            }catch (Exception e){
                e.printStackTrace();
                logger.error("执行英德赛OA存货同步U8接口报错：{}", e);
            }
        }
        return null;
    }

    /**
     * 回调方法
     * @Since 3.0
     * @param logEntity
     */
    @Override
    public void ydcSeeyon2u8CallBack(SysMessageManageLogEntity logEntity) {


        //在这里记录日志
        JSONObject targetData = JSON.parseObject(logEntity.getTargetData());//这个对象里的body是 发送到u8的请求报文
        JSONObject sourceData = JSON.parseObject(logEntity.getSourceData());
        JSONObject sourceHeaders = sourceData.getJSONObject("header");//源数据header
        JSONObject sourceBody = sourceData.getJSONObject("body");//源数据body
        JSONObject hzyaExtData = sourceHeaders.getJSONObject("hzyaExtData");
        JSONArray formMainIds = new JSONArray();
        formMainIds.add(sourceBody.getString("id"));
        JSONObject param = new JSONObject();
        String formApp = sourceBody.getString("formApp");
        param.put("formAppId",formApp);
        param.put("formMainIds",formMainIds);
        param.put("dataSourceCode","ht_oa_sqlserver");
        param.put("eventType",sourceBody.getString("eventType"));

        //把返回的单号更新到oa档案表
        String sql = "";
        switch (formApp){
            case "-8691606453890363968"://存货
                sql = "";
                break;
            case "6223456019738676230"://供应商
                sql = "update formmain_0229 set field0002 = '' where field0001 = "+hzyaExtData.getString("billCode");
                break;
            case "-9122508232154527168"://客户
                sql = "update formmain_0230 set field0002 = '' where field0001 = "+hzyaExtData.getString("billCode");
                break;
        }
        IntegrationTaskLivingDetailsEntity logDetails = new IntegrationTaskLivingDetailsEntity();
        logDetails.setRootAppPk(JSON.toJSONString(param));
        logDetails.setRootAppBill(hzyaExtData.getString("billCode"));
        logDetails.setNewTransmitInfo(logEntity.getReturnData());
        logDetails.setNewPushDate(new Date());
        logDetails.setRootAppNewData(targetData.getString("body"));
        //logDetails.setNewState(SysMessageManageLogStatusEnum.statusGetValue(logEntity.getStatus()));
        logDetails.setPluginId("SeeyonExtPlugin");
        try {
            if (StrUtil.isEmpty(hzyaExtData.getString("integration_task_living_details_id"))){
                if (SysMessageManageLogStatusEnum.SUCCESS.getType().equals(logEntity.getStatus())) {//成功
                    taskLivingDetailsService.saveLogToSuccess(logDetails);
                }else {
                    taskLivingDetailsService.saveLogToFail(logDetails);//失败
                }
            }else {
                logDetails.setId(hzyaExtData.getString("integration_task_living_details_id"));
                if (SysMessageManageLogStatusEnum.SUCCESS.getType().equals(logEntity.getStatus())) {//成功
                    taskLivingDetailsService.saveLogFailToSuccess(logDetails);
                }else {
                    taskLivingDetailsService.updateLogFailToSuccess(logDetails);//失败
                }
            }
        }catch (Exception e){
            logger.error("保存日志出错：{}",e);
        }
    }

    //存货参数组装
    private SysExtensionApiEntity getInventory(JSONObject businessData,SysExtensionApiEntity param){
        if (null != businessData){
            JSONObject formmain0227 = businessData.getJSONObject("formmain_0227");
            JSONArray formson0228Arr = businessData.getJSONArray("formson_0228");
            for (int i=0; i< formson0228Arr.size(); i++){
                JSONObject formson0228 = formson0228Arr.getJSONObject(i);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("Token", "Hzya1314_CheckSkip");
                jsonObject.put("billid", formson0228.getString("id"));
                jsonObject.put("AccId", formmain0227.getString("field0015"));

                JSONObject oArchives = new JSONObject();
                oArchives.put("cInvCode", formson0228.getString("field0002"));
                oArchives.put("cInvCCode", formson0228.getString("field0005"));
                oArchives.put("cInvName", formson0228.getString("field0003"));
                //todo 这个没值
                oArchives.put("cGroupCode", "01");
                oArchives.put("cComUnitCode", formson0228.getString("field0006"));

                jsonObject.put("oArchives", oArchives);
                param.setBodys(JSON.toJSONString(jsonObject));
            }
        }
        return param;
    }
    //供应商参数组装
    private SysExtensionApiEntity getSupplier(JSONObject businessData,SysExtensionApiEntity param,JSONObject hzyaExtData){
        if (null != businessData){
            JSONObject formmain0225 = businessData.getJSONObject("formmain_0225");
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("billid", formmain0225.getString("id"));
            jsonObject.put("AccId", formmain0225.getString("field0020"));
            jsonObject.put("Token", OAU8Util.getToken());
            JSONObject oArchives = new JSONObject();
            oArchives.put("cVenCode", formmain0225.getString("field0002"));
            oArchives.put("cVenName ", formmain0225.getString("field0003"));
            oArchives.put("cVenAbbName", formmain0225.getString("field0004"));
            oArchives.put("cVCCode", formmain0225.getString("field0006"));
            oArchives.put("cVenExch_name", formmain0225.getString("field0010"));
            //oArchives.put("bVenTax", "false");
            //oArchives.put("bLicenceDate", "false");
            //oArchives.put("bBusinessDate", "false");
            //oArchives.put("bProxyDate", "false");
            //oArchives.put("bPassGMP", "false");
            //oArchives.put("bVenCargo", "false");
            //oArchives.put("bProxyForeign", "true");
            //oArchives.put("bVenService", "true");
            //oArchives.put("iVenGSPType", "0");
            //oArchives.put("bVenOverseas", "false");
            //oArchives.put("bVenAccPeriodMng", "false");
            //oArchives.put("bVenHomeBranch", "false");
            oArchives.put("dVenCreateDatetime", DateUtil.now());
            oArchives.put("cVenRegCode", formmain0225.getString("field0009"));
            oArchives.put("cVenBank", formmain0225.getString("field0011"));
            oArchives.put("cVenAccount", formmain0225.getString("field0012"));
            jsonObject.put("oArchives", oArchives);
            param.setBodys(JSON.toJSONString(jsonObject));
            hzyaExtData.put("billCode", formmain0225.getString("field0001"));
            hzyaExtData.put("formmainId", formmain0225.getString("id"));
        }
        return param;
    }
    //客户参数组装
    private SysExtensionApiEntity getCustomer(JSONObject businessData,SysExtensionApiEntity param,JSONObject hzyaExtData){
        if (null != businessData){
            JSONObject formmain0226 = businessData.getJSONObject("formmain_0226");
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("billid", formmain0226.getString("id"));
            jsonObject.put("AccId", formmain0226.getString("field0025"));
            jsonObject.put("Token", "Hzya1314_CheckSkip");

            JSONObject oArchives = new JSONObject();
            oArchives.put("cCusCode", formmain0226.getString("field0002"));
            oArchives.put("cCusName", formmain0226.getString("field0007"));
            oArchives.put("cCusAbbName", formmain0226.getString("field0008"));
            oArchives.put("cCCCode", formmain0226.getString("field0012"));
            oArchives.put("cCusExch_name", formmain0226.getString("field0013"));
            // todo 这个字段没值
            oArchives.put("cCusMngTypeCode", "999");

            jsonObject.put("oArchives", oArchives);
            param.setBodys(JSON.toJSONString(jsonObject));
            hzyaExtData.put("billCode",formmain0226.getString("field0001"));
            hzyaExtData.put("formmainId",formmain0226.getString("id"));
        }
        return param;
    }
}
