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

import com.weaver.seconddev.interfaces.htjt.util.TransUtil;
import com.weaver.seconddev.interfaces.prop.ConfigProp;
import  com.weaver.seconddev.interfaces.srmoa.CallVdDlvApplyServices;
import  com.weaver.seconddev.interfaces.srmoa.VdDlvApplyHandlerServiceServiceStub;
import  com.weaver.seconddev.interfaces.swfa.BillFieldUtil;
import java.util.HashMap;
import java.util.Map;
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.file.Prop;
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 com.weaver.verupgrade.common.DateUtil;
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.Property;
import com.weaver.verupgrade.interfaces.workflow.action.Action;

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

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

    @Autowired
    private ConfigProp configProp;

    @Autowired
    private CallVdDlvApplyServices service;
    private static final Logger logger_9af84826 = LoggerFactory.getLogger(OaSrmVendorAdmitAction.class);

    @Override
    public WeaResult<Map<String, Object>> execute(Map<String, Object> requestInfoMap) {
        logger_9af84826.error("OaSrmVendorAdmitAction 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();
            RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
            TransUtil tu = new TransUtil();
//            String tablename = tu.getTableName(workflowid);
            String tablename = requestinfo.getRequestManager().getBillTableName();
            logger_9af84826.error(String.valueOf("OaSrmVendorAdmitAction--start--" + requestid));
            try {
                String state = "E";
                String message = "";
                Map<String, String> map = new HashMap<String, String>();
                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);
                }
                logger_9af84826.error("map--" + map);
                String sqdwid = map.get("SQDW");//申请单位
                //申请单位 江苏华脉光电科技有限公司 不触发接口
                String gy103gsid = configProp.getGy103gsid();
                if(!"".equals(sqdwid)&&!"".equals(gy103gsid)&&(","+gy103gsid+",").indexOf(","+sqdwid+",")>=0){
                    logger_9af84826.error(requestid+"sqdw:"+sqdwid+" gy103gsid:"+gy103gsid);
                    return WeaResult.success(getResultMapForAction(weaverResultMap, "result", Action.SUCCESS, requestinfo.getRequestManager()));
                }
                ResourceComInfo resourcecominfo = I18nContextUtil.getBean(ResourceComInfo.class);
                DepartmentComInfo departmentComInfo = I18nContextUtil.getBean(DepartmentComInfo.class);
                // 53252测试 59388正式
                String val = tu.getSelectName(tablename, "xsxxgys", map.get("XSXXGYS"));

                // String val = BillFieldUtil.getselectName(map.get("XSXXGYS"), "59388");//53252测试 59388正式
                logger_9af84826.error(String.valueOf("OaSrmVendorAdmitAction--线上/线下供应商:" + val));
                if (val.length() > 1) {
                    val = val.substring(0, 1);
                }
                String 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"));
                // TODO custom 已处理 审核人
                String shr = resourcecominfo.getResourcename(String.valueOf(userIdTemp));
                // 供应商类型
                String gyslx = map.get("GYSLX");
                // 测试53251    正式59387
                String gyslxmc = tu.getSelectName(tablename, "gyslx", gyslx);
                // String gyslxmc = BillFieldUtil.getselectName(gyslx,"59387"); //测试53251    正式59387
                if (val.equals("0")) {
                    // 引入后预计达到的目的
                    String yrhyqdddxg = String.valueOf(map.get("JTQKSM"));
                    // 审核时间
                    String date = DateUtil.getFullDate();
                    // 申请原因
                    String yryy = String.valueOf(map.get("YRYY"));
                    // String yryyms = BillFieldUtil.getselectName(yryy,"59421");//测试53462  正式59421
                    // 测试53462  正式59421
                    String yryyms = tu.getSelectName(tablename, "yryy", yryy);
                    // 预计年度将本金额
                    String yjndcbjsje = "";
                    if ("1".equals(yryy) || "2".equals(yryy)) {
                        // 测试53282 正式59417
                        yjndcbjsje = Util.null2String(map.get("QTJDJE"));
                    }
                    // 现场审核 	0：不需要；1：需要；
                    int xcsh = 0;
                    if ("0".equals(String.valueOf(map.get("XCSH")))) {
                        xcsh = 1;
                    }
                    if ("1".equals(String.valueOf(map.get("XCSH")))) {
                        xcsh = 0;
                    }
                    // 现有合格供应商
                    String xyhggys = String.valueOf(map.get("XYHGGYSMC"));
                    VdDlvApplyHandlerServiceServiceStub.DlvApplyIn dlvapplyin = new VdDlvApplyHandlerServiceServiceStub.DlvApplyIn();
                    dlvapplyin.setRequestId(Integer.parseInt(getFormno(requestid)));
                    dlvapplyin.setApplyNo(lcbh);
                    dlvapplyin.setCompanyCode(sqdwbm);
                    dlvapplyin.setCompanyName(sqdw);
                    dlvapplyin.setVendorCode(gysbm);
                    dlvapplyin.setVendorName(gysmc);
                    dlvapplyin.setApplyer(sqrxm);
                    dlvapplyin.setEmpNo(gh);
                    dlvapplyin.setCategoryName("");
                    dlvapplyin.setCheckUserName(shr);
                    dlvapplyin.setCheckTime(date);
                    dlvapplyin.setApplyReason(yryyms);
                    dlvapplyin.setExpectedMoney(yjndcbjsje);
                    dlvapplyin.setExpectedPurpose(yrhyqdddxg);
                    // 提交标记(0：校验； 1：提交)
                    dlvapplyin.setSubmitFlag(1);
                    dlvapplyin.setDept(sqbm);
                    dlvapplyin.setVendors(xyhggys);
                    dlvapplyin.setInspectFlag(xcsh);
                    dlvapplyin.setVendorType(gyslxmc);
                    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_9af84826.error("OaSrmVendorAdmitAction sql-->" + sql);
                    String poolname = CONN_TYPE.workflow.getType();
                    // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                    boolean b = rs.executeSql(sql, poolname);
                    logger_9af84826.error("OaSrmVendorAdmitAction b-->" + b);
                    dtcount = rs.getCounts();
                    if (dtcount > 0) {
                        int index = 0;
                        VdDlvApplyHandlerServiceServiceStub.DlvApplyInItem[] items = new VdDlvApplyHandlerServiceServiceStub.DlvApplyInItem[dtcount];
                        while (rs.next()) {
                            VdDlvApplyHandlerServiceServiceStub.DlvApplyInItem item = new VdDlvApplyHandlerServiceServiceStub.DlvApplyInItem();
                            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")));
                            items[index] = item;
                            index++;
                        }
                        dlvapplyin.setItems(items);
                    }
//                    CallVdDlvApplyServices service = new CallVdDlvApplyServices();
                    service.setOainputvendor(dlvapplyin);
                    String[] result = service.call();
                    logger_9af84826.error(String.valueOf(requestid + "供应商准入接口返回值" + result[0] + "--" + result[1]));
                    state = result[0];
                    message = result[1];
                } else {
                    state = "S";
                    message = "线下供应商";
                    logger_9af84826.error(String.valueOf(requestid + "申请准入供应商为线下供应商"));
                }
                if (!"S".equals(state)) {
                    requestinfo.getRequestManager().setMessagecontent(message);
                    return  WeaResult.fail(500, "OaSrmVendorAdmitAction message"+ message, getResultMapForAction(weaverResultMap, "result",message, requestinfo.getRequestManager()));
                }
            } catch (Exception e) {
                logger_9af84826.error(String.valueOf(e));
                logger_9af84826.error(String.valueOf(requestid + "--OaSrmVendorAdmitAction--error--" + e.toString()));
                requestinfo.getRequestManager().setMessagecontent("调用SRM接口校验数据异常，请联系管理员！");
                return  WeaResult.fail(500, "OaSrmVendorAdmitAction err"+ e, getResultMapForAction(weaverResultMap, "result",e.getMessage(), requestinfo.getRequestManager()));
            }
            logger_9af84826.error(String.valueOf("OaSrmVendorAdmitAction--end--" + requestid));
            return WeaResult.success(getResultMapForAction(weaverResultMap, "result", Action.SUCCESS, requestinfo.getRequestManager()));
        } catch (Exception e) {
            e.printStackTrace();
            logger_9af84826.error("OaSrmVendorAdmitAction e: {}", e.getMessage());
            return  WeaResult.fail(500, "OaSrmVendorAdmitAction e: {}"+ e, getResultMapForAction(weaverResultMap, "result",e.getMessage(), requestinfo.getRequestManager()));
        }
    }

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

//    public static void main(String[] args) {
//        String cs = "1104617940341235715";
//        System.out.println(Integer.parseInt(getFormno(cs)));
//    }
}
