package com.lz.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lz.modules.job.model.responseBo.DepartmentInfosBo;
import com.lz.modules.job.model.responseBo.DepartmentStaffBo;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
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.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component("feishuRobotUtil")
public class FeishuUtil {
    protected static Logger logger = LoggerFactory.getLogger(FeishuUtil.class);

    @Autowired
    RedisUtils redisUtils;

    public static CloseableHttpClient getHttpClient() {
        try {
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(builder.build(),
                    NoopHostnameVerifier.INSTANCE);
            Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", new PlainConnectionSocketFactory())
                    .register("https", sslConnectionSocketFactory)
                    .build();
            PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
            cm.setMaxTotal(100);
            CloseableHttpClient httpclient = HttpClients.custom()
                    .setSSLSocketFactory(sslConnectionSocketFactory)
                    .setDefaultCookieStore(new BasicCookieStore())
                    .setConnectionManager(cm).build();
            return httpclient;
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }
        return HttpClients.createDefault();
    }

    public String SendImageByApacheHttpClient(File file, String authorization) throws IOException {
        CloseableHttpClient client = getHttpClient();
        HttpPost post = new HttpPost("https://open.feishu.cn/open-apis/image/v4/put/");
        final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        FileBody bin = new FileBody(file);
        builder.addPart("image", bin);
        builder.addTextBody("image_type", "message");
        HttpEntity multiPartEntity = builder.build();
        post.setEntity(multiPartEntity);
        post.setHeader("Authorization", "Bearer " + authorization);
        CloseableHttpResponse response = client.execute(post);
        logger.info("http response code:" + response.getStatusLine().getStatusCode());
//        for (Header header: response.getAllHeaders()) {
//            System.out.println(header.toString());
//        }
        if (StringUtil.equals(response.getStatusLine().getStatusCode() + "", "99991663")) {
            authorization = this.getAccessToken();
            redisUtils.set(Constant.FEI_SHU_ROBOT_TOKEN, authorization);
            SendImageByApacheHttpClient(file, authorization);
        }
        HttpEntity resEntity = response.getEntity();
        if (resEntity == null) {
            logger.info("never here?");
            return "";
        }
        logger.info("Response content length: " + resEntity.getContentLength());
        return EntityUtils.toString(resEntity);
    }

    /**
     * 获取机器人的有效token值
     *
     * @return
     * @throws IOException
     */
    public static String getAccessToken() {
        String url = "https://open.feishu.cn/open-apis/auth/v3/app_access_token/internal/";
        Map<String, String> data = new HashMap<String, String>();
        data.put("app_id", "cli_9e22ac4f7bfa100d");
        data.put("app_secret", "WIYyBMIkSHh8Jd85M8fqyepCRJPgirXU");
        String resultStr = HttpUtil.doHttpPost(url, data, "UTF-8");
        JSONObject dataObj = JSON.parseObject(resultStr);
        String tenant_access_token = dataObj.getString("tenant_access_token");
        return tenant_access_token;
    }

    /**
     * 1获取通讯录授权范围（获取顶级部门Id列表）
     *
     * @param accessToken
     * @return
     */
    public List<String> getDepartmentIds(String accessToken) {
        String urlStr = "https://open.feishu.cn/open-apis/contact/v1/scope/get";
        String result = HttpUtil.feishuGet(urlStr, accessToken);
        JSONObject dataObj = JSON.parseObject(result);
        List<String> departmentIds = JSONArray.parseArray(dataObj.getJSONObject("data").getString("authed_departments"), String.class);
        return departmentIds;
    }

    /**
     * 获取子部门id列表
     *
     * @param accessToken
     * @return
     */
    public List<String> getChildDepartmentIds(String accessToken, String departmentId) {
        String urlStr = "https://open.feishu.cn/open-apis/contact/v1/department/simple/list?page_size=100&fetch_child=true&department_id=" + departmentId;
        String result = HttpUtil.feishuGet(urlStr, accessToken);
        JSONObject dataObj = JSON.parseObject(result);
        List childDepartmentIds = new ArrayList();
        List departmentInfos = JSONArray.parseArray(dataObj.getJSONObject("data").getString("department_infos"), String.class);
        for (int i = 0; i <= departmentInfos.size() - 1; i++) {
            childDepartmentIds.add(JSON.parseObject(departmentInfos.get(i).toString()).getString("id"));
        }
        return childDepartmentIds;
    }

