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

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import  com.weaver.seconddev.interfaces.crmoa.CRM_SyncTempUnfreeze;
import  com.weaver.seconddev.interfaces.crmoa.CRM_SyncTempUnfreezeStub.CRM_TEMPUNFREEZE_HEAD;
import  com.weaver.seconddev.interfaces.crmoa.CRM_SyncTempUnfreezeStub.CRM_TEMPUNFREEZE_RETURN;
import  com.weaver.seconddev.interfaces.swfa.BillFieldUtil;
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_BlackListTempThawCheckAction")
public class BlackListTempThawCheckAction extends BaseBean implements Action, EsbServerlessRpcRemoteInterface {

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

    @Autowired
    private CRM_SyncTempUnfreeze service;
    private static final Logger logger_454fb322 = LoggerFactory.getLogger(BlackListTempThawCheckAction.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();
            logger_454fb322.error(String.valueOf("BlackListTempThawCheckAction--start--" + requestid));
            String wfid = request.getWorkflowid();
            BillFieldUtil util = new BillFieldUtil();
//            String table = util.getTablename(wfid);
            String table = request.getRequestManager().getBillTableName();
            Property[] properties = request.getMainTableInfo().getProperty();
            Map<String, String> map = new HashMap<String, String>();
            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 jdksrq = "";
            String jdjsrq = "";
            String sqlx = map.get("SQLX");
            String status = "";
            StringBuilder sb = new StringBuilder();
            if ("0".equals(sqlx)) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String today = sdf.format(new Date());
                jdksrq = map.get("JDKSRQ");
                jdjsrq = map.get("JDJSRQ");
                int res = jdksrq.compareTo(today);
                if (res < 0) {
                    status = "E";
                    sb.append("解冻开始日期不能小于当天，");
                }
                res = jdjsrq.compareTo(jdksrq);
                if (res <= 0) {
                    status = "E";
                    sb.append("解冻结束日期不能小于等于解冻开始日期，");
                }
            } else if ("1".equals(sqlx)) {
                String chsqd = map.get("CHSQD");
                String lrhmddw = map.get("LRHMDDW");
                if (!getApplyCom(chsqd, table).equals(lrhmddw)) {
                    status = "E";
                    sb.append("当前选择的黑名单和要撤销的申请单里的不一致，请重新选择！");
                }
            }
            if ("E".equals(status)) {
                logger_454fb322.error(String.valueOf("BlackListTempThawCheckAction--error--" + requestid + "--" + sb.toString()));
                request.getRequestManager().setMessageid("ERROR");
                request.getRequestManager().setMessagecontent(sb.toString());
                return  WeaResult.fail(500, "BlackListTempThawCheckAction--error--" + requestid + "--" + sb , getResultMapForAction(weaverResultMap, "result", "", request.getRequestManager()));
            } else {
                try {
                    CRM_TEMPUNFREEZE_HEAD[] arr = new CRM_TEMPUNFREEZE_HEAD[1];
//                    CRM_SyncTempUnfreeze service = new CRM_SyncTempUnfreeze();
                    CRM_TEMPUNFREEZE_HEAD head = new CRM_TEMPUNFREEZE_HEAD();
                    // 公司编码
                    head.setBusinessCode(map.get("GSDM"));
                    // 编号
                    head.setCode(map.get("BH"));
                    // 解冻截止时间
                    head.setEndDate(map.get("JDJSRQ"));
                    // 法人/自然人名称
                    head.setLegalPerson(map.get("HMDMC"));
                    // OA流程号
                    head.setOaCode(requestid);
                    // oa流程操作
                    head.setOaOperateFlag("1");
                    // 录入操作人
                    head.setOperator(map.get("LRCZR"));
                    // 撤回的oa流程号
                    head.setRecallform(map.get("CHSQD"));
                    // 解冻开始时间
                    head.setStartDate(map.get("JDKSRQ"));
                    // 标识状态
                    head.setStatusFlag(Integer.parseInt(sqlx) + 1 + "");
                    // 简要原因
                    head.setSummary(map.get("YWGK"));
                    // 社会信用代码/身份证号码
                    head.setTaxno(map.get("SHXYDM"));
                    // 类型
                    head.setType(util.getselectName(map.get("LX"), "50151"));
                    arr[0] = head;
                    CRM_TEMPUNFREEZE_RETURN[] rets = service.call(arr);
                    String mes = "";
                    for (CRM_TEMPUNFREEZE_RETURN ret : rets) {
                        String state = ret.getState();
                        String message = ret.getMessage();
                        logger_454fb322.error(String.valueOf("调用ARS同步黑名单返回值：" + state + "--" + message));
                        if ("S".equals(state)) {
                            status = "S";
                            mes = "执行成功";
                        } else {
                            status = "E";
                            mes += message + "；";
                        }
                    }
                    if (!"S".equals(status)) {
                        logger_454fb322.error(String.valueOf("BlackListTempThawCheckAction--error--" + requestid + "--" + mes));
                        request.getRequestManager().setMessageid("ERROR");
                        request.getRequestManager().setMessagecontent("ARS系统返回信息：" + mes);
                        return  WeaResult.fail(500, "ARS系统返回信息：" + mes, getResultMapForAction(weaverResultMap, "result", "", request.getRequestManager()));
                    }
                } catch (Exception e) {
                    logger_454fb322.error(String.valueOf(requestid + "调用ARS临时解冻接口校验数据出错" + e.toString()));
                    request.getRequestManager().setMessageid("ERROR");
                    request.getRequestManager().setMessagecontent("ARS系统返回信息：" + e.toString());
                    return  WeaResult.fail(500, "ARS系统返回信息：" + e, getResultMapForAction(weaverResultMap, "result", e.getMessage(), request.getRequestManager()));
                }
            }
            logger_454fb322.error(String.valueOf("BlackListTempThawCheckAction--end--" + requestid));
            return WeaResult.success(getResultMapForAction(weaverResultMap, "result", Action.SUCCESS, request.getRequestManager()));
        } catch (Exception e) {
            e.printStackTrace();
            logger_454fb322.error("BlackListTempThawCheckAction e: {}", e.getMessage());
            return  WeaResult.fail(500, "BlackListTempThawCheckAction e: {}"+ e, getResultMapForAction(weaverResultMap, "result", e.getMessage(), request.getRequestManager()));
        }
    }

    public String getApplyCom(String id, String table) {
        RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
        String sql = "select lrhmddw from e10_core_business.dbo." + table + " where id=" + id;

        logger_454fb322.error("getApplyCom sql == " + sql);
        String poolname = CONN_TYPE.workflow.getType();
        // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
        boolean b1 = rs.executeSql(sql, poolname);
        logger_454fb322.error("getApplyCom sql flag== " + b1);
        String lrhmddw = "";
        if (rs.next()) {
            lrhmddw = Util.null2String(rs.getString("lrhmddw"));
        }
        logger_454fb322.error("getApplyCom lrhmddw= " +  lrhmddw);
        return lrhmddw;
    }

    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;
    }
}
