package com.weaver.seconddev.interfaces.workflow.action;

import  com.weaver.seconddev.interfaces.easoa.EASIntermediarySyncService;
import  com.weaver.seconddev.interfaces.easoa.SI_FiAgncyAssetApplicationSync_OUTServiceStub.IntermediaryApplication;
import  com.weaver.seconddev.interfaces.swfa.BillFieldUtil;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.weaver.common.i18n.tool.util.I18nContextUtil;
import com.weaver.verupgrade.conn.CONN_TYPE;
import java.lang.*;
import java.util.*;
import com.weaver.verupgrade.workflow.request.RequestManager;
import com.weaver.esb.api.rpc.EsbServerlessRpcRemoteInterface;
import com.weaver.common.base.entity.result.WeaResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.weaver.verupgrade.soa.workflow.request.RequestInfo;
import com.weaver.verupgrade.conn.RecordSet;
import com.weaver.verupgrade.general.BaseBean;
import com.weaver.verupgrade.general.Util;
import com.weaver.verupgrade.soa.workflow.request.Property;
import com.weaver.verupgrade.interfaces.workflow.action.Action;

@org.springframework.stereotype.Service("workflow_action_EASIntermediarySyncAction")
public class EASIntermediarySyncAction extends BaseBean implements Action, EsbServerlessRpcRemoteInterface {

    // 对应E9的请求信息对象
    @Autowired
    private RequestInfo requestInfoTemp;

    @Autowired
    private EASIntermediarySyncService service;

    private static final Logger logger_c15112b8 = LoggerFactory.getLogger(EASIntermediarySyncAction.class);