    /**
     * 批量获取部门详情
     *
     * @param accessToken
     * @return
     */
    public List<DepartmentInfosBo> getDepartmentDetails(String accessToken, String departmentIds) {
        String urlStr = "https://open.feishu.cn/open-apis/contact/v1/department/detail/batch_get?" + departmentIds;
        String result = HttpUtil.feishuGet(urlStr, accessToken);
        JSONObject dataObj = JSON.parseObject(result);
        List<DepartmentInfosBo> departmentInfos = JSONArray.parseArray(dataObj.getJSONObject("data").getString("department_infos"), DepartmentInfosBo.class);
        return departmentInfos;
    }

    /**
     * 获取部门用户详情
     *
     * @param accessToken
     * @return
     */
    public List<DepartmentStaffBo> getDepartmentStaffDetails(String accessToken, String departmentId) {
        String urlStr = "https://open.feishu.cn/open-apis/contact/v1/department/user/detail/list?page_size=100&fetch_child=true&department_id=" + departmentId;
        String result = HttpUtil.feishuGet(urlStr, accessToken);
        JSONObject dataObj = JSON.parseObject(result);
        List<DepartmentStaffBo> departmentStaffs = JSONArray.parseArray(dataObj.getJSONObject("data").getString("user_infos"), DepartmentStaffBo.class);
        return departmentStaffs;
    }


    /**
     * 获取图片image_key
     *
     * @return
     * @throws IOException
     */
    public String getImageKey(File file, String tenant_access_token) throws IOException {
//        File file = new File(imgUrl);
        String result = SendImageByApacheHttpClient(file, tenant_access_token);
        JSONObject dataObj = JSON.parseObject(result);
        String image_key = dataObj.getJSONObject("data").getString("image_key");
        return image_key;
    }

    /**
     * 获取飞书用户唯一标识
     *
     * @param mobile
     * @param accessToken
     * @return
     */
    public static String getUserId(String mobile, String accessToken) {
        String urlStr = "https://open.feishu.cn/open-apis/user/v1/batch_get_id?mobiles=" + mobile;
        String result = HttpUtil.feishuGet(urlStr, accessToken);
        JSONObject dataObj = JSON.parseObject(result);
        String userId = dataObj.getJSONObject("data").getJSONObject("mobile_users").getJSONArray(mobile).getJSONObject(0).getString("user_id");
        return userId;
    }

    /**
     * 1、获取tenant_access_token；
     * 2、获取图片image_key;
     * 3、发送富文本信息
     * "chat_id":"oc_0ef00f576a5a9d29e267112e8c82b4ab"
     */
    public static void main(String[] args) throws IOException {
        //1、获取tenant_access_token；
        String tenant_access_token = getAccessToken();
        System.out.println(tenant_access_token);

        String mobile = "18758158620";
        String userId = getUserId(mobile, tenant_access_token);
        System.out.println(userId);

//        //2、获取图片image_key;
//        String imgUrl = "/Users/fumeiai/tmp/IMG_001.jpg";
//        String image_key = getImageKey(imgUrl, tenant_access_token);
//        System.out.println(image_key);

//        //3、发送文本消息
//        String chatId = "oc_0ef00f576a5a9d29e267112e8c82b4ab";
//        String content = "**那就这个当标题吧**\n *new line1* \n new line2";
//        sendMessage(chatId, content, tenant_access_token);
//        String chatId, String title, String content, String accessToken, List<String> userIds, String hrefUrl, String imgKey
        //4、发送富文本消息
//        String chatId = "oc_0ef00f576a5a9d29e267112e8c82b4ab";
//        String title = "代码实现噜";
//        String content = "看样式能否拆开\n *换行行不行* \n 如果不行就这样啦";
//        sendRichText(chatId,title, content, tenant_access_token, Lists.newArrayList(),"http://www.feishu.cn",image_key);
    }


}
