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

import  com.weaver.seconddev.interfaces.swfa.BillFieldUtil;
import java.text.SimpleDateFormat;
import java.util.HashMap;
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 java.util.Map;
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_ZOA_MM_PR_CREATE_JGJ_JgAction")
public class ZOA_MM_PR_CREATE_JGJ_JgAction extends BaseBean implements Action, EsbServerlessRpcRemoteInterface {

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

    private static final Logger logger_56a61d8 = LoggerFactory.getLogger(ZOA_MM_PR_CREATE_JGJ_JgAction.class);

    public WeaResult<Map<String, Object>> execute(Map<String, Object> requestInfoMap) {
        logger_56a61d8.error("ZOA_MM_PR_CREATE_JGJ_JgAction 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 {
            try {
                RecordSet rs1 = I18nContextUtil.getBean(RecordSet.class);
                ResourceComInfo hr = I18nContextUtil.getBean(ResourceComInfo.class);
                BillFieldUtil unit = new BillFieldUtil();
                // 采购申请类型 在建工程-ZPR4；备品备件-ZPR2
                String prtype = "";
                // 采购组  在建工程-140；备品备件-110
                String cgz = "";
                // 申请人
                String sqr = "";
                // 申请人姓名
                String sqrxm = "";
                // 申请人工号
                String code = "";
                // 科目类别
                String kmlb = "F";
                int xmh = 0;
                String[][] prdetail = null;
                // 流程请求ID
                String reid = request.getRequestid();
                // 接单意见 0 全部同意接单 1 非全部同意接单 2 不满足退回 3 线缆接单 4 智能接单
                String jdyj = "";
                // 获取表单主字段信息
                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 (name.equals("SQR")) {
                        sqr = value;
                    }
                    if (name.equals("JDYJ")) {
                        jdyj = value;
                    }
                }
                if (!sqr.equals("")) {
                    // 申请人工号
                    code = unit.getWorkcode(sqr);
                    // 获取申请人姓名
                    sqrxm = hr.getResourcename(sqr);
                }
                // 获取明细表
                DetailTable[] detailtable = request.getDetailTableInfo().getDetailTable();
                // 指定明细表
                DetailTable dtq = detailtable[0];
                // 当前明细表的所有数据,按行存储
                Row[] sq = dtq.getRow();
                if (sq != null && sq.length > 0) {
                    Cell[] cellinfo = sq[0].getCell();
                    HashMap<String, String> mMap = new HashMap<String, String>();
                    for (int i = 0; i < cellinfo.length; i++) {
                        mMap.put(cellinfo[i].getName().toUpperCase(), Util.null2String(cellinfo[i].getValue()));
                    }
                    // 采购类型
                    String type = mMap.get("CGLX");
                    if ("0".equals(type)) {
                        prtype = "ZPR2";
                    } else if ("1".equals(type)) {
                        prtype = "ZPR4";
                    } else if ("2".equals(type)) {
                        // 维修
                        prtype = "ZPR3";
                        kmlb = "K";
                    } else if ("3".equals(type)) {
                        // 研发项目 7726104
                        prtype = "ZPR4";
                    }
                    if ("ZPR4".equals(prtype) || "ZPR3".equals(prtype)) {
                        // 在建工程-ZPR4 维修-ZPR3
                        if ("ZPR4".equals(prtype)) {
                            cgz = "140";
                        } else {
                            cgz = "130";
                        }
                        prdetail = new String[sq.length][15];
                        for (int j = 0; j < sq.length; j++) {
                            xmh = xmh + 10;
                            // prdetail[j][0] = j+1+""; //项目号
                            prdetail[j][0] = String.valueOf(xmh);
                            // 科目类别
                            prdetail[j][1] = kmlb;
                            // 采购组
                            prdetail[j][8] = cgz;
                            // 申请者
                            prdetail[j][9] = code;
                            // 指定行
                            Row rq = sq[j];
                            // 每行数据再按列存储
                            Cell[] cq = rq.getCell();
                            for (int k = 0; k < cq.length; k++) {
                                // 指定列
                                Cell cq1 = cq[k];
                                // 明细字段名称
                                String nameq = cq1.getName().toUpperCase();
                                // 明细字段的值
                                String valueq = Util.null2String(cq1.getValue());
                                // 物料描述
                                if (nameq.equals("WLMS")) {
                                    prdetail[j][2] = valueq.trim();
                                }
                                // 数量
                                if (nameq.equals("SL")) {
                                    prdetail[j][3] = valueq;
                                }
                                // 单位码
                                if (nameq.equals("DWM")) {
                                    prdetail[j][4] = unit.getUnitno(valueq).trim();
                                }
                                // 交期
                                if (nameq.equals("JHRQ")) {
                                    prdetail[j][5] = valueq.replace("-", "");
                                }
                                // 物料组
                                if (nameq.equals("WLZ")) {
                                    prdetail[j][6] = valueq.split(" ")[0];
                                }
                                // 工厂
                                if (nameq.equals("GC")) {
                                    prdetail[j][7] = valueq;
                                }
                                // 内部订单
                                if (nameq.equals("NBDD")) {
                                    prdetail[j][10] = valueq.split(" ")[0];
                                }
                                // 备注
                                if (nameq.equals("BZ")) {
                                    prdetail[j][11] = valueq.trim();
                                }
                                // 库存地点
                                if (nameq.equals("SHDZ")) {
                                    if (valueq != null && !"".equals(valueq)) {
                                        prdetail[j][12] = valueq.trim().substring(0, 4);
                                    } else {
                                        prdetail[j][12] = "";
                                    }
                                }
                                // 是否接单
                                if (nameq.equals("SFJD")) {
                                    if ("0".equals(valueq)) {
                                        if ("3".equals(jdyj)) {
                                            prdetail[j][13] = "线缆接单";
                                        } else if ("4".equals(jdyj)) {
                                            prdetail[j][13] = "智能接单";
                                        } else {
                                            prdetail[j][13] = "是";
                                        }
                                    } else {
                                        prdetail[j][13] = "否";
                                    }
                                }
                                if ("ZPR3".equals(prtype)) {
                                    // 成本中心
                                    if (nameq.equals("CBZX")) {
                                        prdetail[j][14] = valueq.trim();
                                    }
                                }
                            }
                        }
                    } else if ("ZPR2".equals(prtype)) {
                        // 备品备件
                        cgz = "110";
                        prdetail = new String[sq.length][10];
                        for (int j = 0; j < sq.length; j++) {
                            xmh = xmh + 10;
                            // prdetail[j][0] = j+1+""; //项目号
                            prdetail[j][0] = String.valueOf(xmh);
                            // 采购组
                            prdetail[j][4] = cgz;
                            // 申请者
                            prdetail[j][5] = code;
                            // 指定行
                            Row rq = sq[j];
                            // 每行数据再按列存储
                            Cell[] cq = rq.getCell();
                            for (int k = 0; k < cq.length; k++) {
                                // 指定列
                                Cell cq1 = cq[k];
                                // 明细字段名称
                                String nameq = cq1.getName().toUpperCase();
                                // 明细字段的值
                                String valueq = Util.null2String(cq1.getValue());
                                // 物料编码
                                if (nameq.equals("WLBM")) {
                                    prdetail[j][1] = valueq.trim();
                                }
                                // 数量
                                if (nameq.equals("SL")) {
                                    prdetail[j][2] = valueq;
                                }
                                // 交期
                                if (nameq.equals("JHRQ")) {
                                    prdetail[j][3] = valueq.replace("-", "");
                                }
                                // 工厂
                                if (nameq.equals("GC")) {
                                    prdetail[j][6] = valueq;
                                }
                                // 备注
                                if (nameq.equals("BZ")) {
                                    prdetail[j][7] = valueq.trim();
                                }
                                // 库存地点
                                if (nameq.equals("SHDZ")) {
                                    if (valueq != null && !"".equals(valueq)) {
                                        prdetail[j][8] = valueq.trim().substring(0, 4);
                                    } else {
                                        prdetail[j][8] = "";
                                    }
                                }
                                // 是否接单
                                if (nameq.equals("SFJD")) {
                                    if ("0".equals(valueq)) {
                                        if ("3".equals(jdyj)) {
                                            prdetail[j][9] = "线缆接单";
                                        } else if ("4".equals(jdyj)) {
                                            prdetail[j][9] = "智能接单";
                                        } else {
                                            prdetail[j][9] = "是";
                                        }
                                    } else {
                                        prdetail[j][9] = "否";
                                    }
                                }
                            }
                        }
                    }
                }
                String tablename = "";
                String wfid = request.getWorkflowid();
//                tablename = unit.getTablename(wfid);
                tablename = request.getRequestManager().getBillTableName();
                ZOA_MM_PR_CREATE_JGJ po = new ZOA_MM_PR_CREATE_JGJ();
                String[] fhz = po.Getexecute(prtype, prdetail);
                String cgsqh = fhz[0];
                String sta = fhz[1];
                String meg = fhz[2].replace("'", "’");
                Date now = new Date();
                SimpleDateFormat datetype = new SimpleDateFormat("yyyy-MM-dd");
                SimpleDateFormat timetype = new SimpleDateFormat("HH:mm");
                String date = datetype.format(now);
                String time = timetype.format(now);
                String output = date + "," + time + "," + meg;
                String logsql = "update e10_core_business.dbo." + tablename + " set cgsqh ='" + cgsqh + "', state = '" + sta + "', message = '" + output + "' where id = " + reid;
                String poolname = CONN_TYPE.workflow.getType();
                // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                boolean b = rs1.executeSql(logsql, poolname);
                logger_56a61d8.error("b--" + b);
                logger_56a61d8.error(String.valueOf("start log--" + code + "--" + sqrxm));
                logger_56a61d8.error(String.valueOf("------------------------------------------------------------------------"));
                logger_56a61d8.error(String.valueOf("ZOA_MM_PR_CREATE_JGJ_JgAction:" + logsql));
                logger_56a61d8.error(String.valueOf("------------------------------------------------------------------------"));
                logger_56a61d8.error(String.valueOf("end log--" + code + "--" + sqrxm));
                logger_56a61d8.error("sta"+sta+"--"+",meg"+meg);
                if (!"S".equals(sta)) {
                    request.getRequestManager().setMessagecontent("SAP返回错误信息：" + output);
                    return  WeaResult.fail(500, "SAP返回错误信息：" + output, getResultMapForAction(weaverResultMap, "result",output, request.getRequestManager()));
                }
            } catch (Exception e) {
                // BaseBean baseBean = new BaseBean();
                logger_56a61d8.error(String.valueOf("start log"));
                logger_56a61d8.error(String.valueOf("------------------------------------------------------------------------"));
                logger_56a61d8.error(String.valueOf("ZOA_MM_PR_CREATE_JGJ_JgAction error:" + e.toString()));
                logger_56a61d8.error(String.valueOf("------------------------------------------------------------------------"));
                logger_56a61d8.error(String.valueOf("end log"));
                logger_56a61d8.error("ZOA_MM_PR_CREATE_JGJ_JgAction error: {}", e);
                request.getRequestManager().setMessagecontent("SAP返回错误信息：" + e.toString());
                return  WeaResult.fail(500, "SAP返回错误信息："+ e, getResultMapForAction(weaverResultMap, "result", e.getMessage(), request.getRequestManager()));
            }
            return WeaResult.success(getResultMapForAction(weaverResultMap, "result", Action.SUCCESS, request.getRequestManager()));
        } catch (Exception e) {
            e.printStackTrace();
            logger_56a61d8.error("ZOA_MM_PR_CREATE_JGJ_JgAction e: {}", e.getMessage());
            return  WeaResult.fail(500, "ZOA_MM_PR_CREATE_JGJ_JgAction e: {}"+ e, getResultMapForAction(weaverResultMap, "result", e.getMessage(), request.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;
    }
}
