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

import com.alibaba.fastjson.JSONArray;
import  com.weaver.seconddev.interfaces.oames.ReturnMesWLPS_SYService;
import  com.weaver.seconddev.interfaces.oames.SI_OA_HTOAApproFlowSync_OUTServiceStub.ArrayOfWLPS_SY_Main;
import  com.weaver.seconddev.interfaces.oames.SI_OA_HTOAApproFlowSync_OUTServiceStub.WLPS_SY_Main;
import  com.weaver.seconddev.interfaces.oames.SI_OA_HTOAApproFlowSync_OUTServiceStub.WLPS_SY_Request;
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.soa.workflow.request.DetailTable;
import com.weaver.verupgrade.soa.workflow.request.Row;
import com.weaver.verupgrade.soa.workflow.request.Cell;
import com.weaver.verupgrade.interfaces.workflow.action.Action;

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

    // 对应E9的请求信息对象
    @Autowired
    private RequestInfo requestInfoTemp;
    @Autowired
    private ReturnMesWLPS_SYService service;
    private static final Logger logger_d0d39a5f = LoggerFactory.getLogger(HTGD_MES_SpeedFixAction.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();
                logger_d0d39a5f.error(String.valueOf("HTGD_MES_SpeedFixAction-start-" + requestId));
                logger_d0d39a5f.error("requestIdTemp == " +requestIdTemp);
                logger_d0d39a5f.error("userIdTemp == " +userIdTemp);
                String fxzt = "";
                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;
                    }
                }
                DetailTable[] detailtable = requestinfo.getDetailTableInfo().getDetailTable();
                DetailTable dtq = detailtable[0];
                Row[] sq = dtq.getRow();
                JSONArray mJSONArray = new JSONArray();
                for (int j = 0; j < sq.length; j++) {
                    // 指定行
                    Row rq = sq[j];
                    // 每行数据再按列存储
                    Cell[] cq = rq.getCell();
                    Map<String, String> mDetailMap = 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 ("ph".equals(nameq)) {
                            mDetailMap.put("ph", valueq);
                        }
                        if ("xzsd".equals(nameq)) {
                            mDetailMap.put("xzsd", valueq);
                        }
                        if ("xzyy".equals(nameq)) {
                            mDetailMap.put("xzyy", valueq);
                        }
                    }
                    mJSONArray.add(mDetailMap);
                }
                ResourceComInfo rsCom = I18nContextUtil.getBean(ResourceComInfo.class);
                String uuid = UUID.randomUUID().toString();
//                ReturnMesWLPS_SYService service = new ReturnMesWLPS_SYService();
                WLPS_SY_Request req = new WLPS_SY_Request();
                ArrayOfWLPS_SY_Main mainData = new ArrayOfWLPS_SY_Main();
                WLPS_SY_Main param = new WLPS_SY_Main();
                param.setWorkflowid(workFlowId);
                param.setFxzt(fxzt);
                param.setRequestName(requestName);
                param.setRequestid(requestId);
                param.setCreator(rsCom.getWorkcode(creatorId));
                param.setPlaceholder1(mJSONArray.toJSONString());
                logger_d0d39a5f.error(mJSONArray.toJSONString());
                mainData.addWLPS_SY_Main(param);
                req.setSYSID("SYS052");
                req.setSENDID(uuid);
                req.setITFID("HT01ETS009");
                req.setDATAS(mainData);
                String[] ret = service.returnRes(req);
                logger_d0d39a5f.error(String.valueOf(requestId + "-HTGD_MES_SpeedFixAction 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 = CONN_TYPE.workflow.getType();
                    // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                    boolean b = rs.executeSql("update e10_core_business.dbo." + tablename + " set state='E',message='" + ret[1] + "' where id=" + requestId, poolname);
                    logger_d0d39a5f.error(String.valueOf(requestId + "-HTGD_MES_SpeedFixAction update:" + b));
                }
            } catch (Exception exception) {
                logger_d0d39a5f.error(String.valueOf(requestId + "-HTGD_MES_SpeedFixAction error:" + exception.getMessage()));
                return  WeaResult.fail(500, "HTGD_MES_SpeedFixAction error:"+ exception, getResultMapForAction(weaverResultMap, "result",exception.getMessage(), requestinfo.getRequestManager()));

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