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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringEscapeUtils;
import  com.weaver.seconddev.interfaces.oames.ReturnMesWLPS_SYService;
import  com.weaver.seconddev.interfaces.oames.SI_OA_HTOAApproFlowSync_OUTServiceStub;
import  com.weaver.seconddev.interfaces.swfa.BillFieldUtil;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
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.hrm.resource.ResourceComInfo;
import com.weaver.verupgrade.soa.workflow.request.*;
import com.weaver.verupgrade.soa.workflow.request.Property;
import com.weaver.verupgrade.interfaces.workflow.action.Action;

/**
 * HTGD-SC09-亨通光电调试申请流程
 */
@org.springframework.stereotype.Service("workflow_action_HTGD_MES_SC03Action")
public class HTGD_MES_SC03Action extends BaseBean implements Action, EsbServerlessRpcRemoteInterface {

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

    @Autowired
    private ReturnMesWLPS_SYService service;
    private static final Logger logger_1ea91e04 = LoggerFactory.getLogger(HTGD_MES_SC03Action.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 requestinfo = requestInfoTemp.getRequestInfo(requestIdTemp, userIdTemp);
        try {
            String requestId = requestinfo.getRequestid();
            try {
                String requestName = requestinfo.getRequestManager().getRequestname();
                String creatorId = requestinfo.getCreatorid();
                // 工作流ID
                String workFlowId = requestinfo.getWorkflowid();
                ResourceComInfo rsCom = I18nContextUtil.getBean(ResourceComInfo.class);
                logger_1ea91e04.error(String.valueOf("HTGD_MES_SC03Action-start-" + requestId));
                logger_1ea91e04.error("requestIdTemp == " +requestIdTemp);
                logger_1ea91e04.error("userIdTemp == " +userIdTemp);
                String fxzt = "";
                // 申请部门意见
                String sqbmyj = "";
                // 受理部门意见
                String slbmyj = "";
                // 协助部门意见
                String xzbmyj = "";
                Property[] aproperty = requestinfo.getMainTableInfo().getProperty();
                for (int j = 0; j < aproperty.length; j++) {
                    String name = aproperty[j].getName().toUpperCase();
                    String value = Util.null2String(aproperty[j].getValue());
                    if ("SPJG".equals(name)) {
                        fxzt = value;
                    }
                    if ("SQBMYJ".equals(name)) {
                        sqbmyj = StringEscapeUtils.unescapeHtml(value.trim());
                    }
                    if ("SLBMYJ".equals(name)) {
                        slbmyj = StringEscapeUtils.unescapeHtml(value.trim());
                    }
                    if ("XZBMYJ".equals(name)) {
                        xzbmyj = StringEscapeUtils.unescapeHtml(value.trim());
                    }
                }
                JSONObject mjson = new JSONObject();
                RecordSet sqbmrs = I18nContextUtil.getBean(RecordSet.class);
                // 获取申请部门审核记录
                String sql = "select operatedatetime,operatetime,b.username from e10_core_business.dbo.wfc_requestlog  a " + "INNER JOIN employee b on a.creator = b.id " + "where id = " + requestId + // 申请部门一级人员 测试环境-19915 正式环境-29618
                " and nodeid = 29618";
                String poolname = CONN_TYPE.workflow.getType();
                // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                boolean b = sqbmrs.executeSql(sql, poolname);
                logger_1ea91e04.error("b -----"+ b);
                while (sqbmrs.next()) {
                    String date = Util.null2String(sqbmrs.getString("operatedate"));
                    String time = Util.null2String(sqbmrs.getString("operatetime"));
                    String name = Util.null2String(sqbmrs.getString("lastname"));
                    mjson.put("sqbmspr", name);
                    mjson.put("sqbmspsj", date + " " + time);
                    mjson.put("sqbmyj", sqbmyj);
                }
                // 获取受理部门审核记录
                String sql_slbm = "select operatedatetime,operatetime,b.username from e10_core_business.dbo.wfc_requestlog  a " + "INNER JOIN employee b on a.creator = b.id " + "where id = " + requestId + // 受理部门一级人员 测试环境-19916  正式环境-29619
                " and nodeid = 29619";
                String poolname_dk = CONN_TYPE.workflow.getType();
                // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                boolean b1 = sqbmrs.executeSql(sql_slbm, poolname_dk);
                logger_1ea91e04.error("b1 -----"+ b1);
                while (sqbmrs.next()) {
                    String date = Util.null2String(sqbmrs.getString("operatedate"));
                    String time = Util.null2String(sqbmrs.getString("operatetime"));
                    String name = Util.null2String(sqbmrs.getString("lastname"));
                    mjson.put("slbmspr", name);
                    mjson.put("slbmspsj", date + " " + time);
                    mjson.put("slbmyj", slbmyj);
                }
                // 获取协助部门审核记录
                // String sql_xzbm = "select operatedate,operatetime,b.lastname from workflow_requestLog a "
                // + "INNER JOIN HrmResource b on a.operator = b.id "
                // + "where requestid = " + requestId + " and nodeid = 19940";//协助部门一级人员 测试环境-19940  正式环境-29621
                // RecordSet xzbmrs = new RecordSet();
                // xzbmrs.executeSql(sql_xzbm);
                // while (xzbmrs.next()) {
                // String date = Util.null2String(xzbmrs.getString("operatedate"));
                // String time = Util.null2String(xzbmrs.getString("operatetime"));
                // String name = Util.null2String(xzbmrs.getString("lastname"));
                // mjson.put("xzbmspr",name);
                // mjson.put("xzbmspsj",date+" "+time);
                // mjson.put("xzbmyj",xzbmyj);
                // }
                if ("1".equals(fxzt)) {
                    String xzbmsprid = requestinfo.getLastoperator();
                    String xzbmspr = rsCom.getResourcename(xzbmsprid);
                    String xzbmspsj = requestinfo.getRequestManager().getCurrentDate() + " " + requestinfo.getRequestManager().getCurrentTime();
                    mjson.put("xzbmspr", xzbmspr);
                    mjson.put("xzbmspsj", xzbmspsj);
                    mjson.put("xzbmyj", xzbmyj);
                } else {
                    mjson.put("xzbmspr", "");
                    mjson.put("xzbmspsj", "");
                    mjson.put("xzbmyj", "");
                }
                String uuid = UUID.randomUUID().toString();
//                ReturnMesWLPS_SYService service = new ReturnMesWLPS_SYService();
                SI_OA_HTOAApproFlowSync_OUTServiceStub.WLPS_SY_Request req = new SI_OA_HTOAApproFlowSync_OUTServiceStub.WLPS_SY_Request();
                SI_OA_HTOAApproFlowSync_OUTServiceStub.ArrayOfWLPS_SY_Main mainData = new SI_OA_HTOAApproFlowSync_OUTServiceStub.ArrayOfWLPS_SY_Main();
                SI_OA_HTOAApproFlowSync_OUTServiceStub.WLPS_SY_Main param = new SI_OA_HTOAApproFlowSync_OUTServiceStub.WLPS_SY_Main();
                param.setWorkflowid(workFlowId);
                param.setFxzt(fxzt);
                param.setRequestName(requestName);
                param.setRequestid(requestId);
                param.setCreator(rsCom.getWorkcode(creatorId));
                param.setPlaceholder1(mjson.toJSONString());
                logger_1ea91e04.error(mjson.toJSONString());
                mainData.addWLPS_SY_Main(param);
                req.setSYSID("SYS052");
                req.setSENDID(uuid);
                req.setITFID("HT01ETS009");
                req.setDATAS(mainData);
                String[] ret = service.returnRes(req);
                logger_1ea91e04.error(String.valueOf(requestId + "-HTGD_MES_SC03Action info:" + ret[0] + "-" + ret[1]));
                if (!"S".equals(ret[0])) {
                    BillFieldUtil util = new BillFieldUtil();
//                    String tablename = util.getTablename(workFlowId);
                    String tablename = requestinfo.getRequestManager().getBillTableName();
                    RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
                    String poolname_ig = CONN_TYPE.workflow.getType();
                    // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                    boolean b2 = rs.executeSql("update e10_core_business.dbo" + tablename + " set state='E',message='" + ret[1] + "' where id=" + requestId, poolname_ig);
                    logger_1ea91e04.error("b2 -----"+ b2);
                }
            } catch (Exception exception) {
                logger_1ea91e04.error(String.valueOf(requestId + "-HTGD_MES_SC03Action error:" + exception.getMessage()));
                return  WeaResult.fail(500, requestId + "-HTGD_MES_SC03Action error:" + exception.getMessage(), getResultMapForAction(weaverResultMap, "result",requestId + "-HTGD_MES_SC03Action error:" + exception.getMessage(), requestinfo.getRequestManager()));

            }
            return WeaResult.success(getResultMapForAction(weaverResultMap, "result", Action.SUCCESS, requestinfo.getRequestManager()));
        } catch (Exception e) {
            e.printStackTrace();
            logger_1ea91e04.error("HTGD_MES_SC03Action e: {}", e.getMessage());
            return  WeaResult.fail(500, "HTGD_MES_SC03Action " + e, getResultMapForAction(weaverResultMap, "result", e.getMessage(), requestinfo.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;
    }
}