    public WeaResult<Map<String, Object>> execute(Map<String, Object> requestInfoMap) {
        Map<String, Object> weaverResultMap = new HashMap<>();
        Long requestIdTemp = Long.parseLong(String.valueOf(requestInfoMap.getOrDefault("requestid", -1)));
        Long userIdTemp = Long.parseLong(String.valueOf(requestInfoMap.getOrDefault("userid", -1)));
        RequestInfo request = requestInfoTemp.getRequestInfo(requestIdTemp, userIdTemp);
        try {
            String requestid = request.getRequestid();
            try {
                logger_c15112b8.error(String.valueOf(requestid + "调用报账系统中介机构同步接口开始"));
                logger_c15112b8.error("requestIdTemp == " +requestIdTemp);
                logger_c15112b8.error("userIdTemp == " +userIdTemp);
                Property[] properties = request.getMainTableInfo().getProperty();
                Map<String, String> map = new HashMap<String, String>();
                BillFieldUtil util = new BillFieldUtil();
                for (int i = 0; i < properties.length; i++) {
                    String name = properties[i].getName().toUpperCase();
                    String value = Util.null2String(properties[i].getValue());
                    map.put(name, value);
                }
                String sqr = util.getName(map.get("SQR"));
                String sqrid = map.get("SQR");
                String sqbm = util.getDepartmentname(map.get("SQBM"));
                String sqgs = util.getSubcompanyname(map.get("SQGS"));
                // 是否备案
                String sfba = map.get("CWZJJGSFYBA");
                // 业务类型
                String ywlx = "";
                // 联系人
                String lxr = "";
                // 联系方式
                String lxfs = "";
                // 财务中介机构名称
                String name = "";
                // 税号
                String sh = "";
                // 新增原因
                String xzyy = "";
                // 有效性
                String yxx = "";
                if ("0".equals(sfba)) {
                    // 测试：47916，正式：44963
                    ywlx = BillFieldUtil.getselectName(map.get("YWLX"), "100003720000044963");
                    lxr = map.get("CWZJJGLXR");
                    lxfs = map.get("CWZJJGLXFS");
                    name = map.get("CWZJJGMC");
                    sh = map.get("NSRSBH");
                    xzyy = map.get("SQJTNR");
                    yxx = map.get("YXX");
                    if ("0".equals(yxx)) {
                        yxx = "Y";
                    } else {
                        yxx = "N";
                    }
                } else {
                    // 测试：47923，正式：44993
                    ywlx = BillFieldUtil.getselectName(map.get("YWLXXZ"), "100003720000044993");
                    lxr = map.get("LXRXZ");
                    lxfs = map.get("LXFSXZ");
                    name = map.get("CWZJJGMCXZ");
                    sh = map.get("NSSBHXZ");
                    xzyy = map.get("XZYY");
                    yxx = "Y";
                }
                IntermediaryApplication info = new IntermediaryApplication();
                info.setAddReason(xzyy);
                info.setAgencyCosts(map.get("CWZJJGFY"));
                info.setAgencyName(name);
                info.setApplicantCompany(sqgs);
                info.setApplicantDept(sqbm);
                info.setApplicantName(sqr);
                info.setApplicantNumber(map.get("GH"));
                info.setApplicantTime(map.get("SQRQ") + " 00:00:00");
                info.setApplicationDetails(map.get("SQJTNR"));
                info.setContacts(lxr);
                info.setContactWay(lxfs);
                info.setDraftTaxRate(map.get("DFTGDDPJJSL"));
                info.setEnabeldFlag(yxx);
                info.setFlowCode(map.get("LCBH"));
                info.setFlowId(requestid);
                info.setOperation(ywlx);
                info.setProject(map.get("JTXM"));
                info.setSocialCredit(sh);
//                EASIntermediarySyncService service = new EASIntermediarySyncService();
                String[] str = service.call(info);
                logger_c15112b8.error(String.valueOf(requestid + "调用报账系统中介机构同步接口返回值" + str[0] + "--" + str[1]));
                if (!"1".equals(str[0])) {
                    request.getRequestManager().setMessageid("ERROR");
                    request.getRequestManager().setMessagecontent("报账系统返回错误信息：" + str[1]);
                } else {
                    String sql = "";
                    if ("0".equals(sfba)) {
                        sql = "update e10_common.dbo.uf_intermediaries set mc='" + name + "',yxx=" + map.get("YXX") + ",ywlx=" + map.get("YWLX") + " where nssbh='" + sh + "'";
                    } else {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String[] datetime = sdf.format(new Date()).split(" ");
                        sql = "insert into e10_common.dbo.uf_intermediaries(formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime,mc,ywlx,nssbh,lxr,lxfs,sfqy,yxx) values(122," + sqrid + ",0,'" + datetime[0] + "','" + datetime[1] + "','" + name + "'," + map.get("YWLXXZ") + ",'" + sh + "','" + lxr + "','" + lxfs + "',0,0)";
                        logger_c15112b8.error(String.valueOf("sql == "+sql));
                    }
                    RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
                    String poolname = CONN_TYPE.workflow.getType();
                    // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                    boolean b = rs.executeSql(sql, poolname);
                    logger_c15112b8.error(String.valueOf("b == "+b));
                    logger_c15112b8.error(String.valueOf(requestid + "更新财务中介机构模块数据成功"));
                }
                logger_c15112b8.error(String.valueOf(requestid + "调用报账系统中介机构同步接口结束"));
            } catch (Exception e) {
                logger_c15112b8.error(String.valueOf(requestid + "调用报账系统中介机构同步接口出错：" + e.toString()));
                request.getRequestManager().setMessageid("ERROR");
                request.getRequestManager().setMessagecontent("报账系统返回错误信息：" + e.toString());
                return  WeaResult.fail(500, "报账系统返回错误信息: {}"+ e, getResultMapForAction(weaverResultMap, "result", e.getMessage(), request.getRequestManager()));

            }
            return WeaResult.success(getResultMapForAction(weaverResultMap, "result", Action.SUCCESS, request.getRequestManager()));
        } catch (Exception e) {
            e.printStackTrace();
            logger_c15112b8.error("EASIntermediarySyncAction e: {}", e.getMessage());
            return  WeaResult.fail(500, "EASIntermediarySyncAction e: {}"+ e, getResultMapForAction(weaverResultMap, "result", e.getMessage(), request.getRequestManager()));
        }
    }

    Map<String, Object> getResultMapForAction(Map<String, Object> map, String key, Object value, RequestManager requestManager) {
        if (key != null && !key.isEmpty()) {
            map.put(key, value);
        }
        String msgContent = requestManager.getMessagecontent();
        if (msgContent != null && !msgContent.isEmpty()) {
            map.put("msgContent", msgContent);
        }
        String msgId = requestManager.getMessageid();
        if (msgId != null && !msgId.isEmpty()) {
            map.put("msgId", msgId);
        }
        return map;
    }
}
