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

import java.text.SimpleDateFormat;
import  com.weaver.seconddev.interfaces.oames.CallMesKeSuService;
import  com.weaver.seconddev.interfaces.oames.OA_KSJXCL_SERVICEStub;
import  com.weaver.seconddev.interfaces.swfa.BillFieldUtil;
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 java.util.HashMap;
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.Cell;
import com.weaver.verupgrade.soa.workflow.request.DetailTable;
import com.weaver.verupgrade.soa.workflow.request.Property;
import com.weaver.verupgrade.soa.workflow.request.Row;
import com.weaver.verupgrade.interfaces.workflow.action.Action;

/**
 * SRM--亨通光电客诉及退换货申请接口--
 *
 * @author Administrator
 */
@org.springframework.stereotype.Service("workflow_action_HTGD_SW_OaBackAction")
public class HTGD_SW_OaBackAction extends BaseBean implements Action, EsbServerlessRpcRemoteInterface {

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

    private static final Logger logger_e4a191d3 = LoggerFactory.getLogger(HTGD_SW_OaBackAction.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 request = requestInfoTemp.getRequestInfo(requestIdTemp, userIdTemp);
        try {
            try {
                String[][] prdetail = null;
                // 流程编号
                String lcbh = "";
                // 申请日期
                String sqrq = "";
                // 申请人
                String sqr = "";
                // 申请人姓名
                String sqrxm = "";
                // 申请人部门
                String sqrbm = "";
                // 问题分类
                String wtfl = "";
                // 申请部门
                String sqbm = "";
                // 销售组
                String xsz = "";
                // 销售办公室
                String xsbgs = "";
                // 工程派人
                String gcpr = "";
                // 退/换货赔偿
                String thhpc = "";
                // 本年度累计退换货次数
                String bndljthhcs = "";
                // 质量部门判定是否派人
                String zlbpdsfpr = "";
                // 质量部判定是否退换货/赔偿
                String zlbpdsfthh = "";
                // 退货产品类别
                String thcplb = "";
                // 退货单位全称
                String thdwqc = "";
                // SAP号
                String saph = "";
                // MES号
                String mesh = "";
                // 订单类型
                String ddlx = "";
                // 退货总金额
                String thzje = "";
                // 退货原因
                String thyy = "";
                // 协调情况
                String xtqk = "";
                // 办事处负责人
                String bscfzr = "";
                // 退货总数量
                String thzsl = "";
                int id = 0;
                Date now = new Date();
                SimpleDateFormat datetype = new SimpleDateFormat("yyyy-MM-dd");
                sqrq = datetype.format(now);
                // 流程请求ID
                String requestId = request.getRequestid();
                logger_e4a191d3.error(String.valueOf("获取requestId:=" + requestId));
                // 工作流ID
                String Id = request.getWorkflowid();
                // 主表字段赋值
                // 获取表单主字段信息
                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("LCBH")) {
                        // 流程编号
                        lcbh = value.trim();
                    }
                    if (name.equals("SQBM")) {
                        // 申请部门
                        sqbm = value;
                    }
                    if (name.equals("SQRQ")) {
                        // 申请日期
                        sqrq = value;
                    }
                    if (name.equals("WTFL")) {
                        // 问题分类
                        wtfl = value;
                    }
                    if (name.equals("XSBGS")) {
                        // 销售组
                        xsz = value;
                    }
                    if (name.equals("XSZ")) {
                        // 销售办公室
                        xsbgs = value;
                    }
                    if (name.equals("GCPR")) {
                        // 工程派人
                        gcpr = value;
                    }
                    if (name.equals("THHPC")) {
                        // 退换货赔偿
                        thhpc = value.trim();
                    }
                    if (name.equals("CDWBNDLJTHCS")) {
                        // 本年度累计退换货次数
                        bndljthhcs = value;
                    }
                    if (name.equals("ZLBPDSFTHH")) {
                        // 质量部判定是否退换货
                        zlbpdsfthh = value;
                    }
                    if (name.equals("ZLBPDSFPR")) {
                        // 质量部判定是否派人
                        zlbpdsfpr = value.trim();
                    }
                    if (name.equals("THCPLB")) {
                        // 退货产品类别
                        thcplb = value.trim();
                    }
                    if (name.equals("THDW")) {
                        // 退货单位全称
                        thdwqc = value.trim();
                    }
                    if (name.equals("SAPH")) {
                        // SAP号
                        saph = value.trim();
                    }
                    if (name.equals("MESH")) {
                        // MES号
                        mesh = value.trim();
                    }
                    if (name.equals("DDLX")) {
                        // 订单类型
                        ddlx = value.trim();
                    }
                    if (name.equals("THZJE")) {
                        // 退货总金额
                        thzje = value;
                    }
                    if (name.equals("THYY")) {
                        // 退货原因
                        thyy = value.trim();
                    }
                    if (name.equals("XTQK")) {
                        // 协调情况
                        xtqk = value.trim();
                    }
                    if (name.equals("BSCFZR")) {
                        // 办事处负责人
                        bscfzr = value;
                    }
                    if (name.equals("THZSL")) {
                        // 退货总数量
                        thzsl = value;
                    }
                }
                // 将申请人信息由代号转换为真实信息
                ResourceComInfo hr = I18nContextUtil.getBean(ResourceComInfo.class);
                BillFieldUtil unit = new BillFieldUtil();
                logger_e4a191d3.error(String.valueOf("开始 将申请人信息由代号转换为真实信息"));
                if (!sqr.equals("")) {
                    // 获取申请人姓名
                    sqrxm = hr.getResourcename(sqr);
                }
                if (!sqr.equals("")) {
                    // 获取申请人部门
                    sqrbm = unit.getDepartmentname(sqbm);
                }
                if (!bscfzr.equals(bscfzr)) {
                    // 办事处负责人
                    bscfzr = hr.getResourcename(bscfzr);
                }
                logger_e4a191d3.error(String.valueOf("代号转为真实信息结束" + "\t" + "申请人" + sqrxm + "问题分类：" + wtfl));
                try {
                    id = Integer.parseInt(Id);
                } catch (NumberFormatException e) {
                    System.err.println(e.toString());
                    logger_e4a191d3.error(String.valueOf("明细表强制转换传值报错 " + e.toString()));
                }
                // 获取明细表
                logger_e4a191d3.error(String.valueOf("明细表开始取值"));
                DetailTable[] detailtable = request.getDetailTableInfo().getDetailTable();
                // 指定明细表
                DetailTable dtq = detailtable[0];
                // 当前明细表的所有数据,按行存储
                Row[] sq = dtq.getRow();
                logger_e4a191d3.error(String.valueOf("明细表临时存放dtq中" + dtq));
                prdetail = new String[sq.length][6];
                OA_KSJXCL_SERVICEStub.ArrayOfOA_KSJTHHLC_ITEMS_TYPE arrayItems = new OA_KSJXCL_SERVICEStub.ArrayOfOA_KSJTHHLC_ITEMS_TYPE();
                logger_e4a191d3.error(String.valueOf("For循环开始赋值"));
                for (int j = 0; j < sq.length; j++) {
                    OA_KSJXCL_SERVICEStub.OA_KSJTHHLC_ITEMS_TYPE item = new OA_KSJXCL_SERVICEStub.OA_KSJTHHLC_ITEMS_TYPE();
                    // 指定行
                    Row rq = sq[j];
                    // 每行数据再按列存储
                    Cell[] cq = rq.getCell();
                    // RequestId
                    prdetail[j][0] = requestId;
                    logger_e4a191d3.error(String.valueOf("Id的值赋为requestId:" + prdetail[j][0]));
                    for (int k = 0; k < cq.length; k++) {
                        // 指定列
                        Cell cq1 = cq[k];
                        // 明细字段名称
                        String nameq = cq1.getName().toUpperCase();
                        // 明细字段的值
                        String valueq = Util.null2String(cq1.getValue());
                        // 退货产品规格型号
                        try {
                            if (nameq.equals("THCPGGXH")) {
                                prdetail[j][1] = valueq.trim();
                                logger_e4a191d3.error(String.valueOf("取退货产品规格型号的值：" + prdetail[j][1]));
                                item.setTHCPGGXH(prdetail[j][1]);
                            }
                            // 退货单价
                            if (nameq.equals("THDJ")) {
                                prdetail[j][2] = valueq.trim();
                                logger_e4a191d3.error(String.valueOf("取退货单价的值：" + prdetail[j][2]));
                                // 取值结束，直接赋值
                                item.setTHDJ(Double.parseDouble(prdetail[j][2]));
                                logger_e4a191d3.error("赋退货单价的值给item：" + item.getTHDJ());
                            }
                            // 退货数量
                            if (nameq.equals("THSL")) {
                                prdetail[j][3] = valueq.trim();
                                logger_e4a191d3.error(String.valueOf("取退货数量的值：" + prdetail[j][3]));
                                item.setTHSL(Double.parseDouble(prdetail[j][3]));
                                logger_e4a191d3.error("赋退货单价的值给item：" + item.getTHSL());
                            }
                            // 退货金额
                            if (nameq.equals("THJE")) {
                                prdetail[j][4] = valueq.trim();
                                logger_e4a191d3.error(String.valueOf("取退金额的值：" + prdetail[j][4]));
                                item.setTHJE(Double.parseDouble(prdetail[j][4]));
                                logger_e4a191d3.error("赋退货单价的值给item：" + item.getTHJE());
                            }
                            // 退货盘数
                            if (nameq.equals("THPS")) {
                                prdetail[j][5] = valueq.trim();
                                logger_e4a191d3.error(String.valueOf("取退货盘数的值：" + prdetail[j][5]));
                                item.setTHPS(Integer.parseInt(prdetail[j][5]));
                                logger_e4a191d3.error("赋退货单价的值给item：" + item.getTHPS());
                            }
                            logger_e4a191d3.error(String.valueOf("For循环取值结束"));
                            logger_e4a191d3.error("名细表的值放到arrayItem数值中：" + arrayItems);
                        } catch (NumberFormatException e) {
                            logger_e4a191d3.error(e.toString());
                            logger_e4a191d3.error(String.valueOf("明细表强制转换传值报错 " + e.toString()));
                        }
                    }
                    try {
                        arrayItems.addOA_KSJTHHLC_ITEMS_TYPE(item);
                        logger_e4a191d3.error("名细表的值放到arrayItem数值中：" + arrayItems);
                    } catch (NumberFormatException e) {
                        System.err.println(e.toString());
                        logger_e4a191d3.error(String.valueOf("明细表存值到item报错" + e.toString()));
                    }
                }
                OA_KSJXCL_SERVICEStub.OA_KSJTHHLC_HEADER_TYPE param_data = new OA_KSJXCL_SERVICEStub.OA_KSJTHHLC_HEADER_TYPE();
                OA_KSJXCL_SERVICEStub.ArrayOfOA_KSJTHHLC_HEADER_TYPE param_datas = new OA_KSJXCL_SERVICEStub.ArrayOfOA_KSJTHHLC_HEADER_TYPE();
                OA_KSJXCL_SERVICEStub.OA_KSJTHHLC resultin = new OA_KSJXCL_SERVICEStub.OA_KSJTHHLC();
                try {
                    logger_e4a191d3.error(String.valueOf("主表信息开始赋值"));
                    param_data.setID(id);
                    param_data.setLCBH(lcbh);
                    param_data.setSQRQ(sqrq);
                    param_data.setSQBM(sqrbm);
                    // 后期增加字段   避免更改接口，申请单位代值
                    param_data.setSQDW(wtfl);
                    param_data.setXSZ(xsz);
                    param_data.setXSBGS(xsbgs);
                    param_data.setSQR(sqrxm);
                    param_data.setGCPR(gcpr);
                    param_data.setTHHPC(thhpc);
                    param_data.setZLBPDSFPR(zlbpdsfpr);
                    param_data.setZLBPDSFTHH(zlbpdsfthh);
                    param_data.setTHCPLB(thcplb);
                    param_data.setTHDWQC(thdwqc);
                    param_data.setSAPH(saph);
                    param_data.setMESH(mesh);
                    param_data.setDDLX(ddlx);
                    param_data.setTHYY(thyy);
                    param_data.setXTQK(xtqk);
                    param_data.setBSCFZR(bscfzr);
                    param_data.setREQUESTID(Integer.parseInt(requestId));
                    param_data.setBNDLJTHHCS(Integer.parseInt(bndljthhcs));
                    param_data.setTHZJE(Double.parseDouble(thzje));
                    param_data.setTHZSL(Double.parseDouble(thzsl));
                    logger_e4a191d3.error("主表信息赋值结束        如：协调情况取值为：    " + param_data.getXTQK());
                } catch (NumberFormatException e) {
                    System.err.println(e.toString());
                    logger_e4a191d3.error(String.valueOf("主表强制转换传值报错 " + e.toString()));
                }
                try {
                    // 封装信息
                    logger_e4a191d3.error(String.valueOf("开始封装信息"));
                    param_data.setITEMS(arrayItems);
                    param_datas.addOA_KSJTHHLC_HEADER_TYPE(param_data);
                    resultin.setITFID("IFTIF001");
                    resultin.setWERKS("A000");
                    resultin.setDATAS(param_datas);
                    logger_e4a191d3.error("封装信息结束：" + resultin);
                } catch (NumberFormatException e) {
                    System.err.println(e.toString());
                    logger_e4a191d3.error(String.valueOf("封装报错 " + e.toString()));
                }
                logger_e4a191d3.error(String.valueOf("调用接口开始0 "));
                logger_e4a191d3.error(String.valueOf("调用接口完成RequestId--" + requestId + "--sqr--" + sqr + "--lcbh--" + lcbh + "--sqbm--" + sqbm + "--saph--" + saph));
                String sta = "";
                String meg = "";
                CallMesKeSuService mes = new CallMesKeSuService();
                // 修改过
                mes.setOainput(resultin);
                String[] rtInfo = mes.call();
                logger_e4a191d3.error(String.valueOf("调用接口完成RequestId--" + rtInfo[0] + "--Istat--" + rtInfo[1] + "--Srmsage--" + rtInfo[2]));
                sta = rtInfo[1];
                meg = rtInfo[2].replace("'", "’");
                String tablename = "";
                String wfid = request.getWorkflowid();
//                tablename = unit.getTablename(wfid);
                tablename = request.getRequestManager().getBillTableName();
                String logsql = "update e10_core_business.dbo." + tablename + " set sta ='" + sta + "', meg = '" + meg + "' where id = " + requestId;
                logger_e4a191d3.error(String.valueOf("logsql:" + logsql));
                RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
                String poolname = CONN_TYPE.workflow.getType();
                // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                boolean b = rs.executeSql(logsql, poolname);
                logger_e4a191d3.error(String.valueOf("b--" + b));
                logger_e4a191d3.error(String.valueOf("HTGD_SW_OaBackAction-Request: " + requestId + "完成"));
                if (!sta.equals("S")) {
                    request.getRequestManager().setMessageid("100001");
                    request.getRequestManager().setMessagecontent(meg);
                    return  WeaResult.fail(500, "HTGD_SW_OaBackAction 100001"+ meg, getResultMapForAction(weaverResultMap, "result",meg, request.getRequestManager()));

                }
                System.out.println(meg);
            } catch (Exception e) {
                System.err.println(e.toString());
                logger_e4a191d3.error(String.valueOf("调用接口报错 " + e.toString()));
                return  WeaResult.fail(500, "HTGD_SW_OaBackAction err"+ e, getResultMapForAction(weaverResultMap, "result",e.getMessage(), request.getRequestManager()));

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