package com.kiisoo.ic.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kiisoo.ic.common.utils.httpClientUtil.HttpClientUtil;
import com.kiisoo.ic.config.WxCpConfiguration;
import com.kiisoo.ic.wx.entity.ContactWayDTO;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.kiisoo.ic.config.WxCpConfiguration.APPLICATIONID;

/**
 * @author dexiang.jiang
 * @data 2017/03/11
 * @details 微信API 配置
 */
public class WeixinApi {

    /**
     * 打印日志
     */
    private static final Logger logger = LoggerFactory.getLogger(WeixinApi.class);

    public static final String ERRCODE = "errcode";
    public static final String ERRMSG = "errmsg";
    public static final String ACCESS_TOKEN = "access_token";
    public static final String USERID = "UserId";
    public static final String TICKET = "ticket";

    /**
     * 企业ID
     */
    public static final String CORPID = "ww6f6138e7d7cac0f4";

    /**
     * 企业秘钥
     */
    public static final String CORPSECRET = "Iw1OhiRnASC63B6c9yplOLril87YHPchR-eetvvBSnE";

    public static final String TOKEN = "xX8XSN4MY5bGWdxrbDTVrtB";
    public static final String ENCODING_AES_KEY = "RwYBA8OPZxx5UwEJzJdltZbamKdWfNjqu3lYcozJBYs";

    /**
     * 通讯录回调事件
     */
    public static final String CONTACT_TOKEN = "xX8XSN4MY5bGWdxrbDTVrtB";
    public static final String CONTACT_ENCODING_AES_KEY = "RwYBA8OPZxx5UwEJzJdltZbamKdWfNjqu3lYcozJBYs";

    /**
     * 客户联系回调事件
     */
    public static final String CUSTOMER_TOKEN = "xX8XSN4MY5bGWdxrbDTVrtB";
    public static final String CUSTOMER_ENCODING_AES_KEY = "RwYBA8OPZxx5UwEJzJdltZbamKdWfNjqu3lYcozJBYs";


