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

import java.text.SimpleDateFormat;
import java.util.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.weaver.common.distribution.genid.IdGenerator;
import  com.weaver.seconddev.interfaces.easoa.EAS_YszxfpApplyResult;
import com.weaver.common.i18n.tool.util.I18nContextUtil;
import com.weaver.verupgrade.conn.CONN_TYPE;
import java.lang.*;
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 java.util.Map;
import java.util.HashMap;
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.Cell;
import com.weaver.verupgrade.soa.workflow.request.DetailTable;
import com.weaver.verupgrade.soa.workflow.request.Property;
import com.weaver.verupgrade.soa.workflow.request.Row;
import com.weaver.verupgrade.interfaces.workflow.action.Action;

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

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

    @Autowired
    private EAS_YszxfpApplyResult mGetResult;
    private static final Logger logger_c018d513 = LoggerFactory.getLogger(SCFAndEASApplyUserSyncAction.class);

    public WeaResult<Map<String, Object>> execute(Map<String, Object> requestInfoMap) {
        logger_c018d513.error("SCFAndEASApplyUserSyncAction start");
        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();
            String applyNo = "";
            String companyCode = "";
            // 申请人
            String sqr = "";
            Property[] properties = request.getMainTableInfo().getProperty();
            for (int i = 0; i < properties.length; i++) {
                String name = properties[i].getName().toUpperCase();
                String value = Util.null2String(properties[i].getValue());
                if ("LCBH".equals(name)) {
                    applyNo = value;
                }
                if ("GSBH".equals(name)) {
                    companyCode = value;
                }
                if ("SQR".equals(name)) {
                    sqr = value;
                }
            }
            DetailTable dtq = request.getDetailTableInfo().getDetailTable(0);
            Row[] sq = dtq.getRow();
            List<Map<String, String>> list = new ArrayList<Map<String, String>>();
            List<Map<String, String>> list1 = new ArrayList<Map<String, String>>();
            for (int j = 0; j < sq.length; j++) {
                Row rq = sq[j];
                Cell[] cq = rq.getCell();
                Map<String, String> map = new HashMap<String, String>();
                Map<String, String> map1 = new HashMap<String, String>();
                for (int k = 0; k < cq.length; k++) {
                    Cell cq1 = cq[k];
                    String nameq = cq1.getName().toLowerCase();
                    String valueq = Util.null2String(cq1.getValue());
                    if ("lclx".equals(nameq)) {
                        map.put("lclx", valueq);
                        map1.put("flowType", Integer.parseInt(valueq) + 1 + "");
                    }
                    if ("oafqr".equals(nameq)) {
                        map.put("oafqr", valueq);
                    }
                    if ("oafqrgh".equals(nameq)) {
                        map.put("oafqrgh", valueq);
                    }
                    if ("easfqr".equals(nameq)) {
                        map.put("easfqr", valueq);
                    }
                    if ("easfqrgh".equals(nameq)) {
                        map.put("easfqrgh", valueq);
                        map1.put("employeeNumber", valueq);
                    }
                    if ("bm".equals(nameq)) {
                        map1.put("attribute1", valueq);
                    }
                }
                logger_c018d513.error("map = " + map);
                logger_c018d513.error("map1 = " + map1);
                if (Integer.parseInt(map.get("lclx")) <= 1 && !"".equals(map.get("oafqr"))) {
                    list.add(map);
                }
                if (!"".equals(map1.get("employeeNumber"))) {
                    list1.add(map1);
                }
            }
            if (list1 != null && list1.size() > 0) {
                try {
                    JSONObject obj = new JSONObject();
                    obj.put("systemFlag", "OA");
                    obj.put("companyCode", companyCode);
                    obj.put("requestId", requestid);
                    obj.put("applyNo", applyNo);
                    obj.put("checkFlag", "2");
                    obj.put("ITFID", "HT01BZ033");
                    obj.put("items", JSONArray.parseArray(JSON.toJSONString(list1)));
                    logger_c018d513.error("getApproveResult 入参" + obj);
//                    EAS_YszxfpApplyResult mGetResult = new EAS_YszxfpApplyResult();
                    String result = mGetResult.getApproveResult(obj, "SCFAndEASApplyUser");
                    logger_c018d513.error(String.valueOf(requestid + "调用报账系统同步流程发起人信息返回值：" + result));
                    if (!"E".equals(result)) {
                        JSONObject jsonObject = JSONObject.parseObject(result);
                        // 接口处理状态 S-成功，E-失败
                        String isTat = jsonObject.getString("istat");
                        // 处理消息
                        String srMessage = jsonObject.getString("srmsage");
                        if (!"S".equals(isTat)) {
                            // 失败
                            logger_c018d513.error(String.valueOf(requestid + "报账系统返回错误信息：" + srMessage));
                            request.getRequestManager().setMessageid("ERROR");
                            request.getRequestManager().setMessagecontent("报账系统返回错误信息：" + srMessage);
                            return  WeaResult.fail(500, "SCFAndEASApplyUserSyncAction srMessage"+ srMessage, getResultMapForAction(weaverResultMap, "result",srMessage, request.getRequestManager()));
                        } else {
                            updateData(sqr, companyCode, list);
                        }
                    }
                } catch (Exception e) {
                    logger_c018d513.error(String.valueOf(requestid + "调用报账系统同步流程发起人信息接口出错：" + e.toString()));
                    request.getRequestManager().setMessageid("ERROR");
                    request.getRequestManager().setMessagecontent("调用报账系统接口返回失败，请联系报账系统管理员！");
                    return  WeaResult.fail(500, "SCFAndEASApplyUserSyncAction err"+ e, getResultMapForAction(weaverResultMap, "result",e.getMessage(), request.getRequestManager()));
                }
            } else {
                logger_c018d513.error(String.valueOf("不需要调用接口"));
                if (list != null && list.size() > 0) {
                    updateData(sqr, companyCode, list);
                }
            }
            return WeaResult.success(getResultMapForAction(weaverResultMap, "result", Action.SUCCESS, request.getRequestManager()));
        } catch (Exception e) {
            e.printStackTrace();
            logger_c018d513.error("SCFAndEASApplyUserSyncAction e: {}", e.getMessage());
            return  WeaResult.fail(500, "SCFAndEASApplyUserSyncAction e {}"+ e, getResultMapForAction(weaverResultMap, "result",e.getMessage(), request.getRequestManager()));
        }
    }

    public void updateData(String sqr, String companyCode, List<Map<String, String>> list) {
        RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
        for (int i = 0; i < list.size(); i++) {
            String lclx = list.get(i).get("lclx");
            String time = getCurrentDate();
            String currentdate = "";
            String currenttime = "";
            if (time != null && time.length() > 10) {
                currentdate = time.substring(0, 10);
                currenttime = time.substring(11);
            }
            String sql = "select id from e10_common.dbo.uf_applyUser where companycode='" + companyCode + "' and lclx=" + list.get(i).get("lclx");
            String poolname = CONN_TYPE.workflow.getType();
            // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
            boolean b = rs.executeSql(sql, poolname);
            logger_c018d513.error("b1 -----"+ b);
            if (rs.next()) {
                if ("0".equals(lclx)) {
                    String poolname_7m = CONN_TYPE.workflow.getType();
                    /*开票申请
 TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源*/
                   // boolean b1 = rs.executeSql("update e10_common.dbo.uf_applyUser set " + "'E10无此字段formmodeid'='139'" + ", modedatacreater=" + sqr + ", 'E10无此字段modedatacreatertype'= '0'" + ", modedatacreatedate= '" + currentdate + "'" + ", modedatacreatetime= '" + currenttime + "'" + ", oafqr=" + list.get(i).get("oafqr") + ",oafqrgh='" + list.get(i).get("oafqrgh") + "'" + " where  companycode='" + companyCode + "' and lclx=" + list.get(i).get("lclx"), poolname_7m);
                    boolean b1 = rs.executeSql("update e10_common.dbo.uf_applyUser set oafqr=" + list.get(i).get("oafqr") + ",oafqrgh='" + list.get(i).get("oafqrgh") + "'" + " where  companycode='" + companyCode + "' and lclx=" + list.get(i).get("lclx"), poolname_7m);
                    logger_c018d513.error("b1 -----"+ b1);
                } else {
                    String poolname_19 = CONN_TYPE.workflow.getType();
                    /*直贷业务
 TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源*/
                 //   boolean b1 = rs.executeSql("update e10_common.dbo.uf_applyUser set " + "'E10无此字段formmodeid'='139'" + ", modedatacreater=" + sqr + ", 'E10无此字段modedatacreatertype'= '0'" + ", modedatacreatedate= '" + currentdate + "'" + ", modedatacreatetime= '" + currenttime + "'" + ", oafqr=" + list.get(i).get("oafqr") + ",oafqrgh='" + list.get(i).get("oafqrgh") + "'" + ", easfqr=" + list.get(i).get("oafqr") + ",easfqrgh='" + list.get(i).get("oafqrgh") + "'" + " where  companycode='" + companyCode + "' and lclx=" + list.get(i).get("lclx"), poolname_19);
                    boolean b1 = rs.executeSql("update e10_common.dbo.uf_applyUser set oafqr=" + list.get(i).get("oafqr") + ",oafqrgh='" + list.get(i).get("oafqrgh") + "'" + ", easfqr=" + list.get(i).get("oafqr") + ",easfqrgh='" + list.get(i).get("oafqrgh") + "'" + " where  companycode='" + companyCode + "' and lclx=" + list.get(i).get("lclx"), poolname_19);
                    logger_c018d513.error("b1 -----"+ b1);
                }
                // rs.execute("update uf_applyUser set oafqr="+list.get(i).get("oafqr")+",oafqrgh='"+list.get(i).get("oafqrgh")+"',easfqr="+list.get(i).get("easfqr")+",easfqrgh='"+list.get(i).get("easfqrgh")+"' where  companycode='"+companyCode+"' and lclx="+list.get(i).get("lclx"));
            }
            /*TODO
            建模需要确认数据插入如何实行（唯一值怎么确认 如formmodeid，modeUUID等等 2025/02/27）
             */
//            else {
//                String uuid = UUID.randomUUID().toString();
//                if ("0".equals(lclx)) {
//                    String poolname_qw = CONN_TYPE.workflow.getType();
//                    // 开票申请
//                    /* *TODO  检测到insert语句 -> E9插入sql迁移到E10需要特殊处理请参考文档进行调整  https://www.e-cology.com.cn/sp/doc/docShare/1027709301045985331?tenantKey=t7akvdnf84
// TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源*/
//                    long generate = IdGenerator.generate();
//                    boolean b1 = rs.executeSql("insert into e10_common.dbo.uf_applyUseruf_applyUser(companycode,formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime," + "lclx,oafqr,oafqrgh,modeuuid) " + "values('" + companyCode + "'," + "'139'," + sqr + "," + "'0'," + "'" + currentdate + "'," + "'" + currenttime + "'," + list.get(i).get("lclx") + "," + list.get(i).get("oafqr") + ",'" + list.get(i).get("oafqrgh") + "','" + uuid + "')", poolname_qw, generate);
//                    logger_c018d513.error("b1 -----"+ b1);
//                } else {
//                    String poolname_2n = CONN_TYPE.workflow.getType();
//                    /*直贷业务
// TODO  检测到insert语句 -> E9插入sql迁移到E10需要特殊处理请参考文档进行调整  https://www.e-cology.com.cn/sp/doc/docShare/1027709301045985331?tenantKey=t7akvdnf84
// TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源*/
//                    long generate = IdGenerator.generate();
//                    boolean b1 = rs.executeSql("insert into e10_common.dbo.uf_applyUseruf_applyUser(companycode,formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime," + "lclx,oafqr,oafqrgh,easfqr,easfqrgh,modeuuid) " + "values('" + companyCode + "'," + "'139'," + sqr + "," + "'0'," + "'" + currentdate + "'," + "'" + currenttime + "'," + list.get(i).get("lclx") + "," + list.get(i).get("oafqr") + ",'" + list.get(i).get("oafqrgh") + "'," + list.get(i).get("oafqr") + ",'" + list.get(i).get("oafqrgh") + "','" + uuid + // DiscountedInvoiceApplicationImpl 使用eas发起人
//                            "')", poolname_2n, generate);
//                    logger_c018d513.error("b1 -----"+ b1);
//                }
//                // rs.execute("F");
//            }
        }
    }

    public String getCurrentDate() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(currentTime);
        return dateString;
    }

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