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

import com.alibaba.fastjson.JSONObject;
import com.weaver.seconddev.interfaces.prop.ConfigProp;
import com.weaver.verupgrade.general.StringUtil;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
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.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_ARSPaymentRecepitAction")
public class ARSPaymentRecepitAction extends BaseBean implements Action, EsbServerlessRpcRemoteInterface {

    // 对应E9的请求信息对象
    @Autowired
    private RequestInfo requestInfoTemp;
    @Autowired
    private ConfigProp configProp;
    private static final Logger logger_c29b3679 = LoggerFactory.getLogger(ARSPaymentRecepitAction.class);

    String operate;

    @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)));
        String newoperate = String.valueOf(requestInfoMap.getOrDefault("operate", -1));
        RequestInfo requestInfo = requestInfoTemp.getRequestInfo(requestIdTemp, userIdTemp);
        try {
            String requestid = requestInfo.getRequestid();
            logger_c29b3679.error(String.valueOf("ARSPaymentRecepitAction--start--" + requestid));
            logger_c29b3679.error(String.valueOf("newoperate--" + newoperate));
            try {
                String workflowid = requestInfo.getWorkflowid();
                logger_c29b3679.error( "workflowid--" + workflowid) ;
                Map<String, String> map = new HashMap<String, String>();

                Property[] properties = requestInfo.getMainTableInfo().getProperty();
                for (int i = 0; i < properties.length; i++) {
                    String name = properties[i].getName().toUpperCase();
                    String value = Util.null2String(properties[i].getValue());
                    map.put(name, value);
                }



                int hklx = 0;
                if ("0".equals(map.get("HKLX"))) {
                    hklx = 5;
                } else if ("1".equals(map.get("HKLX"))) {
                    hklx = 6;
                } else if ("2".equals(map.get("HKLX"))) {
                    hklx = 7;
                } else if ("3".equals(map.get("HKLX"))) {
                    hklx = 8;
                } else if ("4".equals(map.get("HKLX"))) {
                    hklx = 17;
                } else if ("5".equals(map.get("HKLX"))) {
                    hklx = 20;
                } else if ("6".equals(map.get("HKLX"))) {
                    hklx = 21;
                }
                JSONObject obj = new JSONObject();
                logger_c29b3679.error( "map--" + map) ;
                ResourceComInfo hrm = I18nContextUtil.getBean(ResourceComInfo.class);
                logger_c29b3679.error( "hrm--" + hrm.toString()) ;

                RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
                logger_c29b3679.error( "rs--" + rs.toString()) ;
                String currencyCode = "";
                String poolname = CONN_TYPE.ebuilder.getType();
                // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                String sql = "select id,currencyCode from e10_common.dbo.uf_eas_currency where id=" + map.get("BZ");
                logger_c29b3679.error( "sql--" + sql) ;
                boolean b1 = rs.executeSql(sql, poolname);
                logger_c29b3679.error( "sql flag  = " + b1) ;
                while (rs.next()) {
                    currencyCode = rs.getString("currencyCode");
                    logger_c29b3679.error( "currencyCode--" + currencyCode) ;
                }

                obj.put("ITFID", "ARSOA01");
                obj.put("SYSID", "SYS006");
                obj.put("ACCOUNTCODE", map.get("WLDWBM"));
                obj.put("ACCOUNTNAME", map.get("WLDWMC"));
                obj.put("VERIFYTYPE", Integer.parseInt(map.get("HXLX")) + 1);
                obj.put("BILLINGWAY", Integer.parseInt(map.get("SKFS")) + 1);
                obj.put("RETURNAMOUNT", map.get("HKJE"));
                obj.put("BILLINGTYPE", hklx);
                obj.put("ISPOSTING", Integer.parseInt(map.get("SFGZ")) == 0 ? 1 : 0);
                obj.put("PAYMENTTYPE", Integer.parseInt(map.get("FKLX")) + 1);
                obj.put("CURRENCY", currencyCode);
                obj.put("BILLINGDATE", map.get("HKRQ"));
                obj.put("REATE", map.get("REATE"));
                obj.put("SPONSORBUSINESSUNIT", map.get("CPGSBM"));
                // x
                obj.put("OAFLOW", map.get("LCBH"));
                obj.put("OAREQUESTID", requestid);
                // x
                //TODO custom 已处理 edit
                if ("2".equals(newoperate)) {
                    obj.put("BUSINESSUNITSYS", StringUtil.isEmpty(map.get("CLR"))?"":hrm.getWorkcode(map.get("CLR")));
                    logger_c29b3679.error( "map--" + map.toString()) ;

                }else {
                    obj.put("BUSINESSUNITSYS", "");
                }

                obj.put("BUSINESSUNIT", map.get("GZGSBM"));
                obj.put("OAID", workflowid);

                logger_c29b3679.error(" operate " + newoperate);
                obj.put("OPERATETYPE", newoperate);
                logger_c29b3679.error(" obj " + obj.toJSONString());
                logger_c29b3679.error(" newoperate " + obj.get("OPERATETYPE"));

                HttpClient client = new DefaultHttpClient();

//                String url = Util.null2String(I18nContextUtilcus.getBean(Environment.class).getProperty("htcrmoasync.CreateBilling")).trim();
//                String appkey = Util.null2String(I18nContextUtilcus.getBean(Environment.class).getProperty("htcrmoasync.appkey")).trim();
                String url = configProp.getCreateBilling();

                String appkey = configProp.getHtcrmoasync_appkey();

                logger_c29b3679.error(" url " + url);
                logger_c29b3679.error(" appkey " + appkey );
                HttpPost post = new HttpPost(url);
                post.setHeader(HTTP.CONTENT_TYPE, "application/json; charset=UTF-8");
                post.setHeader("Accept", "application/json; charset=UTF-8");
                post.setHeader("appkey", appkey);
                StringEntity entity = new StringEntity(obj.toString(), "UTF-8");
                post.setEntity(entity);
                HttpResponse response = client.execute(post);
                int rspCode = response.getStatusLine().getStatusCode();
                logger_c29b3679.error(String.valueOf("ZZ_SendPostRequest---rspCode" + rspCode));
                String result = "E";
                if (rspCode == 200) {
                    result = EntityUtils.toString(response.getEntity(), "UTF-8");
                }
                logger_c29b3679.error("ARSPaymentRecepitAction-result=　" +result);
                if (!"E".equals(result)) {
                    JSONObject ret = JSONObject.parseObject(result);
                    if (!"S".equals(ret.get("status"))) {
                        requestInfo.getRequestManager().setMessageid("ERROR");
                        requestInfo.getRequestManager().setMessagecontent("ARS接口返回信息" + ret.get("message"));
                        return  WeaResult.fail(500, "ARS接口返回信息:"+ ret.get("message"), getResultMapForAction(weaverResultMap, "result", ret.get("message"), requestInfo.getRequestManager()));

                    } else {
                        if ("2".equals(newoperate)) {
                            // 正式formtable_main_2714,测试formtable_main_2252，formtable_main_2401
                            boolean billingno = rs.execute("update e10_core_business.dbo.formtable_main_2714 set hkdh='" + ret.get("billingno") + "' where id=" + requestid);
                            logger_c29b3679.error( "ret--" + ret.toString()) ;
                            logger_c29b3679.error("sql　＝　" +"update e10_core_business.dbo.formtable_main_2714 set hkdh='" + ret.get("billingno") + "' where id=" + requestid);
                            logger_c29b3679.error("billingno　＝　" +billingno);
                        }
                    }
                }
            } catch (Exception e) {
                logger_c29b3679.error(String.valueOf("ARSPaymentRecepitAction--error--" + requestid + "|" + e.toString()));
                requestInfo.getRequestManager().setMessageid("ERROR");
                requestInfo.getRequestManager().setMessagecontent("调用ARS接口出错" + e.toString());
                logger_c29b3679.error("ARSPaymentRecepitAction e: {}", e);
                e.printStackTrace();
                return  WeaResult.fail(500, "调用ARS接口出错:"+e, getResultMapForAction(weaverResultMap, "result", e.getMessage(), requestInfo.getRequestManager()));
            }
            logger_c29b3679.error(String.valueOf("ARSPaymentRecepitAction--start--" + requestid));
            return WeaResult.success(getResultMapForAction(weaverResultMap, "result", Action.SUCCESS, requestInfo.getRequestManager()));
        } catch (Exception e) {
            e.printStackTrace();
            logger_c29b3679.error("ARSPaymentRecepitAction e: {}", e);
            return  WeaResult.fail(500, "出错啦: "+e, getResultMapForAction(weaverResultMap, "result", e.getMessage(), requestInfo.getRequestManager()));
        }
    }

    public String getOperate() {
        return operate;
    }

    public void setOperate(String operate) {
        this.operate = operate;
    }

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