package com.jianshui.income.utils.elephant;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.jianshui.common.core.domain.entity.Companyservice;
import com.jianshui.common.exception.jianshui.JianshuiServiceConfigErrorException;
import com.jianshui.common.exception.jianshui.JianshuiServiceException;
import com.jianshui.common.utils.DictUtils;
import com.jianshui.common.utils.RedisUtil;
import com.jianshui.common.utils.spring.SpringUtils;
import com.jianshui.common.utils.uuid.IdUtils;
import com.jianshui.income.constant.elephant.ElephantAuthConstants;
import com.jianshui.income.constant.elephant.ElephantConstants;
import com.jianshui.system.domain.CompanyserviceProp;
import com.jianshui.system.service.ICompanyservicePropService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.util.Base64Utils;
import redis.clients.jedis.Jedis;

import java.nio.charset.StandardCharsets;

/**
 * @Description 区分多companyservice的工具类
 * @Author 巩权林
 * @Date 2022-09-19 9:37
 **/
public class ElephantCompanyserviceUtils {


    //大象token标志
    private final static String ELE_TOKEN = "elephant_income_token";

    private static String ELE_URL;

    static {
        Environment environment = SpringUtils.getBean(Environment.class);
        ELE_URL = environment.getProperty("ele_auth_url");
    }

    /**
     * 发送请求到大象
     *
     * @param apiName 大象方法名。在EleIncomeConstant中
     * @param reqBody 请求体
     * @return
     * @throws Exception
     */
    public static JSONObject request(String apiName, Object reqBody, Companyservice companyservice) throws Exception {
        String entCode = companyservice.getSellertax() != null ? companyservice.getSellertax() : "";
        if (StringUtils.isEmpty(entCode)) {
            throw new Exception("未配置系统entCode，请联系管理员！");
        }

        String token = getToken(companyservice);

        //1.报文组装
        JSONObject requestBody = new JSONObject();
        requestBody.put("zipCode", "0");
        requestBody.put("encryptCode", "0");
        requestBody.put("dataExchangeId", StringUtils.leftPad(IdUtils.fastSimpleUUID(), 32));
        requestBody.put("entCode", entCode);
        requestBody.put("content",
                Base64Utils.encodeToString(JSONUtil.parse(reqBody).toString().getBytes(StandardCharsets.UTF_8)));


        //2.请求及解析
        String url = ELE_URL + ElephantAuthConstants.PREFIX + apiName + "?access_token=" + token;
        String respRaw = HttpUtil.createPost(url).body(requestBody.toString()).execute().body();
        JSONObject resp = JSONObject.parseObject(respRaw, JSONObject.class);
        JSONObject returnStateInfo = resp.getJSONObject("returnStateInfo");
        if (returnStateInfo == null) {
            throw new JianshuiServiceException("上游接口请求返回异常，请联系管理员处理。returnStateInfo为null");
        }
        String returnCode = returnStateInfo.getString("returnCode");
        if (!StringUtils.equals("0000", returnCode)) {
            throw new JianshuiServiceException(new String(Base64Utils.decodeFromString(returnStateInfo.getString("returnMessage"))));
        }

        String content = new String(Base64Utils.decodeFromString(resp.getString("content")));
        return JSONObject.parseObject(content, JSONObject.class);
    }

    /**
     * 获取大象token
     *
     * @return
     */
    public static String getToken(Companyservice companyservices) throws Exception {
        ICompanyservicePropService propService = SpringUtils.getBean(ICompanyservicePropService.class);

        if (BeanUtil.isEmpty(companyservices)) {
            throw new Exception("未配置系统app key，请联系管理员！");
        }

        //系统存在当即返回
        Jedis jedis = RedisUtil.getJedis();
        if (jedis == null) {
            throw new Exception("系统异常，获取缓存系统失败，请联系管理员");
        }
        String token = jedis.get(ELE_TOKEN);
        if (StringUtils.isNotEmpty(token)) {
            return token;
        }

        //获取token配置参数
        CompanyserviceProp propAuthKey = propService.selectPropByKey(companyservices.getCompanyid(), "elephant_income_appkey");
        String propAuthKeyS = getValue(propAuthKey.getValue());
        CompanyserviceProp propAuthSecret = propService.selectPropByKey(companyservices.getCompanyid(), "elephant_income_appsecret");
        String propAuthSecretS = getValue(propAuthSecret.getValue());

        if (StrUtil.isEmpty(propAuthKeyS) || StrUtil.isEmpty(propAuthSecretS)) {
            jedis.close();
            throw new Exception("未配置系统app key/app secret，请联系管理员！！!");
        }

        String url = ELE_URL + "authen/token";
        JSONObject body = new JSONObject();
        body.put("appKey", propAuthKeyS);
        body.put("appSecret", propAuthSecretS);
        String responseRaw = HttpUtil.createPost(url).body(JSONObject.toJSONString(body)).execute().body();
        if (StringUtils.isEmpty(responseRaw)) {
            throw new Exception("上游生产异常，请紧急联系管理员处理！");
        }
        JSONObject response = JSONObject.parseObject(responseRaw, JSONObject.class);
        token = response.getString("access_token");
        if (StringUtils.isEmpty(token)) {
            throw new JianshuiServiceConfigErrorException("大象app secret/app key错误，请检查配置");
        }
        Integer expiresIn = response.getInteger("expires_in");
        jedis.setex(ELE_TOKEN, (long) expiresIn, token);
        jedis.close();
        return token;
    }

    /**
     * Object toString
     *
     * @param obje
     * @return
     */
    public static String getValue(Object obje) {
        return obje != null ? obje.toString() : "";
    }

}
