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

import com.weaver.common.base.entity.result.WeaResult;
import com.weaver.common.i18n.tool.util.I18nContextUtil;
import com.weaver.esb.api.rpc.EsbServerlessRpcRemoteInterface;
import com.weaver.seconddev.interfaces.htjt.util.TransUtil;
import com.weaver.seconddev.interfaces.srmoa.CallSrmVenMatExtsSevices;
import com.weaver.seconddev.interfaces.srmoa.VenMatExtsHandlerServiceServiceStub;
import com.weaver.seconddev.interfaces.swfa.BillFieldUtil;
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.interfaces.workflow.action.Action;
import com.weaver.verupgrade.soa.workflow.request.*;
import com.weaver.verupgrade.workflow.request.RequestManager;
import org.apache.commons.lang.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 供应商新货源扩充接口 校验
 */
@Service("workflow_action_AddVenMatExtsToSrmCheckAction")
public class AddVenMatExtsToSrmCheckAction extends BaseBean implements Action, EsbServerlessRpcRemoteInterface {

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

    @Autowired
    private CallSrmVenMatExtsSevices service;

    private static final Logger logger_81b57400 = LoggerFactory.getLogger(AddVenMatExtsToSrmCheckAction.class);

    @Override
    public WeaResult<Map<String, Object>> execute(Map<String, Object> requestInfoMap) {
        logger_81b57400.error("AddVenMatExtsToSrmCheckAction 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 {
            // 流程请求ID
            String requestId = request.getRequestid();
            TransUtil tu = new TransUtil();
            String workflowid = request.getWorkflowid();
//            String tablename = tu.getTableName(workflowid);
            String tablename = request.getRequestManager().getBillTableName();
            try {
                // 公司名字
                String companyName = "";
                // 公司编码
                String companyCode = "";
                // 申请人
                String applyUser = "";
                // 审核人
                String checkUser = "";
                // 处理类型（0.校验 1.货源扩充）
                String handleType = "0";
                // 1 原材料货源， 2 OEM货源
                String resourceType = "1";
                RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
                ResourceComInfo hr = I18nContextUtil.getBean(ResourceComInfo.class);
                BillFieldUtil unit = new BillFieldUtil();
                logger_81b57400.error(String.valueOf("AddVenMatExtsToSrmCheckAction-Request: " + requestId + "开始"));
                VenMatExtsHandlerServiceServiceStub.VenMatExtsRusultIn oainputvendor = new VenMatExtsHandlerServiceServiceStub.VenMatExtsRusultIn();
                // 封装单据主信息
                // 封装表单信息
                // 获取表单主字段信息
                Property[] properties = request.getMainTableInfo().getProperty();
                for (int i = 0; i < properties.length; i++) {
                    // 主表数据
                    // 字段名
                    String name = properties[i].getName().toLowerCase();
                    // 值
                    String value = Util.null2String(properties[i].getValue());
                    // 单据主信息使用
                    if (name.equals("gsbh")) {
                        // 公司编号
                        companyCode = value;
                    }
                    if (name.equals("gsmc")) {
                        // 公司名称
                        companyName = value;
                    }
                    if (name.equals("gh")) {
                        // 申请人
                        applyUser = value;
                    }
                    // if (name.equals("gylplfzr")){
                    // checkUser = value;  //审核人
                    // }
                    String ischeck = "";
                    if (name.equals("ischeck")) {
                        // 审核人
                        ischeck = value;
                    }
                    if ("sfoemhy".equals(name)) {
                        if ("0".equals(value)) {
                            // oem
                            resourceType = "2";
                        }
                    }
                    // if("0".equals(ischeck)) {
                    // handleType = "0";
                    // } else {
                    // handleType = "1";
                    // }
                }
                //TODO custom 已处理 获取Lastoperator
//                checkUser = hr.getResourcename(request.getLastoperator());
                checkUser = hr.getResourcename(String.valueOf(userIdTemp));

                oainputvendor.setRequestId(requestId);
                oainputvendor.setCompanyCode(companyCode);
                oainputvendor.setCompanyName(companyName);
                oainputvendor.setApplyUser(applyUser);
                oainputvendor.setCheckUser(checkUser);
                oainputvendor.setHandleType(handleType);
                logger_81b57400.error(String.valueOf(requestId + " resourceType:" + resourceType));
                oainputvendor.setResourceType(resourceType);
                logger_81b57400.error(String.valueOf(requestId + " AddVenMatExtsToSrmCheckAction-获取明细表信息: "));
                DetailTable[] detailtable = request.getDetailTableInfo().getDetailTable();
                // 指定明细表
                DetailTable dtq = detailtable[0];
                // 当前明细表的所有数据,按行存储
                Row[] sq = dtq.getRow();
                logger_81b57400.error(String.valueOf(requestId + " AddVenMatExtsToSrmCheckAction-明细表行数：" + sq.length));
                VenMatExtsHandlerServiceServiceStub.VenMatExtsRusultItemIn[] item = new VenMatExtsHandlerServiceServiceStub.VenMatExtsRusultItemIn[sq.length];
                for (int j = 0; j < sq.length; j++) {
                    // 指定行
                    Row rq = sq[j];
                    Cell[] cq = rq.getCell();
                    VenMatExtsHandlerServiceServiceStub.VenMatExtsRusultItemIn itemIn = new VenMatExtsHandlerServiceServiceStub.VenMatExtsRusultItemIn();
                    for (int k = 0; k < cq.length; k++) {
                        // 指定列
                        Cell cq1 = cq[k];
                        // 明细字段名称
                        String nameq = cq1.getName().toLowerCase();
                        // 明细字段的值
                        String valueq = Util.null2String(cq1.getValue());
                        if ("gysmc".equals(nameq)) {
                            // 供应商名称
                            itemIn.setVendorName(valueq);
                            logger_81b57400.error(String.valueOf(requestId + " 供应商名称：" + valueq));
                        }
                        if ("gysbm".equals(nameq)) {
                            // 供应商编码
                            itemIn.setVendorCode(valueq);
                            logger_81b57400.error(String.valueOf(requestId + " 供应商编码：" + valueq));
                        }
                        if ("cgzzbm".equals(nameq)) {
                            // 采购组织编码
                            itemIn.setPurOrgCode(valueq);
                            logger_81b57400.error(String.valueOf(requestId + " 采购组织编码：" + valueq));
                        }
                        if ("wlh".equals(nameq)) {
                            // 物料编码/物料号
                            itemIn.setMaterialCode(valueq);
                            logger_81b57400.error(String.valueOf(requestId + " 物料编码/物料号：" + valueq));
                        }
                        if ("wlms".equals(nameq)) {
                            // 物料描述/物料名称
                            // String wlms = StringEscapeUtils.unescapeHtml(valueq.trim());
                            // itemIn.setMaterialName(wlms);
                            String wlms = StringEscapeUtils.unescapeHtml(valueq.trim());
                            logger_81b57400.error(String.valueOf(requestId + " wlms:" + wlms));
                            // String wlms_half = full2HalfWidth(wlms);
                            // writeLog(requestId+" wlms_half:"+wlms_half);
                            itemIn.setMaterialName(wlms);
                        }
                        if ("jxzb".equals(nameq)) {
                            // 绩效占比
                            itemIn.setWeight(valueq);
                        }
                        if ("wlzbm".equals(nameq)) {
                            // 物料组编码
                            itemIn.setMatCategoryCode(valueq);
                        }
                        if ("wlzmc".equals(nameq)) {
                            // 物料组名称
                            itemIn.setMatCategoryName(valueq);
                        }
                        if ("clfl".equals(nameq)) {
                            // 物料类型
                            // String clfl = unit.getselectName(valueq,"70526");//测试环境-63098 正式环境-70526
                            String clfl = tu.getSelectName(tablename, "clfl", valueq);
                            itemIn.setMatLevel(clfl);
                            logger_81b57400.error(String.valueOf(requestId + " 物料编码/物料号：" + clfl));
                        }
                    }
                    item[j] = itemIn;
                }
                oainputvendor.setItems(item);
//                CallSrmVenMatExtsSevices service = new CallSrmVenMatExtsSevices();
                logger_81b57400.error(requestId + "-------AddVenMatExtsToSrmCheckAction请求数据----" + oainputvendor);
                // 
                String[] str = service.call(oainputvendor, requestId);
                String isTat = str[1];
                String msg = str[2];
                logger_81b57400.error(String.valueOf(requestId + " GY137供应商新货源扩充接口数据返回值：" + isTat + "--" + msg));
                if (!isTat.equals("S")) {
                    request.getRequestManager().setMessageid("error");
                    request.getRequestManager().setMessagecontent(msg);
                    return WeaResult.fail(500, "执行失败:"+msg, getResultMapForAction(weaverResultMap, "result", FAILURE_AND_CONTINUE, request.getRequestManager()));
                }
            } catch (Exception e) {
                request.getRequestManager().setMessageid("error");
                request.getRequestManager().setMessagecontent("SRM接口返回错误信息：" + e.toString());
                logger_81b57400.error(requestId + "AddVenMatExtsToSrmCheckAction-Request出错: " ,e);
                return WeaResult.fail(500, "执行失败:SRM接口返回错误信息：" + e , getResultMapForAction(weaverResultMap, "result", FAILURE_AND_CONTINUE, request.getRequestManager()));
            }
            return WeaResult.success(getResultMapForAction(weaverResultMap, "result", Action.SUCCESS, request.getRequestManager()));
        } catch (Exception e) {
            e.printStackTrace();
            logger_81b57400.error("AddVenMatExtsToSrmCheckAction e: {}", e);
            return WeaResult.success(getResultMapForAction(weaverResultMap, "result", WeaResult.fail(500, "执行异常:"+e, getResultMapForAction(weaverResultMap, "result", e.getMessage(), request.getRequestManager())), request.getRequestManager()));
        }
    }

    /**
     * 全角字符串转半角字符串，比如“（”--->"("
     */
    public static String full2HalfWidth(String str) {
        String outStr = "";
        String Tstr = "";
        byte[] b = null;
        if (str != null) {
            for (int i = 0; i < str.trim().length(); i++) {
                try {
                    Tstr = str.substring(i, i + 1);
                    b = Tstr.getBytes("unicode");
                } catch (java.io.UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                if (b[2] == -1) {
                    b[3] = (byte) (b[3] + 32);
                    b[2] = 0;
                    try {
                        outStr = outStr + new String(b, "unicode");
                    } catch (java.io.UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                } else {
                    outStr = outStr + Tstr;
                }
            }
        }
        return outStr;
    }

    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;
    }
}
