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

import  com.weaver.seconddev.interfaces.k3.CallK3CustomerService;
import  com.weaver.seconddev.interfaces.k3.CustomerServiceStub;
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;

/**
 * ERP002客户
 */
@org.springframework.stereotype.Service("workflow_action_K3BuildCustomerAction")
public class K3BuildCustomerAction extends BaseBean implements Action, EsbServerlessRpcRemoteInterface {

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

    @Autowired
    private CallK3CustomerService service;
    private static final Logger logger_4201db9b = LoggerFactory.getLogger(K3BuildCustomerAction.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();
                CustomerServiceStub.CustomerReq req = new CustomerServiceStub.CustomerReq();
                CustomerServiceStub.Customer customer = new CustomerServiceStub.Customer();
                CustomerServiceStub.CustContact contact = new CustomerServiceStub.CustContact();
                Property[] properties = requestInfo.getMainTableInfo().getProperty();
                requestID = requestInfo.getRequestid();
                logger_4201db9b.error(String.valueOf("K3BuildCustomerAction--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_4201db9b.error(String.valueOf(requestID + " 数据中心:" + dataCenterID));
                foperation = mMap.get("SQLX");
                if (foperation != null && foperation.length() > 0) {
                    foperation = (Integer.parseInt(foperation) - 11) + "";
                }
                logger_4201db9b.error(String.valueOf(requestID + " 操作类型:" + foperation));
                String fsupname = mMap.get("KHMC");
                logger_4201db9b.error(String.valueOf(requestID + " 客户名称:" + fsupname));
                String fSupNumber = mMap.get("KHDM");
                logger_4201db9b.error(String.valueOf(requestID + " 客户代码:" + fSupNumber));
                String fgroup = mMap.get("KHFZMCGH");
                String fzbm = "";
                String fzmc = "";
                logger_4201db9b.error(String.valueOf(requestID + " fgroup:" + fgroup));
                if (fgroup != null && fgroup.contains("（")) {
                    fzbm = fgroup.substring(0, fgroup.indexOf("（"));
                    fzmc = fgroup.substring(fgroup.indexOf("（") + 1, fgroup.indexOf("）"));
                }
                logger_4201db9b.error(String.valueOf(requestID + " 客户分组:" + fzbm));
                logger_4201db9b.error(String.valueOf(requestID + " 客户分组名称:" + fzmc));
                String gyslb = mMap.get("KHLBGH");
                String fSupplierClassify = "";
                String fSUPPLYCLASSIFYNAME = "";
                if ("0".equals(gyslb)) {
                    fSupplierClassify = "KHLB001_SYS";
                } else if ("1".equals(gyslb)) {
                    fSupplierClassify = "KHLB002_SYS";
                } else if ("2".equals(gyslb)) {
                    fSupplierClassify = "KHLB003_SYS";
                }
                // fSUPPLYCLASSIFYNAME = unit.getName(gyslb);;//khlbgh
                logger_4201db9b.error(String.valueOf(requestID + " 客户类别:" + fSupplierClassify));
                // writeLog("客户类别名称:" + fSUPPLYCLASSIFYNAME);
                String fSOCIALCRECODE = mMap.get("TYSHXYDMGH");
                logger_4201db9b.error(String.valueOf(requestID + " 统一社会信用代码:" + 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_4201db9b.error(String.valueOf(requestID + " 结算币别:" + fPayCurrencyId));
                String fPayCondition = mMap.get("FKTJMCGH");
                logger_4201db9b.error(String.valueOf(requestID + " 付款条件:" + fPayCondition));
                String fTaxRateId = mMap.get("MRSLGH");
                logger_4201db9b.error(String.valueOf(requestID + " 默认税率:" + 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_4201db9b.error(String.valueOf(requestID + " 关联方属性:" + F_HTGD_RELATEDTYPE));
                // 联系人相关信息
                String fcontact = mMap.get("LXRGH");
                logger_4201db9b.error(String.valueOf(requestID + " 联系人:" + fcontact));
                String fBizAddress = mMap.get("XXTXDZGH");
                logger_4201db9b.error(String.valueOf(requestID + " 通讯地址:" + fBizAddress));
                String fMobile = mMap.get("SJGH");
                logger_4201db9b.error(String.valueOf(requestID + " 手机:" + fMobile));
                String ftel = mMap.get("DHGH");
                logger_4201db9b.error(String.valueOf(requestID + " 电话:" + ftel));
                String fFax = mMap.get("CZGH");
                logger_4201db9b.error(String.valueOf(requestID + " 传真:" + fFax));
                String femail = mMap.get("DZYXGH");
                logger_4201db9b.error(String.valueOf(requestID + " 电子邮箱:" + femail));
                String fpzz = mMap.get("FPZZBHGH");
                logger_4201db9b.error(String.valueOf(requestID + " 分配组织:" + fpzz));
                req.setUser(user);
                req.setPwd(psw);
                req.setDataCenterID(dataCenterID);
                req.setOperateType(foperation);
                customer.setFCustName(fsupname);
                customer.setFCustNumber(fSupNumber);
                customer.setFGroup(fzbm);
                customer.setFGroupName(fzmc);
                customer.setFCustClassify(fSupplierClassify);
                customer.setFTAXREGISTERCODE(fSOCIALCRECODE);
                customer.setFTRADINGCURRID(fPayCurrencyId);
                customer.setFRECCONDITIONID(fPayCondition);
                customer.setF_HTGD_RELATEDTYPE(F_HTGD_RELATEDTYPE);
                customer.setFTaxRate(fTaxRateId);
                contact.setFCONTACT(fcontact);
                contact.setFBIZADDRESS(fBizAddress);
                contact.setFMOBILE(fMobile);
                contact.setFTEL(ftel);
                contact.setFFAX(fFax);
                contact.setFEMAIL(femail);
                customer.setCustContact(contact);
                // 设置分配组织
                String[] zzArr;
                CustomerServiceStub.ArrayOfOrganization orArr = new CustomerServiceStub.ArrayOfOrganization();
                if (fpzz != null && fpzz.length() > 0) {
                    zzArr = fpzz.split(",");
                    for (int i = 0; i < zzArr.length; i++) {
                        CustomerServiceStub.Organization org = new CustomerServiceStub.Organization();
                        org.setFNumber(zzArr[i]);
                        orArr.addOrganization(org);
                    }
                }
                customer.setListOrgs(orArr);
                logger_4201db9b.error(String.valueOf(requestID + " 明细表开始取值"));
                DetailTable[] detailtable = requestInfo.getDetailTableInfo().getDetailTable();
                DetailTable dtq;
                if(detailtable.length >0){
                    dtq = detailtable[0];
                    Row[] sq = dtq.getRow();
                    CustomerServiceStub.ArrayOfCustBank bankinfo = new CustomerServiceStub.ArrayOfCustBank();
                    CustomerServiceStub.CustBank[] bankarr = new CustomerServiceStub.CustBank[sq.length];
                    for (int j = 0; j < sq.length; j++) {
                        // 指定行
                        Row rq = sq[j];
                        // 每行数据再按列存储
                        Cell[] cq = rq.getCell();
                        CustomerServiceStub.CustBank item = new CustomerServiceStub.CustBank();
                        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.setCustBank(bankarr);
                    customer.setBankList(bankinfo);
                    logger_4201db9b.error(String.valueOf(requestID + " 获取明细表数据结束"));
                }
                req.setCustomer(customer);
//                CallK3CustomerService service = new CallK3CustomerService();
                CustomerServiceStub.CustomerRes response = service.buildCustomer(req);
                logger_4201db9b.error(requestID + " 调用K3Cloud系统客户创建接口返回值：" + response);
                // 1-成功 0-失败
                String code = response.getCode();
                String result = response.getResult();
                String message = response.getMessage();
                logger_4201db9b.error(String.valueOf(requestID + " 调用K3Cloud系统客户创建接口返回值：code:" + code + " result:" + result + " message:" + 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_4201db9b.error(String.valueOf("K3BuildCustomerAction--end--" + requestID));
            } catch (Exception e) {
                logger_4201db9b.error(String.valueOf(requestID + " K3Cloud系统接口失败，请联系K3Cloud系统管理员！" + e.getMessage()));
                logger_4201db9b.error(String.valueOf(e));
                requestInfo.getRequestManager().setMessageid("ERROR");
                requestInfo.getRequestManager().setMessagecontent("K3Cloud系统返回错误信息接口失败，请联系K3Cloud系统管理员！");
                return  WeaResult.fail(500, "K3BuildCustomerAction 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_4201db9b.error("K3BuildCustomerAction e: {}", e.getMessage());
            return  WeaResult.fail(500, "K3BuildCustomerAction 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;
    }
}
