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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.weaver.seconddev.interfaces.prop.ConfigProp;
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 org.springframework.core.env.Environment;
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.interfaces.workflow.action.Action;

/**
 * ZWZX-YS05-直贷业务发票申请流程
 * 数据同步给CRM
 */
@org.springframework.stereotype.Service("workflow_action_OaCrmZDYWFPAction")
public class OaCrmZDYWFPAction extends BaseBean implements Action, EsbServerlessRpcRemoteInterface {

    // 对应E9的请求信息对象
    @Autowired
    private RequestInfo requestInfoTemp;
    @Autowired
    private ConfigProp configProp;
    private static final Logger logger_afe2c4b5 = LoggerFactory.getLogger(OaCrmZDYWFPAction.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 systemFlag = "OA";
            String requestID = "";
            String workflowID = "";
            String tablename;
            try {
                logger_afe2c4b5.error(String.valueOf("OaCrmZDYWFPAction--start--" + requestID));
                Property[] properties = requestInfo.getMainTableInfo().getProperty();
                requestID = requestInfo.getRequestid();
                workflowID = requestInfo.getWorkflowid();
                BillFieldUtil util = new BillFieldUtil();
//                tablename = util.getTablename(workflowID);
                tablename = requestInfo.getRequestManager().getBillTableName();
                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 lcbh = mMap.get("LCBH");
                logger_afe2c4b5.error(String.valueOf(requestID + "流程编号:" + lcbh));
                String vendorName = mMap.get("VENDORNAME");
                logger_afe2c4b5.error(String.valueOf(requestID + "供应商名称:" + vendorName));
                String taxno = mMap.get("SH");
                logger_afe2c4b5.error(String.valueOf(requestID + "供应商税号:" + taxno));
                if (taxno == null || ("").equals(taxno)) {
                    // 如果税号为空就不调接口（处理修改之前在途的流程）
                    return WeaResult.success(getResultMapForAction(weaverResultMap, "result", Action.SUCCESS, requestInfo.getRequestManager()));
                }
                String companyName = mMap.get("COMPANYNAME");
                logger_afe2c4b5.error(String.valueOf(requestID + "公司名称:" + companyName));
                String companyCode = mMap.get("COMPANYCODE");
                logger_afe2c4b5.error(String.valueOf(requestID + "公司编码:" + companyCode));
                String applyAmount = mMap.get("APPLYAMOUNT");
                logger_afe2c4b5.error(String.valueOf(requestID + "原币金额:" + applyAmount));
                String kpmc = mMap.get("KPMC");
                logger_afe2c4b5.error(String.valueOf(requestID + "开票名称:" + kpmc));
                String sl = mMap.get("SL");
                sl = sl.replace("%", "");
                double taxRate = Integer.parseInt(sl) / 100.00;
                logger_afe2c4b5.error(String.valueOf(requestID + "税率:" + taxRate));
                String hrcode = mMap.get("HRCODE");
                logger_afe2c4b5.error(String.valueOf(requestID + "提交人工号:" + hrcode));
                String invoiceType = mMap.get("INVOICETYPE");
                int type = Integer.parseInt(invoiceType);
                type = type + 1;
                JSONObject mJson = new JSONObject();
                mJson.put("oaFlowCode", lcbh);
                mJson.put("requestID", requestID);
                mJson.put("workflowID", workflowID);
                mJson.put("name", vendorName);
                mJson.put("taxno", taxno);
                mJson.put("companyName", companyName);
                mJson.put("companyCode", companyCode);
                mJson.put("amount", applyAmount);
                mJson.put("materialName", kpmc);
                mJson.put("taxRate", taxRate);
                mJson.put("hrcode", hrcode);
                mJson.put("invoiceType", type);
                // EAS_YszxfpApplyResult mGetResult = new EAS_YszxfpApplyResult();
                // String result = mGetResult.getApproveResult(mJson,"EasYszxfpApplyResult");
                logger_afe2c4b5.error(requestID + " " + mJson.toString());
                // 调用接口
//                String url = Util.null2String(I18nContextUtilcus.getBean(Environment.class).getProperty("hteasoasync.OA_Golden_Rewrite")).trim();
//                String appKey = Util.null2String(I18nContextUtilcus.getBean(Environment.class).getProperty("hteasoasync.appKey")).trim();
                String url = configProp.getOA_Golden_Rewrite();
                String appKey = configProp.getWeaver_secondev_hteasoasync_appKey();
                SendPostRequest_API mGetResult = new SendPostRequest_API();
                String result = mGetResult.getResult(mJson, url, appKey);
                logger_afe2c4b5.error(String.valueOf(requestID + "调用CRM接口返回值：" + result));
                if (!"E".equals(result)) {
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    // 接口处理状态 S-成功，E-失败
                    String isTat = jsonObject.getString("state");
                    // 处理消息
                    String srMessage = jsonObject.getString("msg");
                    String goldenNum = jsonObject.getString("goldenNum");
                    if (!"S".equals(isTat)) {
                        // 失败
                        logger_afe2c4b5.error(String.valueOf(requestID + "CRM返回错误信息：" + srMessage));
                        requestInfo.getRequestManager().setMessageid("ERROR");
                        requestInfo.getRequestManager().setMessagecontent("CRM返回错误信息：" + srMessage);
                    } else {
                        RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
                        String sql = "update e10_core_business.dbo." + tablename + " set jssqdh='" + goldenNum + "' where id=" + requestID;
                        String poolname = CONN_TYPE.workflow.getType();
                        // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                        boolean b = rs.executeSql(sql, poolname);
                        logger_afe2c4b5.error(String.valueOf(requestID + "更新数据库：" + b));
                        logger_afe2c4b5.error(String.valueOf(requestID + "更新数据库成功！"));
                    }
                } else {
                    logger_afe2c4b5.error(String.valueOf(requestID + "调用CRM系统接口出错：" + result));
                    requestInfo.getRequestManager().setMessageid("ERROR");
                    requestInfo.getRequestManager().setMessagecontent("调用CRM系统接口返回失败，请联系CRM管理员！");
                    return  WeaResult.fail(500, "调用CRM系统接口出错：" + result, getResultMapForAction(weaverResultMap, "result","调用CRM系统接口出错：" + result, requestInfo.getRequestManager()));

                }
            } catch (Exception e) {
                logger_afe2c4b5.error(String.valueOf(requestID + "调用CRM系统接口出错：" + e.toString()));
                requestInfo.getRequestManager().setMessageid("ERROR");
                requestInfo.getRequestManager().setMessagecontent("调用CRM系统接口返回失败，请联系CRM管理员！");
                return  WeaResult.fail(500, "OaCrmZDYWFPAction 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_afe2c4b5.error("OaCrmZDYWFPAction e: {}", e.getMessage());
            return  WeaResult.fail(500, "OaCrmZDYWFPAction 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;
    }
}
