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

import com.weaver.seconddev.interfaces.prop.ConfigProp;
import org.apache.commons.lang.StringEscapeUtils;
import  com.weaver.seconddev.interfaces.srmoa.OaSrmVenMatExtService;
import  com.weaver.seconddev.interfaces.srmoa.VenMatExtHandlerServiceServiceStub.SRM_OA_VENMATEXT_RESULT;
import  com.weaver.seconddev.interfaces.srmoa.VenMatExtHandlerServiceServiceStub.VenMatExtResultIn;
import  com.weaver.seconddev.interfaces.srmoa.VenMatExtHandlerServiceServiceStub.VenMatExtResultItemIn;
import java.util.HashSet;
import java.util.Set;
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.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;

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

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

    @Autowired
    private ConfigProp configProp;


    @Autowired
    private OaSrmVenMatExtService service ;
    private static final Logger logger_e97618d9 = LoggerFactory.getLogger(OaSrmVenMatExtAction.class);

    public OaSrmVenMatExtAction() {
    }

    public WeaResult<Map<String, Object>> execute(Map<String, Object> requestInfoMap) {
        logger_e97618d9.error("OaSrmVenMatExtAction 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 cllx = "";
            // 解冻开始日期
            String jdksrq = "";
            // 解冻结束日期
            String jdjsrq = "";
            // 解冻期限
            String wlhtjdqx = "";
            // 供应商名称
            String gysmc = "";
            // 供应商编码
            String gysbm = "";
            // 原因
            String reason = "";
            // 主表中的采购组织编码用于冻结和解冻
            String cgzzbmzb = "";
            // 线上线下供应商
            String xsxxgys = "";
            // 实际处理类型
            String sjcllx = "";
            // 1 原材料货源， 2 OEM货源
            String resourceType = "1";

            String gsmc = "";
            try {
                logger_e97618d9.error(String.valueOf(requestid + "GY104开始调用接口同步数据"));
                Property[] properties = requestinfo.getMainTableInfo().getProperty();
                for (int i = 0; i < properties.length; i++) {
                    String name = properties[i].getName().toUpperCase();
                    String value = Util.null2String(properties[i].getValue());
                    if ("CLLX".equals(name)) {
                        cllx = value;
                    }
                    if ("JDKSRQ".equals(name)) {
                        jdksrq = value;
                    }
                    if ("JDJSRQ".equals(name)) {
                        jdjsrq = value;
                    }
                    if ("WLHTJDQX".equals(name)) {
                        wlhtjdqx = value;
                    }
                    if ("GYSMC".equals(name)) {
                        gysmc = value;
                    }
                    if ("GYSBM".equals(name)) {
                        gysbm = value;
                    }
                    if ("QKSM".equals(name)) {
                        reason = value;
                    }
                    if ("CGZZBMZB".equals(name)) {
                        cgzzbmzb = value;
                    }
                    if ("XSXXGYS".equals(name)) {
                        xsxxgys = value;
                    }
                    if ("CLLX1".equals(name)) {
                        sjcllx = value;
                    }
                    if ("GYSLX".equals(name)) {
                        if ("16".equals(value) || "28".equals(value) || "29".equals(value)) {
                            // oem
                            resourceType = "2";
                        }
                    }
                    if("GSMC".equals(name)){
                        gsmc = value;
                    }
                }
                //申请单位 江苏华脉光电科技有限公司 不触发接口
                String gy103gsid = configProp.getGy103gsid();
                if(!"".equals(gsmc)&&!"".equals(gy103gsid)&&(","+gy103gsid+",").indexOf(","+gsmc+",")>=0){
                    logger_e97618d9.error(requestid+"sqdw:"+gsmc+" gy103gsid:"+gy103gsid);
                    return WeaResult.success(getResultMapForAction(weaverResultMap, "result", Action.SUCCESS, requestinfo.getRequestManager()));
                }
                if ("7".equals(cllx)) {
                    if ("1".equals(wlhtjdqx)) {
                        jdksrq = "长期";
                        jdjsrq = "长期";
                    }
                } else {
                    jdksrq = "";
                    jdjsrq = "";
                }
                if ("1".equals(xsxxgys)) {
                    String message = "线下供应商";
                    logger_e97618d9.error(String.valueOf(requestid + message));
                    return WeaResult.success(getResultMapForAction(weaverResultMap, "result", Action.SUCCESS, requestinfo.getRequestManager()));
                }
                logger_e97618d9.error(String.valueOf(requestid + "GY104--建议处理类型" + cllx));
                DetailTable[] detailtable = null;
                if (requestinfo != null && requestinfo.getDetailTableInfo() != null) {
                    detailtable = requestinfo.getDetailTableInfo().getDetailTable();
                }

                DetailTable dtq = null;
                if (detailtable != null && detailtable.length > 0) {
                    dtq = detailtable[0];
                }

                logger_e97618d9.error("dtq===> "+dtq);
                Row[] sq = null;
                if (dtq != null) {
                    logger_e97618d9.error("dtq != null===> "+dtq);
                    try {
                        // 尝试获取 dtq 的行
                        if (dtq.getRow() != null) {
                            sq = dtq.getRow();
                        }
                    } catch (NullPointerException e) {
                        // 捕获并记录异常信息
                        logger_e97618d9.error("调用 dtq.getRow() 时发生 NullPointerException: " + e.getMessage());
                    }
                }

                SRM_OA_VENMATEXT_RESULT param = new SRM_OA_VENMATEXT_RESULT();
                VenMatExtResultIn paramInfo = new VenMatExtResultIn();
                Set<String> set = new HashSet<String>();
                int length = 0;
                if(sq != null){
                    length = sq.length;
                }
                VenMatExtResultItemIn[] item = new VenMatExtResultItemIn[length];
                if (sq != null && ( "6".equals(cllx) || "7".equals(cllx))) {
                    for (int j = 0; j < sq.length; j++) {
                        // 指定行
                        Row rq = sq[j];
                        Cell[] cq = rq.getCell();
                        VenMatExtResultItemIn itemIn = new VenMatExtResultItemIn();
                        for (int k = 0; k < cq.length; k++) {
                            // 指定列
                            Cell cq1 = cq[k];
                            // 明细字段名称
                            String nameq = cq1.getName().toLowerCase();
                            // 明细字段的值
                            String valueq = Util.null2String(cq1.getValue());
                            if ("cgzzbm".equals(nameq)) {
                                set.add(valueq);
                                logger_e97618d9.error(String.valueOf("cgzzbm:" + valueq));
                            }
                            if ("wlh".equals(nameq)) {
                                logger_e97618d9.error(String.valueOf("wlh:" + valueq));
                                itemIn.setMaterialCode(valueq);
                            }
                            if ("wlms".equals(nameq)) {
                                String wlms = StringEscapeUtils.unescapeHtml(valueq.trim());
                                logger_e97618d9.error(String.valueOf("wlms:" + wlms));
                                // String wlms_half = full2HalfWidth(wlms);
                                // writeLog("wlms_half:"+wlms_half);
                                itemIn.setMaterialName(wlms);
                            }
                        }
                        item[j] = itemIn;
                    }
                }
                paramInfo.setRequestId("GY104/" + requestid);
                paramInfo.setVendorName(gysmc);
                paramInfo.setVendorCode(gysbm);
                paramInfo.setFreezeReason(reason);
                if ("6".equals(cllx) || "7".equals(cllx)) {
                    paramInfo.setItems(item);
                    paramInfo.setPurOrgCode((String) set.toArray()[0]);
                    paramInfo.setUnFreezonSDate(jdksrq);
                    paramInfo.setUnFreezonEDate(jdjsrq);
                } else {
                    paramInfo.setPurOrgCode(cgzzbmzb);
                }
                if ("4".equals(cllx) && "5".equals(sjcllx)) {
                    cllx = "7";
                } else {
                    cllx = Integer.parseInt(cllx) - 2 + "";
                }
                paramInfo.setHandleType(cllx);
                logger_e97618d9.error(String.valueOf(requestid + " resourceType:" + resourceType));
                paramInfo.setResourceType(resourceType);
                param.setInputTab(paramInfo);
//                OaSrmVenMatExtService service = new OaSrmVenMatExtService();
                // 
                String[] str = service.sendsrm(param, requestid);
                logger_e97618d9.error(String.valueOf(requestid + "str[0]:" + str[0] + "str[1]:" + str[1] + "str[2]:" + str[2]));
                if ("-1".equals(str[0])) {
                    logger_e97618d9.error(String.valueOf(requestid + "调用SRM货源关系接口出错：" + str[2] + "--" + str[1]));
                    requestinfo.getRequestManager().setMessageid("error");
                    requestinfo.getRequestManager().setMessagecontent("SRM返回错误信息：" + str[1]);
                    return  WeaResult.fail(500, "OaSrmVenMatExtAction str[1]"+ str[1], getResultMapForAction(weaverResultMap, "result",str[1], requestinfo.getRequestManager()));
                }
                logger_e97618d9.error(String.valueOf(requestid + "GY104调用接口同步数据完成"));
            } catch (Exception e) {
                logger_e97618d9.error(String.valueOf(requestid + "SRM接口返回错误信息：" + e.toString()));
                requestinfo.getRequestManager().setMessageid("error");
                requestinfo.getRequestManager().setMessagecontent(e.toString());
                return  WeaResult.fail(500, "OaSrmVenMatExtAction err"+ e, getResultMapForAction(weaverResultMap, "result",e.getMessage(), requestinfo.getRequestManager()));
            }
            return WeaResult.success(getResultMapForAction(weaverResultMap, "result", Action.SUCCESS, requestinfo.getRequestManager()));
        } catch (Exception e) {
            e.printStackTrace();
            logger_e97618d9.error("OaSrmVenMatExtAction e: {}", e.getMessage());
            return  WeaResult.fail(500, "OaSrmVenMatExtAction e: {}"+ e, getResultMapForAction(weaverResultMap, "result",e.getMessage(), requestinfo.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;
    }

}

