package com.weaver.seconddev.interfaces.swfa.sl;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.weaver.common.cache.base.BaseCache;
import com.weaver.seconddev.interfaces.htjt.util.TransUtil;
import com.weaver.seconddev.interfaces.prop.ConfigProp;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import java.util.Date;
import java.util.Map;
import java.util.UUID;
import java.lang.*;
import com.weaver.common.i18n.tool.util.I18nContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.weaver.verupgrade.general.BaseBean;
import com.weaver.verupgrade.general.Util;
import org.springframework.stereotype.Component;

@Component
public class CallDTtripService extends BaseBean {

    private static final org.slf4j.Logger logger_a99d9846 = LoggerFactory.getLogger(CallDTtripService.class);

    private static CloseableHttpClient httpClient = HttpClients.createDefault();

    private static HttpPost httpPost;
    @Autowired
    private ConfigProp configProp;
    public String[] optForDTtrip(Map<String, Object> param) {
        String[] str = new String[3];
        try {
//            String url = Util.null2String(I18nContextUtilcus.getBean(Environment.class).getProperty("htsloasync.dttrip_orderUrl")).trim();
            String url = configProp.getDttrip_orderUrl();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("isEncrypt", false);
            jsonObject.put("random", UUID.randomUUID().toString());
            jsonObject.put("timestamp", new Date().getTime());
            String outEmployeeId = String.valueOf(param.get("outEmployeeId"));
//            String account = Util.null2String(getPropValue("htsloasync", "dttrip_account")).trim();
//            String password = Util.null2String(getPropValue("htsloasync", "dttrip_password")).trim();
//            String secret = Util.null2String(getPropValue("htsloasync", "dttrip_secret")).trim();
            String account = configProp.getDttrip_account();
            String password = configProp.getDttrip_password();
            String secret =configProp.getDttrip_secret();
            TransUtil tu = new TransUtil();
            Map<String,String> map = tu.getDTtripMt(outEmployeeId);
            if(!"".equals(Util.null2String(map.get("account")))){
                account = map.get("account");
                password = map.get("password");
                secret = map.get("secret");
            }
            String accessToken = getToken(jsonObject,account,password);
            if ("E".equals(accessToken)) {
                str[0] = "E";
                str[1] = "获取同程Token失败！";
                str[2] = "";
                return str;
            }
            jsonObject.put("accessToken", accessToken);
            jsonObject.put("param", param);
            logger_a99d9846.error("调用同程差旅单接口数据：" + jsonObject.toJSONString());
            httpPost = new HttpPost(url + "?sign=" + getSign(jsonObject.toJSONString(),secret));
            httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json; charset=UTF-8");
            httpPost.setHeader("Accept", "application/json; charset=UTF-8");
            StringEntity entity = new StringEntity(jsonObject.toJSONString(), "UTF-8");
            httpPost.setEntity(entity);
            CloseableHttpResponse response = httpClient.execute(httpPost);
            int rspCode = response.getStatusLine().getStatusCode();
            logger_a99d9846.error(String.valueOf("调用同程接口返回状态码：" + rspCode));
            if (rspCode == 200) {
                String result = EntityUtils.toString(response.getEntity(), "UTF-8");
                JSONObject ret = JSON.parseObject(result);
                logger_a99d9846.error("调用同程接口返回结果：" + ret.toJSONString());
                str[1] = (String) ret.get("errorMessage");
                if ((Boolean) ret.get("success")) {
                    str[0] = "S";
                    JSONObject data = (JSONObject) ret.get("data");
                    str[2] = (String) data.get("travelApplyNo");
                } else {
                    str[0] = "E";
                    str[2] = "";
                }
            }
            if (response != null) {
                response.close();
            }
            return str;
        } catch (Exception e) {
            logger_a99d9846.error(String.valueOf("调用同程差旅单接口异常：" + e.toString()));
        }
        str[0] = "E";
        str[1] = "出差单同步同程失败！";
        str[2] = "";
        return str;
    }

    public String getToken(JSONObject jsonObject,String account,String password){
//        String token = (String) Util_DataCache.getObjVal("DTtrip_token");
        String token = "";
        if (token == null) {
            String result = "";
//            String url = Util.null2String(I18nContextUtilcus.getBean(Environment.class).getProperty("htsloasync.dttrip_tokenUrl")).trim();
//            String account = Util.null2String(I18nContextUtilcus.getBean(Environment.class).getProperty("htsloasync.dttrip_account")).trim();
//            String password = Util.null2String(I18nContextUtilcus.getBean(Environment.class).getProperty("htsloasync.dttrip_password")).trim();
            String url = configProp.getDttrip_tokenUrl();
//            String account = configProp.getDttrip_account();
//            String password = configProp.getDttrip_password();
            httpPost = new HttpPost(url);
            httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json; charset=UTF-8");
            httpPost.setHeader("Accept", "application/json; charset=UTF-8");
            JSONObject param = new JSONObject();
            param.put("account", account);
            param.put("password", password);
            param.put("tokenType", "");
            jsonObject.put("param", param);
            try {
                logger_a99d9846.error(jsonObject.toJSONString());
                StringEntity entity = new StringEntity(jsonObject.toJSONString(), "UTF-8");
                httpPost.setEntity(entity);
                CloseableHttpResponse response = httpClient.execute(httpPost);
                int rspCode = response.getStatusLine().getStatusCode();
                logger_a99d9846.error(String.valueOf("调用同程接口返回状态码：" + rspCode));
                if (rspCode == 200) {
                    result = EntityUtils.toString(response.getEntity(), "UTF-8");
                    JSONObject ret = JSON.parseObject(result);
                    logger_a99d9846.error("getToken:" + ret.toJSONString());
                    if ((Boolean) ret.get("success")) {
                        JSONObject data = (JSONObject) ret.get("data");
                        token = (String) data.get("accessToken");
                        /*String time = (String)data.get("expiryTime");
                        Util_DataCache.setObjVal("DTtrip_token",token,Integer.parseInt(time));*/
                    }
                } else {
                    token = "E";
                }
                if (response != null) {
                    response.close();
                }
            } catch (Exception e) {
                token = "E";
                logger_a99d9846.error(String.valueOf("调用同程接口异常：" + e.toString()));
            }
        }
        return token;
    }

    public String getSign(String postJson,String secret){
//        String secret = Util.null2String(I18nContextUtilcus.getBean(Environment.class).getProperty("htsloasync.dttrip_secret")).trim();
//        String secret = configProp.getDttrip_secret();
        String postData_md5 = SecureUtil.md5(postJson).toLowerCase();
        String finallySign = SecureUtil.md5(postData_md5 + secret).toLowerCase();
        return finallySign;
    }
}
