package com.hfkj.channel.saas.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hfkj.channel.saas.config.SaasConfig;
import com.hfkj.channel.saas.saasenum.FileImgType;
import com.hfkj.common.Base64Util;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.utils.HttpsUtils;
import com.hfkj.common.utils.RedisUtil;
import com.hfkj.config.CommonSysConst;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.mime.content.FileBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 公共
 * @className: SasaCommon
 * @author: HuRui
 * @date: 2023/4/4
 **/
@Component
public class SaasCommon {

    private static final Logger log = LoggerFactory.getLogger(SaasCommon.class);

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 获取token
     * @return
     */
    public Object getToken() {
        try {
            Object saasToken = redisUtil.get("SAAS_TOKEN");
            if (saasToken != null) {
                return saasToken.toString();
            }
            Map<String,Object> param = new HashMap<>();
            param.put("grant_type", "client_credentials");
            param.put("client_id", SaasConfig.client_id);
            param.put("client_secret", SaasConfig.client_secret);

            Map<String,Object> header = new HashMap<>();
            header.put("Authorization", "Basic " + Base64Util.encode(SaasConfig.client_id+":"+SaasConfig.client_secret));

            // 请求参数
            String requestParam = SaasUtils.paramSort(param);

            log.info("==============start 获取token start ==============");
            log.info("请求header:" + JSONObject.toJSONString(header));
            log.info("请求参数:" + requestParam);
            JSONObject jsonObject = HttpsUtils.doPostForm(SaasConfig.requestMerRegistrationTokenUrl, requestParam, header);
            log.info("响应参数:" + jsonObject);
            if (StringUtils.isNotBlank(jsonObject.getString("access_token"))) {
                redisUtil.set("SAAS_TOKEN", jsonObject.getString("access_token"), jsonObject.getLong("expires_in"));
                return jsonObject.getString("access_token");
            }
        } catch (Exception e) {
            log.info("出现异常:", e);
            return null;
        } finally {
            log.info("==============end 获取token end ==============");
        }
        return null;
    }

    public Object getUpdateToken() {
        try {
            Object saasToken = redisUtil.get("SAAS_UPDATE_TOKEN");
            if (saasToken != null) {
                return saasToken.toString();
            }
            Map<String,Object> param = new HashMap<>();
            param.put("grant_type", "password");
            param.put("username", SaasConfig.username);
            param.put("password", SaasConfig.password);
            param.put("scope", "all");

            Map<String,Object> header = new HashMap<>();
            header.put("Authorization", "Basic " + Base64Util.encode(SaasConfig.client_id+":"+SaasConfig.client_secret));

            // 请求参数
            String requestParam = SaasUtils.paramSort(param);

            log.info("==============start 获取token start ==============");
            log.info("请求header:" + JSONObject.toJSONString(header));
            log.info("请求参数:" + requestParam);
            JSONObject jsonObject = HttpsUtils.doPostForm(SaasConfig.requestMerRegistrationTokenUrl, requestParam, header);
            log.info("响应参数:" + jsonObject);
            if (StringUtils.isNotBlank(jsonObject.getString("access_token"))) {
                redisUtil.set("SAAS_UPDATE_TOKEN", jsonObject.getString("access_token"), jsonObject.getLong("expires_in"));
                return jsonObject.getString("access_token");
            }
        } catch (Exception e) {
            log.info("出现异常:", e);
            return null;
        } finally {
            log.info("==============end 获取token end ==============");
        }
        return null;
    }

    /**
     * 文件上传
     * @param file 文件
     * @param attType 文件类型
     * @param sourcechnl  来源 0:PC,1:安卓,2:IOS
     * @return
     */
    public JSONObject fileUpload(File file, String attType, String sourcechnl) {
        try {
            Map<String,Object> param = new HashMap<>();
            param.put("file", new FileBody(file));
            param.put("imgType", attType);
            param.put("sourcechnl", sourcechnl);
            param.put("isOcr", false);

            Map<String,Object> header = new HashMap<>();
            header.put("Authorization", "bearer " + getToken());

            JSONObject jsonObject = HttpsUtils.doPostSaasUpload(SaasConfig.requestMerRegistrationCommonUrl+"/file/upload",file,param, header);
            if (!jsonObject.getString("status").equals("00")) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "文件上传失败");
            }
            return jsonObject;
        } catch (Exception e) {
            System.out.println(e);
            return null;
        }
    }

    /**
     * 查询商户类别【父类】
     * @param parentCode
     * @return
     */
    public JSONArray getCategory(String parentCode) {
        try {
            Map<String,Object> param = new HashMap<>();
            param.put("businessScene", 2);
            if (StringUtils.isNotBlank(parentCode)) {
                param.put("parentCode", parentCode);
            }

            Map<String,Object> header = new HashMap<>();
            header.put("Authorization", "bearer " + getToken());

            String result = HttpsUtils.doSaasGet(SaasConfig.requestMerRegistrationCommonUrl+"customer/category", param, header, true);
            return JSONArray.parseArray(result);
        } catch (Exception e) {
            System.out.println(e);
            return null;
        }
    }

    /**
     * 查询地区编码
     * @param parentCode
     * @return
     */
    public JSONArray getArea(String parentCode) {
        try {
            Map<String,Object> param = new HashMap<>();
            param.put("parentCode", parentCode);

            Map<String,Object> header = new HashMap<>();
            header.put("Authorization", "bearer " + getToken());

            String result = HttpsUtils.doSaasGet(SaasConfig.requestMerRegistrationCommonUrl+"organization", param, header, false);
            return JSONArray.parseArray(result);
        } catch (Exception e) {
            System.out.println(e);
            return null;
        }
    }

    /**
     * 查询银行地区编码
     * @param parentCode
     * @return
     */
    public JSONArray getBankArea(String parentCode) {
        try {
            Map<String,Object> param = new HashMap<>();
            param.put("parentCode", parentCode);

            Map<String,Object> header = new HashMap<>();
            header.put("Authorization", "bearer " + getToken());

            String result = HttpsUtils.doSaasGet(SaasConfig.requestMerRegistrationCommonUrl + "/organization/bank", param, header, false);
            return JSONArray.parseArray(result);

        } catch (Exception e) {
            System.out.println(e);
            return null;
        }
    }

    /**
     * 查询银行列表
     * @param areaCode  地区编码
     * @param bankName  银行名称
     * @return
     */
    public JSONArray getBank(String areaCode,String bankName) {
        try {
            Map<String,Object> param = new HashMap<>();
            param.put("areaCode", areaCode);
            param.put("bankName", bankName);

            Map<String,Object> header = new HashMap<>();
            header.put("Authorization", "bearer " + getToken());

            String result = HttpsUtils.doSaasGet(SaasConfig.requestMerRegistrationCommonUrl + "/bank", param, header, true);
            return JSONArray.parseArray(result);
        } catch (Exception e) {
            System.out.println(e);
            return null;
        }
    }
}
