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

import com.weaver.seconddev.interfaces.htjt.util.TransUtil;
import  com.weaver.seconddev.interfaces.k3.*;
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.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.conn.RecordSet;
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;

/**
 * ERP006-
 */
@org.springframework.stereotype.Service("workflow_action_K3PORequestAction")
public class K3PORequestAction extends BaseBean implements Action, EsbServerlessRpcRemoteInterface {

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

    @Autowired
    private CallPORequestService service ;
    private static final Logger logger_7396c45f = LoggerFactory.getLogger(K3PORequestAction.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";
            String requestID = "";
            String ITFID = "";
            /**
             * 数据中心*
             */
            String dataCenterID = "";
            String foperation = "";
            try {
                BillFieldUtil unit = new BillFieldUtil();
                // PORequestServiceStub. req = new PORequestServiceStub.PORequestRes();
                // PORequestServiceStub.BuildPORequest supplier = new PORequestServiceStub.BuildPORequest();
                // PORequestServiceStub.PO contact = new SupplierServiceStub.SupContact();
                // PORequestServiceStub.BuildPORequest req = new PORequestServiceStub.BuildPORequest();
                PORequestServiceStub.PORequestReq purReq = new PORequestServiceStub.PORequestReq();
                // PORequestServiceStub.PORequestDt dt = new PORequestServiceStub.PORequestDt();
                Property[] properties = requestInfo.getMainTableInfo().getProperty();
                requestID = requestInfo.getRequestid();
                TransUtil tu = new TransUtil();
                RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
                String workflowID = requestInfo.getWorkflowid();
//                String tableName = tu.getTableName(workflowID);
                String tableName = requestInfo.getRequestManager().getBillTableName();
                logger_7396c45f.error(String.valueOf("K3PORequestAction--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);
                }
                String sftsk3 = mMap.get("SFTK3CLOUD");
                if ("1".equals(sftsk3)) {
                    return WeaResult.success(getResultMapForAction(weaverResultMap, "result", Action.SUCCESS, requestInfo.getRequestManager()));
                }
                String sqr = mMap.get("SQR");
                String sqrgh = unit.getWorkcode(sqr);
                // 公司代码
                String gsdm = mMap.get("GSDM");
                logger_7396c45f.error(String.valueOf("公司代码:" + gsdm));
                String bb = mMap.get("BB");
                String fPayCurrencyId = "CNY";
                if ("0".equals(bb)) {
                    fPayCurrencyId = "CNY";
                } else if ("1".equals(bb)) {
                    fPayCurrencyId = "USD";
                } else if ("2".equals(bb)) {
                    fPayCurrencyId = "EUR";
                } else if ("3".equals(bb)) {
                    fPayCurrencyId = "JPY";
                } else if ("4".equals(bb)) {
                    fPayCurrencyId = "AUD";
                } else if ("5".equals(bb)) {
                    fPayCurrencyId = "GBP";
                } else if ("7".equals(bb)) {
                    fPayCurrencyId = "TZS";
                }
                logger_7396c45f.error(String.valueOf("币别" + fPayCurrencyId));
                purReq.setUser(user);
                purReq.setPwd(psw);
                // 
                purReq.setFCompanyNumber(gsdm);
                // 
                purReq.setFdate(mMap.get("SQRQ"));
                // 
                purReq.setFBillTypeID(mMap.get("CGLXBM"));
                // 
                purReq.setFCurrencyId(fPayCurrencyId);
                // 
                purReq.setFPurchaserId(sqrgh);
                // 
                purReq.setFProjNO(mMap.get("XMBH"));
                // 
                purReq.setFInnerOrderNo("");
                // 
                purReq.setFDepartmentID(mMap.get("CBZX"));
                // 
                purReq.setFNote(mMap.get("BZ"));
                // 
                purReq.setFOAProcNO(mMap.get("LCBH"));
                logger_7396c45f.error(String.valueOf("明细表开始取值"));
                DetailTable[] detailtable = requestInfo.getDetailTableInfo().getDetailTable();
                DetailTable dtq = detailtable[0];
                Row[] sq = dtq.getRow();
                PORequestServiceStub.ArrayOfPORequestDt wlinfo = new PORequestServiceStub.ArrayOfPORequestDt();
                for (int j = 0; j < sq.length; j++) {
                    // 
                    Row rq = sq[j];
                    // 
                    Cell[] cq = rq.getCell();
                    // JSONObject item = new JSONObject();
                    PORequestServiceStub.PORequestDt dt = new PORequestServiceStub.PORequestDt();
                    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);
                    }
                    // 
                    dt.setFMaterialNumber(mDetailMap.get("WLBM"));
                    // 
                    dt.setFQty(mDetailMap.get("SQSL"));
                    dt.setFEntryNote(mDetailMap.get("BZ"));
                    dt.setFArrivalDate(mDetailMap.get("DHRQ"));
                    dt.setBudgetPrice(mDetailMap.get("CGYS"));
                    wlinfo.addPORequestDt(dt);
                }
                purReq.setLstPoReqDt(wlinfo);
                logger_7396c45f.error(String.valueOf("获取明细表数据结束"));
//                CallPORequestService service = new CallPORequestService();
                PORequestServiceStub.PORequestRes response = service.buildPORequest(purReq);
                logger_7396c45f.error("调用K3Cloud系统采购流程创建接口返回值" + response);
                // 1-??? 0-???
                String code = response.getCode();
                String result = response.getResult();
                String message = response.getMessage();
                String cgdddjbh = Util.null2String(response.getFBillNO());
                logger_7396c45f.error(String.valueOf(requestID + "result:code:" + code + " result:" + result + " message:" + message + " cgdddjbh:" + cgdddjbh));
                String sql = "update e10_core_business.dbo." + tableName + " set cgdddjbh='" + cgdddjbh + "' where id=" + requestID;
                String poolname = CONN_TYPE.workflow.getType();
                // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                boolean b = rs.executeSql(sql, poolname);
                logger_7396c45f.error(String.valueOf("b2 -----"+ b));
                logger_7396c45f.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_7396c45f.error(String.valueOf("K3PORequestAction--end--" + requestID));
            } catch (Exception e) {
                logger_7396c45f.error("Exception --" , e);
                logger_7396c45f.error(String.valueOf("K3Cloud系统接口失败，请联系K3Cloud系统管理员！"));
                requestInfo.getRequestManager().setMessageid("ERROR");
                requestInfo.getRequestManager().setMessagecontent("K3Cloud系统返回错误信息接口失败，请联系K3Cloud系统管理员！");
                return  WeaResult.fail(500, "K3PORequestAction 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_7396c45f.error("K3PORequestAction e: {}", e);
            return  WeaResult.fail(500, "K3PORequestAction 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;
    }
}
