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

import java.text.SimpleDateFormat;
import java.util.*;
import com.weaver.seconddev.interfaces.htjt.util.TransUtil;
import com.weaver.seconddev.interfaces.prop.ConfigProp;
import org.apache.commons.lang.StringEscapeUtils;
import  com.weaver.seconddev.interfaces.srmoa.CallSrmServices;
import  com.weaver.seconddev.interfaces.srmoa.OaSrmVenMatExtService;
import  com.weaver.seconddev.interfaces.srmoa.OaSrmVendorPropmtionServiceServiceStub;
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  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 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.company.DepartmentComInfo;
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;

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

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

    @Autowired
    private  CallSrmServices srm;
    private static final Logger logger_41a64316 = LoggerFactory.getLogger(OaSrmVendorSyncAction.class);

    @Override
    public WeaResult<Map<String, Object>> execute(Map<String, Object> requestInfoMap) {
        logger_41a64316.error("OaSrmVendorSyncAction 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 workflowid = requestinfo.getWorkflowid();
            TransUtil tu = new TransUtil();
//            String tablename = tu.getTableName(workflowid);
            String tablename = requestinfo.getRequestManager().getBillTableName();
            RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
            logger_41a64316.error(String.valueOf("OaSrmVendorSyncAction--start:" + requestid));
            try {
                String state = "E";
                String message = "";
                Map<String, String> map = new HashMap<String, String>();
                ResourceComInfo resourcecominfo = I18nContextUtil.getBean(ResourceComInfo.class);
                DepartmentComInfo departmentComInfo = I18nContextUtil.getBean(DepartmentComInfo.class);
                Property[] aproperty = requestinfo.getMainTableInfo().getProperty();
                for (int i = 0; i < aproperty.length; i++) {
                    String name = aproperty[i].getName().toUpperCase();
                    String value = Util.null2String(aproperty[i].getValue());
                    map.put(name, value);
                }
                String sqdwid = map.get("SQDW");//申请单位
                //申请单位 江苏华脉光电科技有限公司 不触发接口
                String gy103gsid = configProp.getGy103gsid();
                if(!"".equals(sqdwid)&&!"".equals(gy103gsid)&&(","+gy103gsid+",").indexOf(","+sqdwid+",")>=0){
                    logger_41a64316.error(requestid+"sqdw:"+sqdwid+" gy103gsid:"+gy103gsid);
                    return WeaResult.success(getResultMapForAction(weaverResultMap, "result", Action.SUCCESS, requestinfo.getRequestManager()));
                }
                // 是否推送erp
                String sftserp = map.get("SFTSERP");
                // 流程编号
                String lcbh = getFormno(requestid);
                if (!"".equals(map.get("LCBH")) && map.get("LCBH") != null) {
                    lcbh = map.get("LCBH");
                }
                // 公司编码
                String sqdwbm = map.get("GSBM");
                // 公司名称
                String sqdw = map.get("GSMC");
                // 供应商编码
                String gysbm = map.get("GYSBM");
                // 供应商名称
                String gysmc = map.get("GYSMC");
                // 申请人
                String sqrxm = resourcecominfo.getResourcename(map.get("SQR"));
                // 申请人工号
                String gh = map.get("GH");
                // 申请部门
                String sqbm = departmentComInfo.getDepartmentName(map.get("SQBM"));
                // 审核人
                String shr = resourcecominfo.getResourcename(String.valueOf(userIdTemp));
                // 供应商类型
                String gyslx = map.get("GYSLX");
                // 1 原材料货源， 2 OEM货源
                String resourceType = "1";
                if ("4".equals(gyslx)) {
                    // oem
                    resourceType = "2";
                }
                // String gyslxmc = BillFieldUtil.getselectName(gyslx,"59387"); //测试53251    正式59387
                // 测试53251    正式59387
                String gyslxmc = tu.getSelectName(tablename, "gyslx", gyslx);
                logger_41a64316.error(String.valueOf(requestid + " lcbh:" + lcbh + " sqdwbm:" + sqdwbm + " sqdw:" + sqdw + " gysbm:" + gysbm + " gysmc:" + gysmc + " sqrxm:" + sqrxm + " gh:" + gh + " sqbm:" + sqbm + " shr:" + shr + " gyslx:" + gyslx + " resourceType:" + resourceType + " gyslxmc:" + gyslxmc));
                // String val = BillFieldUtil.getselectName(map.get("XSXXGYS"), "59388");//53252测试 59388正式
                // 53252测试 59388正式
                String val = tu.getSelectName(tablename, "xsxxgys", map.get("XSXXGYS"));
                logger_41a64316.error(String.valueOf("OaSrmVendorSyncAction--线上/线下供应商:" + val));
                if (val.length() > 1) {
                    val = val.substring(0, 1);
                }
                if (val.equals("0")) {
                    Date now = new Date();
                    SimpleDateFormat datetype = new SimpleDateFormat("yyyy-MM-dd");
                    SimpleDateFormat timetype = new SimpleDateFormat("HH:mm:ss");
                    String shrq = datetype.format(now);
                    String shsj = timetype.format(now);
                    String shyj = requestinfo.getRequestManager().getRemark();
                    OaSrmVendorPropmtionServiceServiceStub.OaInputVendor oainputvendor = new OaSrmVendorPropmtionServiceServiceStub.OaInputVendor();
                    oainputvendor.setRequestId(getFormno(requestid));
                    oainputvendor.setLcbh(lcbh);
                    oainputvendor.setSqdwbm(sqdwbm);
                    oainputvendor.setSqdw(sqdw);
                    oainputvendor.setSqbm(sqbm);
                    oainputvendor.setGysbm(gysbm);
                    oainputvendor.setGysmc(gysmc);
                    oainputvendor.setGyslx(gyslxmc);
                    oainputvendor.setSqrxm(sqrxm);
                    oainputvendor.setGh(gh);
                    oainputvendor.setGycpmc("");
                    oainputvendor.setShr(shr);
                    oainputvendor.setShyj(shyj);
                    oainputvendor.setShrq(shrq);
                    oainputvendor.setShsj(shsj);
                    oainputvendor.setShzt("2");
                    if ("".equals(sftserp)) {
                        oainputvendor.setSyncErp(0);
                    } else {
                        oainputvendor.setSyncErp(Integer.valueOf(sftserp));
                    }
                    int dtcount = 0;
                    String sql = "select b.* from e10_core_business.dbo." + tablename + " a,e10_core_business.dbo." + tablename + "_dt3 b where a.form_data_id=b.form_data_id and a.id=" + requestid;
                    logger_41a64316.error(String.valueOf("sql-->" + sql));
                    String poolname = CONN_TYPE.workflow.getType();
                    // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                    boolean b = rs.executeSql(sql, poolname);
                    logger_41a64316.error(String.valueOf("b-->" + b));
                    dtcount = rs.getCounts();
                    if (dtcount > 0) {
                        int index = 0;
                        OaSrmVendorPropmtionServiceServiceStub.OaInItem[] items = new OaSrmVendorPropmtionServiceServiceStub.OaInItem[dtcount];
                        while (rs.next()) {
                            OaSrmVendorPropmtionServiceServiceStub.OaInItem item = new OaSrmVendorPropmtionServiceServiceStub.OaInItem();
                            item.setCompanyCode(Util.null2String(rs.getString("gsbm")));
                            item.setCompanyName(Util.null2String(rs.getString("gsmc")));
                            item.setPurOrgCode(Util.null2String(rs.getString("cgzzbm")));
                            item.setPurOrgName(Util.null2String(rs.getString("cgzzmc")));
                            if ("1".equals(sftserp)) {
                                String tsxt = Util.null2String(rs.getString("tsxt"));
                                String gysjc = Util.null2String(rs.getString("gysjc"));
                                String k3tykm = Util.null2String(rs.getString("k3tykm"));
                                String saptykm = Util.null2String(rs.getString("saptykm"));
                                String fktj = Util.null2String(rs.getString("fktj"));
                                String fkfs = Util.null2String(rs.getString("fkfs"));
                                String k3yslsm = Util.null2String(rs.getString("k3yslsm"));
                                logger_41a64316.error(String.valueOf(requestid + " tsxt:" + tsxt + " gysjc:" + gysjc + " k3tykm:" + k3tykm + " saptykm:" + saptykm + " fktj:" + fktj + " fkfs:" + fkfs + " k3yslsm:" + k3yslsm));
                                // 供应商简称
                                item.setNameSort(gysjc);
                                // 付款方式
                                item.setDictItemId2(fkfs);
                                // 付款方式
                                ;
                                // 付款条件
                                item.setDictItemId3(fktj);
                                // 付款条件
                                ;
                                if ("0".equals(tsxt)) {
                                    // k3
                                    // 科目
                                    item.setDictItemId(k3tykm);
                                    // 科目
                                    ;
                                    // 税率
                                    item.setTaxRateId(k3yslsm);
                                    // 税率
                                    ;
                                } else if ("1".equals(tsxt)) {
                                    // sap
                                    // 科目
                                    item.setDictItemId(saptykm);
                                    // 科目
                                    ;
                                }
                            }
                            items[index] = item;
                            index++;
                        }
                        oainputvendor.setItems(items);
                    }
//                    CallSrmServices srm = new CallSrmServices();
                    srm.setOainputvendor(oainputvendor);
                    String[] rtInfo = srm.call();
                    logger_41a64316.error(String.valueOf("调用接口完成RequestId--" + rtInfo[0] + "--Istat--" + rtInfo[1] + "--Srmsage--" + rtInfo[2]));
                    state = rtInfo[1];
                    message = rtInfo[2].replace("'", "’");
                } else {
                    state = "S";
                    message = "线下供应商";
                    logger_41a64316.error(String.valueOf(requestid + "申请转正供应商为线下供应商"));
                }
                if ("S".equals(state)) {
                    Set<String> set = new HashSet<String>();
                    DetailTable[] detailtable = requestinfo.getDetailTableInfo().getDetailTable();
                    // 指定明细表
                    DetailTable dtq = null;
                    if(dtq != null){
                        dtq =  detailtable[1];
                    }
                    // 当前明细表的所有数据,按行存储
                    Row[] sq = null;
                    if(dtq != null){sq = dtq.getRow();}
                    int dtcount = 0;
                    String sql = "select distinct wlh from e10_core_business.dbo." + tablename + " a,e10_core_business.dbo." + tablename + "_dt2 b where a.form_data_id=b.form_data_id and a.id =" + requestid;
                    logger_41a64316.error("sql-->" + sql);
                    String poolname_wk = CONN_TYPE.workflow.getType();
                    // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                    boolean b = rs.executeSql(sql, poolname_wk);
                    logger_41a64316.error(String.valueOf("b-->" + b));
                    dtcount = rs.getCounts();
                    logger_41a64316.error(String.valueOf(requestid + " dt2count:" + dtcount));
                    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[dtcount];
                        String wlhs = "";
                        String flagwl = "";
                        int itemnum = 0;
                        for (int j = 0; j < sq.length; j++) {
                            // 指定行
                            Row rq = sq[j];
                            Cell[] cq = rq.getCell();
                            VenMatExtResultItemIn itemIn = new VenMatExtResultItemIn();
                            String isexists = "0";
                            logger_41a64316.error(String.valueOf(requestid + " wlhs:" + wlhs));
                            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);
                                }
                                if ("wlh".equals(nameq)) {
                                    if (("," + wlhs + ",").indexOf("," + valueq + ",") >= 0) {
                                        logger_41a64316.error(String.valueOf(requestid + " 物料号重复:" + valueq));
                                        isexists = "1";
                                        continue;
                                    }
                                    itemIn.setMaterialCode(valueq);
                                    wlhs = wlhs + flagwl + valueq;
                                    flagwl = ",";
                                }
                                if ("wlms".equals(nameq)) {
                                    // String wlms = StringEscapeUtils.unescapeHtml(valueq.trim());
                                    // itemIn.setMaterialName(wlms);
                                    String wlms = StringEscapeUtils.unescapeHtml(valueq.trim());
                                    logger_41a64316.error(String.valueOf("wlms:" + wlms));
                                    // String wlms_half = full2HalfWidth(wlms);
                                    // writeLog("wlms_half:"+wlms_half);
                                    itemIn.setMaterialName(wlms);
                                }
                                if ("xjxzb".equals(nameq)) {
                                    itemIn.setWeight(valueq);
                                }
                                if ("clfl".equals(nameq)) {
                                    // String clfl = BillFieldUtil.getselectName(valueq,"59436");//测试53290   正式59436
                                    // 测试53290   正式59436
                                    String clfl = tu.getSelectName(tablename, "clfl", valueq);
                                    itemIn.setMatLevel(clfl);
                                }
                            }
                            if ("1".equals(isexists)) {
                                logger_41a64316.error(String.valueOf(requestid + " 物料号重复:跳过"));
                                continue;
                            }
                            item[itemnum] = itemIn;
                            itemnum++;
                        }
                        String purOrgCodes = "";
                        String flag = "";
                        Iterator it = set.iterator();
                        while (it.hasNext()) {
                            purOrgCodes = purOrgCodes + flag + it.next();
                            flag = ";";
                        }
                        logger_41a64316.error(String.valueOf(requestid + " purOrgCodes：" + purOrgCodes));
                        paramInfo.setApplyUser(gh);
                        paramInfo.setCheckUser(shr);
                        paramInfo.setCompanyCode(sqdwbm);
                        paramInfo.setCompanyName(sqdw);
                        paramInfo.setVendorCode(gysbm);
                        paramInfo.setVendorName(gysmc);
                        paramInfo.setHandleType("6");
                        paramInfo.setRequestId("GY103/" + requestid);
                        paramInfo.setStartDate(map.get("SQRQ"));
                        paramInfo.setEndDate("2099-12-31");
                        paramInfo.setPurOrgCode(purOrgCodes);
                        paramInfo.setItems(item);
                        paramInfo.setFreezeReason("");
                        logger_41a64316.error(String.valueOf(requestid + " resourceType:" + resourceType));
                        paramInfo.setResourceType(resourceType);
                        param.setInputTab(paramInfo);
//                        OaSrmVenMatExtService service = new OaSrmVenMatExtService();
                        //

                        logger_41a64316.error("param--" + param + ",requestid--" + requestid);
                        String[] str = service.sendsrm(param, requestid);
                        if ("1".equals(str[0])) {
                            state = "S";
                        } else {
                            state = "E";
                        }
                        message = str[1];
                        logger_41a64316.error(String.valueOf(requestid + "调用货源关系接口同步数据返回值" + message));
                    }
                }
                if (!"S".equals(state)) {
                    requestinfo.getRequestManager().setMessagecontent(message);
                    return  WeaResult.fail(500, "OaSrmVendorSyncAction message"+ message, getResultMapForAction(weaverResultMap, "result",message, requestinfo.getRequestManager()));
                }
            } catch (Exception e) {
                logger_41a64316.error("Exception--",e);
                logger_41a64316.error(String.valueOf(requestid + "-OaSrmVendorSyncAction--error:" + e.toString()));
                requestinfo.getRequestManager().setMessagecontent("调用SRM接口同步数据异常，请联系管理员！");
                return  WeaResult.fail(500, "OaSrmVendorSyncAction err"+ e, getResultMapForAction(weaverResultMap, "result",e.getMessage(), requestinfo.getRequestManager()));
            }
            logger_41a64316.error(String.valueOf("OaSrmVendorSyncAction--end:" + requestid));
            return WeaResult.success(getResultMapForAction(weaverResultMap, "result", Action.SUCCESS, requestinfo.getRequestManager()));
        } catch (Exception e) {
            e.printStackTrace();
            logger_41a64316.error("OaSrmVendorSyncAction e: {}", e.getMessage());
            return  WeaResult.fail(500, "OaSrmVendorSyncAction 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;
    }

    public String getFormno(String requestid){
        String formno = "";
        if(requestid.length()>8){
            formno = "1"+requestid.substring(requestid.length()-8);
        }else{
            formno = requestid;
        }
        return formno;
    }

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