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

import com.weaver.seconddev.interfaces.htjt.util.TransUtil;
import  com.weaver.seconddev.interfaces.swfa.BillFieldUtil;
import java.util.HashMap;
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.*;
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;

/**
 * sap206-SAP206-OEM成品价格会签流程
 */
@org.springframework.stereotype.Service("workflow_action_ZSR_PUR_INFO_OEM_Action")
public class ZSR_PUR_INFO_OEM_Action extends BaseBean implements Action, EsbServerlessRpcRemoteInterface {

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

    private static final Logger logger_adc1e038 = LoggerFactory.getLogger(ZSR_PUR_INFO_OEM_Action.class);

    @Override
    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);

        logger_adc1e038.error("----- workflow_action_ZSR_PUR_INFO_OEM_Action new -----");
        logger_adc1e038.error("requestIdTemp -----"+ requestIdTemp);
        logger_adc1e038.error("userIdTemp -----"+ userIdTemp);
        try {
            String requestid = requestinfo.getRequestid();
            String wfid = requestinfo.getWorkflowid();
            TransUtil tu = new TransUtil();
//            String tablename = tu.getTableName(wfid);
            String tablename = requestinfo.getRequestManager().getBillTableName();
            RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
            try {
                logger_adc1e038.error(String.valueOf("ZSR_PUR_INFO_OEM_Action-start-" + requestid));
                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());
                }
                DetailTable[] detailtable = requestinfo.getDetailTableInfo().getDetailTable();
                DetailTable dtq = detailtable[0];
                Row[] sq = dtq.getRow();
                StringBuilder sb = new StringBuilder();
                String state = "";
                int mxcount = 0;
                String sql = "select count(b.id) as mxcount from e10_core_business.dbo." + tablename + " a,e10_core_business.dbo." + tablename + "_dt1 b where a.form_data_id = b.form_data_id  and a.id =" + requestid + " and isnull(sfbjsc,1)<>0";
                logger_adc1e038.error("sql -----"+ sql);
                String poolname = CONN_TYPE.workflow.getType();
                // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                boolean b1 = rs.executeSql(sql, poolname);
                logger_adc1e038.error("sql flag1-----"+ b1);
                if (rs.next()) {
                    mxcount = rs.getInt("mxcount");
                    logger_adc1e038.error("mxcount -----"+ mxcount);
                }
                if (mxcount > 0) {
                    int j = 0;
                    String[][] str = new String[mxcount][21];
                    for (int i = 0; i < sq.length; i++) {
                        Row rq = sq[i];
                        Cell[] cq = rq.getCell();
                        Map<String, String> map = new HashMap<String, String>();
                        for (int k = 0; k < cq.length; k++) {
                            Cell cq1 = cq[k];
                            String nameq = cq1.getName().toUpperCase();
                            String valueq = Util.null2String(cq1.getValue());
                            map.put(nameq, valueq);
                        }
                        // 是否标记删除
                        String sfbjsc = map.get("SFBJSC");
                        if ("0".equals(sfbjsc)) {
                            continue;
                        }
                        str[j][0] = requestid + "_" + j;
                        // 采购组织
                        str[j][1] = map.get("CGZZ");
                        // 采购组
                        str[j][2] = map.get("CGZ");
                        // 物料
                        str[j][3] = map.get("CPWL");
                        // 供应商账户号（ERP编码）
                        str[j][4] = map.get("GYSZHHERPBM");
                        // 订单单位
                        str[j][5] = map.get("DDDW");
                        // 订单单位到基本单位(BTCI)转换的值
                        str[j][6] = map.get("ZHZ");
                        // 有关订货价格单位转换为基本单位的分子(BTCI)
                        str[j][7] = map.get("JBDW");
                        // 最小采购订单数量 (BTCI)
                        str[j][8] = map.get("ZXSL");
                        // 标准采购订单数量 (BTCI)
                        str[j][9] = map.get("BZSL");
                        // 以天计的计划交货时间(BTCI)
                        str[j][10] = map.get("JHSJ");
                        // 销售/购买税代码
                        str[j][11] = map.get("XSGMSDM");
                        // 采购信息记录分类
                        str[j][12] = map.get("JLFL");
                        // 条件记录有效起始日期
                        str[j][13] = map.get("YXQSRQ").replaceAll("-", "");
                        // 条件记录有效截止日期
                        str[j][14] = map.get("YXJZRQ").replaceAll("-", "");
                        // 采购凭证中的净价格(以凭证货币计)BTCI/OEM最终总价
                        str[j][15] = map.get("OEMZZZJ");
                        // BTCI的价格单位
                        str[j][16] = map.get("JGDW");
                        // 供应商物料组
                        str[j][17] = map.get("GYSWLZ");
                        str[j][18] = "";
                        // 货币
                        str[j][19] = map.get("HB");
                        str[j][20] = requestid;
                        logger_adc1e038.error(String.valueOf(requestid + " ZSR_PUR_INFO_OEM_Action-request-id=" + str[j][0] + "||CGZZ=" + str[j][1] + "||CGZ=" + str[j][2] + "||CPWL=" + str[j][3] + "||GYSZHHERPBM=" + str[j][4] + "||DDDW=" + str[j][5] + "||ZHZ=" + str[j][6] + "||JBDW=" + str[j][7] + "||ZXSL=" + str[j][8] + "||BZSL=" + str[j][9] + "||JHSJ=" + str[j][10] + "||XSGMSDM=" + str[j][11] + "||JLFL=" + str[j][12] + "||YXQSRQ=" + str[j][13] + "||YXJZRQ=" + str[j][14] + "||OEMZZZJ=" + str[j][15] + "||JGDW=" + str[j][16] + "||GYSWLZ=" + str[j][17] + "||====" + str[j][18] + "||HB=" + str[j][19]));
                        j++;
                    }
                    logger_adc1e038.error(String.valueOf(requestid + "传输明细行数：" + j));
                    ZSRM_PUR_INFO info = new ZSRM_PUR_INFO();
                    String[] ret = info.Getexecute(str);
                    state = ret[0];
                    logger_adc1e038.error(String.valueOf("ZSR_PUR_INFO_OEM_Action-return-" + requestid + "-[" + ret[0] + "," + ret[1] + "]"));
                    sb.append("信息记录新增结果：" + ret[1]);
                }
                BillFieldUtil util = new BillFieldUtil();
                sql = "update e10_core_business.dbo." + tablename + " set state='" + state + "',message='" + sb.toString() + "' where id =" + requestid;
                logger_adc1e038.error("update sql -----"+ sql);
                String poolname_d9 = CONN_TYPE.workflow.getType();
                // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                boolean b = rs.executeSql(sql, poolname_d9);
                logger_adc1e038.error("b -----"+ b);
            } catch (Exception e) {
                logger_adc1e038.error("ZSR_PUR_INFO_OEM_Action-error-" ,e);
                requestinfo.getRequestManager().setMessagecontent("调用SAP接口同步数据出错：" + e.toString());
                return  WeaResult.fail(500, "调用SAP接口同步数据出错：" + e, getResultMapForAction(weaverResultMap, "result", "", requestinfo.getRequestManager()));
            }
            logger_adc1e038.error(String.valueOf("ZSRM_PUR_INFO_Action-end-" + requestid));
            return WeaResult.success(getResultMapForAction(weaverResultMap, "result", Action.SUCCESS, requestinfo.getRequestManager()));
        } catch (Exception e) {
            e.printStackTrace();
            logger_adc1e038.error("ZSR_PUR_INFO_OEM_Action e: {}", e.getMessage());
            return  WeaResult.fail(500, "ZSR_PUR_INFO_OEM_Action e: {}：" + e, getResultMapForAction(weaverResultMap, "result", "", 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;
    }
}
