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

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

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.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.Cell;
import com.weaver.verupgrade.soa.workflow.request.DetailTable;
import com.weaver.verupgrade.soa.workflow.request.DetailTableInfo;
import com.weaver.verupgrade.soa.workflow.request.MainTableInfo;
import com.weaver.verupgrade.soa.workflow.request.Property;
import com.weaver.verupgrade.soa.workflow.request.Row;
import com.weaver.verupgrade.interfaces.workflow.action.Action;

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

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


    @Autowired
    private OaSrmVenMatExtService service ;

    @Autowired
    private ConfigProp configProp;

    private static final Logger logger_ac19fc9b = LoggerFactory.getLogger(OaSrmVenMatExtCheckAction.class);

    public WeaResult<Map<String, Object>> execute(Map<String, Object> requestInfoMap) {
        logger_ac19fc9b.error("OaSrmVenMatExtCheckAction 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 = "";
            // 1 原材料货源， 2 OEM货源
            String resourceType = "1";
            String gsmc = "";
            try {
                logger_ac19fc9b.error(String.valueOf(new StringBuilder().append(requestid).append("GY104开始调用接口校验数据").toString()));
                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 ("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_ac19fc9b.error(requestid+"sqdw:"+gsmc+" gy103gsid:"+gy103gsid);
                    return WeaResult.success(getResultMapForAction(weaverResultMap, "result", Action.SUCCESS, requestinfo.getRequestManager()));
                }
                if ("4".equals(cllx)) {
                    if ("1".equals(wlhtjdqx)) {
                        jdksrq = "长期";
                        jdjsrq = "长期";
                    }
                } else {
                    jdksrq = "";
                    jdjsrq = "";
                }
                logger_ac19fc9b.error(String.valueOf(new StringBuilder().append(requestid).append("GY104--建议处理类型").append(cllx).toString()));
                DetailTable[] detailtable = requestinfo.getDetailTableInfo().getDetailTable();
                DetailTable dtq = null;
                if(detailtable.length > 0){dtq = detailtable[0];}
                Row[] sq = null;
                if(dtq != null){
                    sq = dtq.getRow();
                    logger_ac19fc9b.error(String.valueOf(new StringBuilder().append(requestid).append("明细行数：").append(sq.length).toString()));
                }
                if (Integer.parseInt(cllx) < 6) {
                    if ( sq  != null && sq.length > 0) {
                        logger_ac19fc9b.error(String.valueOf(new StringBuilder().append(requestid).append("建议处理类型为供应商冻结、解冻、淘汰的，请不要填写明细项！").toString()));
                        requestinfo.getRequestManager().setMessageid("error");
                        requestinfo.getRequestManager().setMessagecontent("建议处理类型为供应商冻结、解冻、淘汰的，请不要填写明细项！");
                        return WeaResult.fail(500, "执行失败", getResultMapForAction(weaverResultMap, "result", FAILURE_AND_CONTINUE, requestinfo.getRequestManager()));
                    }
                } else if (("6".equals(cllx)) || ("7".equals(cllx))) {
                    Set set = new HashSet();
                    Set<String> wlhset = new HashSet<String>();
                    List<String> list = new ArrayList<String>();
                    StringBuilder sb = new StringBuilder();
                    if ( sq  != null && (sq.length <= 300) && (sq.length > 0)) {
                        SRM_OA_VENMATEXT_RESULT param = new SRM_OA_VENMATEXT_RESULT();
                        VenMatExtResultIn paramInfo = new VenMatExtResultIn();
                        VenMatExtResultItemIn[] item = new VenMatExtResultItemIn[sq.length];
                        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_ac19fc9b.error(String.valueOf(new StringBuilder().append("cgzzbm:").append(valueq).toString()));
                                }
                                if ("wlh".equals(nameq)) {
                                    logger_ac19fc9b.error(String.valueOf(new StringBuilder().append("wlh:").append(valueq).toString()));
                                    itemIn.setMaterialCode(valueq);
                                    list.add(valueq);
                                }
                                if ("wlms".equals(nameq)) {
                                    logger_ac19fc9b.error(String.valueOf(new StringBuilder().append("y-wlms:").append(valueq.trim()).toString()));
                                    String wlms = StringEscapeUtils.unescapeHtml(valueq.trim());
                                    logger_ac19fc9b.error(String.valueOf(new StringBuilder().append("wlms:").append(wlms).toString()));
                                    // String wlms_half = full2HalfWidth(wlms);
                                    // writeLog(new StringBuilder().append("wlms_half:").append(wlms_half).toString());
                                    itemIn.setMaterialName(wlms);
                                }
                            }
                            item[j] = itemIn;
                        }
                        logger_ac19fc9b.error(String.valueOf(new StringBuilder().append(requestid).append("采购组织编个数：").append(set.size()).toString()));
                        if (list.size() > 0) {
                            for (String s : list) {
                                boolean flag = wlhset.add(s);
                                if (!(flag)) {
                                    sb.append(new StringBuilder().append("物料号-").append(s).append("-存在重复；").toString());
                                }
                            }
                            if ((sb != null) && (sb.length() > 0)) {
                                logger_ac19fc9b.error(String.valueOf(new StringBuilder().append(requestid).append("用户申请GY104流程数据不符合要求：").append(sb.toString()).toString()));
                                requestinfo.getRequestManager().setMessageid("error");
                                requestinfo.getRequestManager().setMessagecontent(sb.toString());
                                return  WeaResult.fail(500, new StringBuilder().append(requestid).append("用户申请GY104流程数据不符合要求：").append(sb.toString()).toString(), getResultMapForAction(weaverResultMap, "result",new StringBuilder().append(requestid).append("用户申请GY104流程数据不符合要求：").append(sb.toString()).toString(), requestinfo.getRequestManager()));
                            } else if (set.size() == 1) {
                                paramInfo.setRequestId(new StringBuilder().append("GY104/").append(requestid).toString());
                                paramInfo.setVendorName(gysmc);
                                paramInfo.setVendorCode(gysbm);
                                paramInfo.setHandleType("0");
                                paramInfo.setItems(item);
                                paramInfo.setPurOrgCode((String) set.toArray()[0]);
                                paramInfo.setUnFreezonSDate(jdksrq);
                                paramInfo.setUnFreezonEDate(jdjsrq);
                                logger_ac19fc9b.error(String.valueOf(requestid + " resourceType:" + resourceType));
                                paramInfo.setResourceType(resourceType);
                                param.setInputTab(paramInfo);
//                                OaSrmVenMatExtService service = new OaSrmVenMatExtService();
                                // 
                                String[] str = service.sendsrm(param, requestid);
                                logger_ac19fc9b.error(String.valueOf(new StringBuilder().append(requestid).append("调用货源关系接口返回值：").append(str[0]).append("--").append(str[1]).toString()));
                                if ("-1".equals(str[0])) {
                                    logger_ac19fc9b.error(String.valueOf(new StringBuilder().append(requestid).append("调用SRM货源关系接口出错：").append(str[2]).append("--").append(str[1]).toString()));
                                    requestinfo.getRequestManager().setMessageid("error");
                                    requestinfo.getRequestManager().setMessagecontent(new StringBuilder().append("SRM返回错误信息：").append(str[1]).toString());
                                    return  WeaResult.fail(500, new StringBuilder().append("SRM返回错误信息：").append(str[1]).toString(), getResultMapForAction(weaverResultMap, "result",new StringBuilder().append("SRM返回错误信息：").append(str[1]).toString(), requestinfo.getRequestManager()));
                                }
                            } else {
                                logger_ac19fc9b.error(String.valueOf(new StringBuilder().append(requestid).append("提交申请出错：一次只能申请一个采购组织的").toString()));
                                requestinfo.getRequestManager().setMessageid("error");
                                requestinfo.getRequestManager().setMessagecontent("一次只能申请一个采购组织的");
                                return  WeaResult.fail(500, "一次只能申请一个采购组织的！", getResultMapForAction(weaverResultMap, "result","一次只能申请一个采购组织的！", requestinfo.getRequestManager()));
                            }
                        }
                    } else if (sq  != null && sq.length > 300) {
                        logger_ac19fc9b.error(String.valueOf(new StringBuilder().append(requestid).append("明细表明细行不能超过300行，请分开申请！").toString()));
                        requestinfo.getRequestManager().setMessageid("error");
                        requestinfo.getRequestManager().setMessagecontent("明细表明细行不能超过300行，请分开申请！");
                        return  WeaResult.fail(500, "明细表明细行不能超过300行，请分开申请！", getResultMapForAction(weaverResultMap, "result","明细表明细行不能超过300行，请分开申请！", requestinfo.getRequestManager()));
                    } else if (sq  != null &&  sq.length == 0) {
                        logger_ac19fc9b.error(String.valueOf(new StringBuilder().append(requestid).append("请填写明细项！").toString()));
                        requestinfo.getRequestManager().setMessageid("error");
                        requestinfo.getRequestManager().setMessagecontent("请填写明细项！");
                        return  WeaResult.fail(500, "请填写明细项！", getResultMapForAction(weaverResultMap, "result","请填写明细项！", requestinfo.getRequestManager()));
                    }
                    logger_ac19fc9b.error(String.valueOf(new StringBuilder().append(requestid).append("GY104调用接口校验数据完成").toString()));
                }
            } catch (Exception e) {
                logger_ac19fc9b.error("E--", e);
                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", SUCCESS, requestinfo.getRequestManager()));
        } catch (Exception e) {
            e.printStackTrace();
            logger_ac19fc9b.error("OaSrmVenMatExtCheckAction e: {}", e);
            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 (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                if (b[2] == -1) {
                    b[3] = (byte) (b[3] + 32);
                    b[2] = 0;
                    try {
                        outStr = new StringBuilder().append(outStr).append(new String(b, "unicode")).toString();
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                } else {
                    outStr = new StringBuilder().append(outStr).append(Tstr).toString();
                }
            }
        }
        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;
    }
}
