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

import com.sap.conn.jco.JCoDestination;
import com.sap.conn.jco.JCoFunction;
import com.sap.conn.jco.JCoTable;
import  com.weaver.seconddev.interfaces.swfa.BillFieldUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
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.Cell;
import com.weaver.verupgrade.soa.workflow.request.DetailTable;
import com.weaver.verupgrade.soa.workflow.request.Row;
import com.weaver.verupgrade.interfaces.workflow.action.Action;

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

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

    private static final Logger logger_e6726d63 = LoggerFactory.getLogger(ZOA_MM_ZMMT002_FASTCONFIG_Action.class);

    @Override
    public WeaResult<Map<String, Object>> execute(Map<String, Object> requestInfoMap) {
        logger_e6726d63.error("ZOA_MM_ZMMT002_FASTCONFIG_Action 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 requestinfo = requestInfoTemp.getRequestInfo(requestIdTemp, userIdTemp);
        try {
            String requestid = requestinfo.getRequestid();
            String wfid = requestinfo.getWorkflowid();
            logger_e6726d63.error(String.valueOf("ZOA_MM_ZMMT002_FASTCONFIG_Action-start:" + requestid));
            BillFieldUtil util = new BillFieldUtil();
//            String tablename = util.getTablename(wfid);
            String tablename = requestinfo.getRequestManager().getBillTableName();
            DetailTable[] detailtable = requestinfo.getDetailTableInfo().getDetailTable();
            DetailTable dtq = detailtable[0];
            Row[] sq = dtq.getRow();
            List<Map<String, String>> list = new ArrayList<Map<String, String>>();
            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 ("wlbh".equals(nameq)) {
                        mDetailMap.put("wlbh", valueq);
                    }
                    if ("mxbgxs".equals(nameq)) {
                        if ("0".equals(valueq)) {
                            valueq = "02";
                        } else if ("1".equals(valueq)) {
                            valueq = "01";
                        }
                        mDetailMap.put("mxbgxs", valueq);
                    }
                    if ("cgzzbm".equals(nameq)) {
                        mDetailMap.put("cgzzbm", valueq);
                    }
                }
                list.add(mDetailMap);
            }
            String[] retstr = new String[2];
            retstr[0] = "E";
            try {
                JCoDestination destination = SAPConn.getJCoDestination();
                JCoFunction jcofunction = destination.getRepository().getFunction("ZOA_MM_ZMMT002_FASTCONFIG");
                if (jcofunction == null) {
                    retstr[1] = "ZOA_MM_PR_CREATE not found in SAP.";
                } else {
                    JCoTable jcotable = jcofunction.getTableParameterList().getTable("T_DATA");
                    for (int i = 0; i < list.size(); i++) {
                        jcotable.appendRow();
                        jcotable.setValue("MATNR", list.get(i).get("wlbh"));
                        jcotable.setValue("EKORG", list.get(i).get("cgzzbm"));
                        jcotable.setValue("ZPUTYP", list.get(i).get("mxbgxs"));
                    }
                    try {
                        jcofunction.execute(destination);
                        retstr[0] = jcofunction.getExportParameterList().getValue("STATUS").toString();
                        retstr[1] = jcofunction.getExportParameterList().getValue("MESSAGE").toString();
                    } catch (Exception e1) {
                        retstr[1] = e1.toString();
                    }
                }
            } catch (Exception e) {
                retstr[1] = e.toString();
            }
            logger_e6726d63.error(String.valueOf("ZOA_MM_ZMMT002_FASTCONFIG_Action-end:" + requestid + "-[" + retstr[0] + "," + retstr[1] + "]"));
            RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
            String poolname = CONN_TYPE.workflow.getType();
            // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
            String sql = "update e10_core_business.dbo." + tablename + " set state='" + retstr[0] + "',message='" + retstr[1] + "' where id=" + requestid;
            logger_e6726d63.error("sql = " + sql );
            boolean b1 = rs.executeSql(sql, poolname);
            logger_e6726d63.error("sql flag= " + b1 );
            if ("E".equals(retstr[0])) {
                requestinfo.getRequestManager().setMessageid("error");
                requestinfo.getRequestManager().setMessagecontent(retstr[1]);
                return  WeaResult.fail(500, "提交失败 e: {}"+ retstr[1], getResultMapForAction(weaverResultMap, "result", retstr[1], requestinfo.getRequestManager()));
            }
            return WeaResult.success(getResultMapForAction(weaverResultMap, "result", Action.SUCCESS, requestinfo.getRequestManager()));
        } catch (Exception e) {
            e.printStackTrace();
            logger_e6726d63.error("ZOA_MM_ZMMT002_FASTCONFIG_Action e: {}", e.getMessage());
            return  WeaResult.fail(500, "ZOA_MM_ZMMT002_FASTCONFIG_Action 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;
    }
}
