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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import  com.weaver.seconddev.interfaces.k3.CallK3SupplierServices;
import  com.weaver.seconddev.interfaces.k3.SupplierServiceStub;
import  com.weaver.seconddev.interfaces.swfa.BillFieldUtil;
import java.util.HashMap;
import java.util.Map;
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 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;

/**
 * ERP001财务供应商维护
 */
@org.springframework.stereotype.Service("workflow_action_K3BuildSupplierAction")
public class K3BuildSupplierAction extends BaseBean implements Action, EsbServerlessRpcRemoteInterface {

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

    @Autowired
    private CallK3SupplierServices service;
    private static final Logger logger_c748ab09 = LoggerFactory.getLogger(K3BuildSupplierAction.class);

    @Override
    public WeaResult<Map<String, Object>> execute(Map<String, Object> requestInfoMap) {
        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 user = "oa";
            /**
             * 身份验证*
             */
            String psw = "k3cloud_htgd";
            /**
             * 请求ID*
             */
            String requestID = "";
            /**
             * 接口ID*
             */
            String ITFID = "";
            /**
             * 数据中心*
             */
            String dataCenterID = "";
            /**
             * 操作类型*
             */
            String foperation = "";
            try {
                BillFieldUtil unit = new BillFieldUtil();
                SupplierServiceStub.SupplierReq req = new SupplierServiceStub.SupplierReq();
                SupplierServiceStub.Supplier supplier = new SupplierServiceStub.Supplier();
                SupplierServiceStub.SupContact contact = new SupplierServiceStub.SupContact();
                Property[] properties = requestInfo.getMainTableInfo().getProperty();
                requestID = requestInfo.getRequestid();
                logger_c748ab09.error(String.valueOf("K3BuildSupplierAction--start--" + requestID));
                Map<String, String> mMap = new HashMap<String, String>();
                for (int i = 0; i < properties.length; i++) {
                    String name = properties[i].getName().toUpperCase();
                    String value = Util.null2String(properties[i].getValue());
                    mMap.put(name, value);
                }
                dataCenterID = mMap.get("SJZX");
                if (dataCenterID != null && dataCenterID.length() > 0) {
                    dataCenterID = (Integer.parseInt(dataCenterID) - 3) + "";
                }
                logger_c748ab09.error(String.valueOf("数据中心:" + dataCenterID));
                foperation = mMap.get("SQLX");
                if (foperation != null && foperation.length() > 0) {
                    foperation = (Integer.parseInt(foperation) - 11) + "";
                }
                logger_c748ab09.error(String.valueOf("操作类型:" + foperation));
                String fsupname = mMap.get("GYSMC");
                logger_c748ab09.error(String.valueOf("供应商名称:" + fsupname));
                String fSupNumber = mMap.get("GYSDM");
                logger_c748ab09.error(String.valueOf("供应商代码:" + fSupNumber));
                String fgroup = mMap.get("GYSFZMCGH");
                String fzbm = "";
                String fzmc = "";
                logger_c748ab09.error(String.valueOf("fgroup:" + fgroup));
                if (fgroup != null && fgroup.contains("（")) {
                    fzbm = fgroup.substring(0, fgroup.indexOf("（"));
                    fzmc = fgroup.substring(fgroup.indexOf("（") + 1, fgroup.indexOf("）"));
                }
                logger_c748ab09.error(String.valueOf("供应商分组:" + fzbm));
                logger_c748ab09.error(String.valueOf("供应商分组名称:" + fzmc));
                String gyslb = mMap.get("GYSLBGH");
                String fSupplierClassify = "";
                String fSUPPLYCLASSIFYNAME = "";
                if ("0".equals(gyslb)) {
                    fSupplierClassify = "CG";
                } else if ("1".equals(gyslb)) {
                    fSupplierClassify = "WW";
                } else if ("2".equals(gyslb)) {
                    fSupplierClassify = "FW";
                } else if ("3".equals(gyslb)) {
                    fSupplierClassify = "ZH";
                }
                // gyslbgh
                fSUPPLYCLASSIFYNAME = unit.getName(gyslb);
                logger_c748ab09.error(String.valueOf("供应商类别:" + fSupplierClassify));
                logger_c748ab09.error(String.valueOf("供应商类别名称:" + fSUPPLYCLASSIFYNAME));
                String fSOCIALCRECODE = mMap.get("TYSHXYDMGH");
                logger_c748ab09.error(String.valueOf("统一社会信用代码:" + fSOCIALCRECODE));
                String jsbbgh = mMap.get("JSBBGH");
                String fPayCurrencyId = "CNY";
                if ("0".equals(jsbbgh)) {
                    fPayCurrencyId = "CNY";
                } else if ("1".equals(jsbbgh)) {
                    fPayCurrencyId = "USD";
                } else if ("2".equals(jsbbgh)) {
                    fPayCurrencyId = "EUR";
                } else if ("3".equals(jsbbgh)) {
                    fPayCurrencyId = "JPY";
                } else if ("4".equals(jsbbgh)) {
                    fPayCurrencyId = "AUD";
                } else if ("5".equals(jsbbgh)) {
                    fPayCurrencyId = "GBP";
                } else if ("7".equals(jsbbgh)) {
                    fPayCurrencyId = "TZS";
                }
                logger_c748ab09.error(String.valueOf("结算币别:" + fPayCurrencyId));
                String fPayCondition = mMap.get("FKTJMCGH");
                logger_c748ab09.error(String.valueOf("付款条件:" + fPayCondition));
                String fTaxRateId = mMap.get("MRSLGH");
                logger_c748ab09.error(String.valueOf("默认税率:" + fTaxRateId));
                String F_HTGD_RELATEDTYPE = mMap.get("GLFZX");
                if (F_HTGD_RELATEDTYPE != null && F_HTGD_RELATEDTYPE.length() > 0) {
                    F_HTGD_RELATEDTYPE = (Integer.parseInt(F_HTGD_RELATEDTYPE) + 1) + "";
                }
                logger_c748ab09.error(String.valueOf("关联方属性:" + F_HTGD_RELATEDTYPE));
                // 联系人相关信息
                String fcontact = mMap.get("LXRGH");
                logger_c748ab09.error(String.valueOf("联系人:" + fcontact));
                String fBizAddress = mMap.get("TXDZGH");
                logger_c748ab09.error(String.valueOf("通讯地址:" + fBizAddress));
                String fMobile = mMap.get("SJGH");
                logger_c748ab09.error(String.valueOf("手机:" + fMobile));
                String ftel = mMap.get("DHGH");
                logger_c748ab09.error(String.valueOf("电话:" + ftel));
                String fFax = mMap.get("CZGH");
                logger_c748ab09.error(String.valueOf("传真:" + fFax));
                String femail = mMap.get("DZYXGH");
                logger_c748ab09.error(String.valueOf("电子邮箱:" + femail));
                String fpzz = mMap.get("FPZZBHGH");
                logger_c748ab09.error(String.valueOf("分配组织:" + fpzz));
                logger_c748ab09.error(String.valueOf("fpzz:" + fpzz));
                req.setUser(user);
                req.setPwd(psw);
                req.setDataCenterID(dataCenterID);
                req.setOperateType(foperation);
                supplier.setFSupName(fsupname);
                supplier.setFSupNumber(fSupNumber);
                supplier.setFGroup(fzbm);
                supplier.setFGroupName(fzmc);
                supplier.setFSupplierClassify(fSupplierClassify);
                supplier.setFSOCIALCRECODE(fSOCIALCRECODE);
                supplier.setFPayCurrencyId(fPayCurrencyId);
                supplier.setFPayCondition(fPayCondition);
                supplier.setFTaxRateId(fTaxRateId);
                supplier.setF_HTGD_RELATEDTYPE(F_HTGD_RELATEDTYPE);
                supplier.setFSystemid("OA");
                supplier.setFSRMCode("");
                contact.setFCONTACT(fcontact);
                contact.setFBIZADDRESS(fBizAddress);
                contact.setFMOBILE(fMobile);
                contact.setFTEL(ftel);
                contact.setFFAX(fFax);
                contact.setFEMAIL(femail);
                supplier.setSupContact(contact);
                // 设置分配组织
                String[] zzArr;
                SupplierServiceStub.ArrayOfOrganization orArr = new SupplierServiceStub.ArrayOfOrganization();
                if (fpzz != null && fpzz.length() > 0) {
                    zzArr = fpzz.split(",");
                    for (int i = 0; i < zzArr.length; i++) {
                        SupplierServiceStub.Organization org = new SupplierServiceStub.Organization();
                        org.setFNumber(zzArr[i]);
                        orArr.addOrganization(org);
                    }
                }
                supplier.setListOrgs(orArr);
                logger_c748ab09.error(String.valueOf("明细表开始取值"));
                DetailTable[] detailtable = requestInfo.getDetailTableInfo().getDetailTable();
                DetailTable dtq = detailtable[0];
                Row[] sq = dtq.getRow();
                SupplierServiceStub.ArrayOfSupplierBank bankinfo = new SupplierServiceStub.ArrayOfSupplierBank();
                SupplierServiceStub.SupplierBank[] bankarr = new SupplierServiceStub.SupplierBank[sq.length];
                for (int j = 0; j < sq.length; j++) {
                    // 指定行
                    Row rq = sq[j];
                    // 每行数据再按列存储
                    Cell[] cq = rq.getCell();
                    // JSONObject item = new JSONObject();
                    SupplierServiceStub.SupplierBank item = new SupplierServiceStub.SupplierBank();
                    Map<String, String> mDetailMap = new HashMap<String, String>();
                    for (int k = 0; k < cq.length; k++) {
                        // 指定列
                        Cell cq1 = cq[k];
                        // 明细字段名称
                        String nameq = cq1.getName().toUpperCase();
                        String valueq = Util.null2String(cq1.getValue());
                        mDetailMap.put(nameq, valueq);
                    }
                    // 账户名称
                    item.setFBankHolder(mDetailMap.get("YXZHMCGH"));
                    // 开户银行（分支机构）
                    item.setFOPENBANKNAME(mDetailMap.get("KHYXFZJGGH"));
                    // 银行账号
                    item.setFBankCode(mDetailMap.get("YXZHGH"));
                    // 银联号
                    item.setFCNAPS(mDetailMap.get("LXHGH"));
                    bankarr[j] = item;
                }
                bankinfo.setSupplierBank(bankarr);
                supplier.setBankList(bankinfo);
                logger_c748ab09.error(String.valueOf("获取明细表数据结束"));
                req.setSupplier(supplier);
//                CallK3SupplierServices service = new CallK3SupplierServices();
                SupplierServiceStub.SupplierRes response = service.buildSupplier(req);
                logger_c748ab09.error("调用K3Cloud系统供应商创建接口返回值：" + response);
                // 1-成功 0-失败
                String code = response.getCode();
                String result = response.getResult();
                String message = response.getMessage();
                logger_c748ab09.error(String.valueOf("调用K3Cloud系统供应商创建接口返回值：" + code + "===" + message));
                if (!"1".equals(code)) {
                    requestInfo.getRequestManager().setMessageid("ERROR");
                    requestInfo.getRequestManager().setMessagecontent("K3Cloud系统返回错误信息：" + message);
                    return  WeaResult.fail(500, "K3Cloud系统返回错误信息：" + message, getResultMapForAction(weaverResultMap, "result","K3Cloud系统返回错误信息：" + message, requestInfo.getRequestManager()));
                }
                logger_c748ab09.error(String.valueOf("K3BuildSupplierAction--end--" + requestID));
            } catch (Exception e) {
                logger_c748ab09.error(String.valueOf("K3Cloud系统接口失败，请联系K3Cloud系统管理员！"));
                requestInfo.getRequestManager().setMessageid("ERROR");
                requestInfo.getRequestManager().setMessagecontent("K3Cloud系统返回错误信息接口失败，请联系K3Cloud系统管理员！");
                return  WeaResult.fail(500, "K3BuildSupplierAction 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_c748ab09.error("K3BuildSupplierAction e: {}", e.getMessage());
            return  WeaResult.fail(500, "K3BuildSupplierAction e: {}"+ e, getResultMapForAction(weaverResultMap, "result",e.getMessage(), requestInfo.getRequestManager()));
        }
    }

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