    public static String getToken() throws IOException {
        JSONObject jsonObject2 = null;
        jsonObject2 = JSON.parseObject(HttpClientUtil.httpGet("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + CORPID + "&corpsecret=" + CORPSECRET).getMessage());
        if (null != jsonObject2) {
            if (jsonObject2.containsKey(ERRCODE)
                    && jsonObject2.getInteger(ERRCODE) != 0) {
                logger.error("通过code获取网页Token失败 errcode:" + jsonObject2.getInteger(ERRCODE) + "---errmsg:" + jsonObject2.getString(ERRMSG));
                return null;
            } else {
                return jsonObject2.getString(ACCESS_TOKEN);
            }
        } else {
            return null;
        }

    }

    public static String readToken() {
        String fileName = "access_token.txt";
        FileInputStream inputStream = null;
        BufferedReader bufferedReader = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            File file = new ClassPathResource(fileName).getFile();
            inputStream = new FileInputStream(file);
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            String txt = bufferedReader.readLine();
            if (StringUtils.isBlank(txt)) {
                String token = getToken();
                write(fileName, sdf.format(new Date()) + "," + token);
                return token;
            } else {
                String[] split = txt.split(",");
                Date date = sdf.parse(split[0]);
                String accessToken = split[1];
                Calendar saveCalendar = Calendar.getInstance();
                saveCalendar.setTime(date);
                saveCalendar.add(Calendar.HOUR, 2);
                Date saveTime = saveCalendar.getTime();


                if (saveTime.before(new Date())) {
                    String token = getToken();
                    write(fileName, sdf.format(new Date()) + "," + token);
                    return token;
                }
                return accessToken;
            }
        } catch (Exception e) {
            logger.error("文件不存在", e);
            return null;
        } finally {
            try {
                inputStream.close();
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void write(String fileName, String text) throws IOException {
        File file = new ClassPathResource(fileName).getFile();
        FileOutputStream outputStream = new FileOutputStream(file);
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
        bufferedWriter.write(text);
        bufferedWriter.flush();
        bufferedWriter.close();
    }


    public static String getJsTicketByFile() {
        String fileName = "js_ticket.txt";
        FileInputStream inputStream = null;
        BufferedReader bufferedReader = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            File file = new ClassPathResource(fileName).getFile();
            inputStream = new FileInputStream(file);
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            String txt = bufferedReader.readLine();
            if (StringUtils.isBlank(txt)) {
                String token = getToken();
                String ticket = getJsTicket(token);
                write(fileName, sdf.format(new Date()) + "," + ticket);
                return token;
            } else {
                String[] split = txt.split(",");
                Date date = sdf.parse(split[0]);
                String ticket = split[1];
                Calendar saveCalendar = Calendar.getInstance();
                saveCalendar.setTime(date);
                saveCalendar.add(Calendar.HOUR, 2);
                Date saveTime = saveCalendar.getTime();

                if (saveTime.before(new Date())) {
                    String token = getToken();
                    ticket = getJsTicket(token);
                    write(fileName, sdf.format(new Date()) + "," + ticket);
                }
                return ticket;
            }
        } catch (Exception e) {
            logger.error("文件不存在", e);
            return null;
        } finally {
            try {
                inputStream.close();
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 根据token获取企业微信凭证
     *
     * @param token TOKEN
     * @return 返回凭证
     * @throws IOException IO异常
     * @author dexiang.jiang
     * @date 2020/03/11 15:25
     */
    public static String getJsTicket(String token) throws IOException {
        JSONObject jsonObject2 = null;
        jsonObject2 = JSON.parseObject(HttpClientUtil.httpPost("https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=" + token, "", "").getMessage());
        if (null != jsonObject2) {
            if (jsonObject2.containsKey(ERRCODE) && jsonObject2.getInteger(ERRCODE) != 0) {
                logger.error("通过code获取网页Token失败 errcode:" + jsonObject2.getInteger("errcode") + "-errmsg:" + jsonObject2.getString(ERRMSG));
                return null;
            } else {
                return jsonObject2.getString(TICKET);
            }
        } else {
            return null;
        }

    }

    /**
     * 获取微信用户信息
     *
     * @param token
     * @param code
     * @return
     */
    public static String getUserLoginInfo(String token, String code) throws IOException {
        JSONObject jsonObject2 = null;
        jsonObject2 = JSON.parseObject(HttpClientUtil.httpGet("https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=" + token + "&code=" + code).getMessage());
        if (null != jsonObject2) {
            if (jsonObject2.containsKey(ERRCODE) && jsonObject2.getInteger(ERRCODE) != 0) {
                return null;
            } else {
                String qywxUserId = jsonObject2.getString(USERID);
                return qywxUserId;
            }
        } else {
            return null;
        }
    }

    /**
     * 企业微信-客户列表
     *
     * @param userid 企业内部用户ID
     * @return 客户列表集合
     * @throws IOException IO异常
     * @author dexiang.jiang
     * @date 2020/03/11 15:25
     */
    public static String getExternalContact(String userid) throws IOException {
        String token = readToken();
        JSONObject jsonObject2 = null;
        jsonObject2 = JSON.parseObject(HttpClientUtil.httpPost("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/list?access_token=" + token + "&userid=" + userid, "", "").getMessage());
        if (null != jsonObject2) {
            if (jsonObject2.containsKey(ERRCODE) && jsonObject2.getInteger(ERRCODE) != 0) {
                logger.error("通过code获取网页Token失败 errcode:" + jsonObject2.getInteger("errcode") + "-errmsg:" + jsonObject2.getString(ERRMSG));
                return null;
            } else {
                return jsonObject2.toJSONString();
            }
        } else {
            return null;
        }

    }

    /**
     * 企业微信-获取企业已配置的「联系我」方式
     *
     * @param contactWayDTO 对象
     * @return 客户列表集合
     * @throws IOException IO异常
     * @author dexiang.jiang
     * @date 2020/03/11 15:25
     */
    public static String addContactWay(ContactWayDTO contactWayDTO) throws IOException {
        String token = readToken();
        JSONObject jsonObject2 = null;
        jsonObject2 = JSON.parseObject(HttpClientUtil.httpPost("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/add_contact_way?access_token=" + token, JSON.toJSONString(contactWayDTO)).getMessage());
        if (null != jsonObject2) {
            if (jsonObject2.containsKey(ERRCODE) && jsonObject2.getInteger(ERRCODE) != 0) {
                logger.error("configId errcode:" + jsonObject2.getInteger("errcode") + "-errmsg:" + jsonObject2.getString(ERRMSG));
                return null;
            } else {
                return jsonObject2.toJSONString();
            }
        } else {
            return null;
        }

    }

    /**
     * 企业微信-获取企业已配置的「联系我」方式
     *
     * @param configId 联系方式的配置id
     * @return 客户列表集合
     * @throws IOException IO异常
     * @author dexiang.jiang
     * @date 2020/03/11 15:25
     */
    public static String getContactWay(String configId) throws IOException {
        String token = readToken();
        JSONObject jsonObject2 = null;
        Map<String, Object> map = new HashMap<>();
        map.put("config_id", configId);
        map.put("access_token", token);
        jsonObject2 = JSON.parseObject(HttpClientUtil.httpPost("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_contact_way?access_token=" + token, JSON.toJSONString(map), "").getMessage());
        if (null != jsonObject2) {
            if (jsonObject2.containsKey(ERRCODE) && jsonObject2.getInteger(ERRCODE) != 0) {
                logger.error("configId errcode:" + jsonObject2.getInteger("errcode") + "-errmsg:" + jsonObject2.getString(ERRMSG));
                return null;
            } else {
                return jsonObject2.toJSONString();
            }
        } else {
            return null;
        }

    }

    /**
     * 获取客户详情
     * @param externalUserId 外部联系人的userid，注意不是企业成员的帐号
     * @return 企业可通过此接口，根据外部联系人的userid（如何获取?），拉取客户详情。
     * @throws IOException IO异常
     */
    public static String getExternalContactInfo(String externalUserId) throws IOException, WxErrorException {
        WxCpService cpService = WxCpConfiguration.getCpService(APPLICATIONID);
        String token = cpService.getAccessToken();
        JSONObject jsonObject2 = null;
        jsonObject2 = JSON.parseObject(HttpClientUtil.httpGet("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get?access_token=" + token + "&external_userid=" + externalUserId).getMessage());
        if (null != jsonObject2) {
            if (jsonObject2.containsKey(ERRCODE) && jsonObject2.getInteger(ERRCODE) != 0) {
                logger.error("configId errcode:" + jsonObject2.getInteger("errcode") + "-errmsg:" + jsonObject2.getString(ERRMSG));
                return null;
            } else {
                return jsonObject2.toJSONString();
            }
        } else {
            return null;
        }
    }
}
