package com.lz.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.*;
import com.dingtalk.api.response.*;
import com.lz.modules.job.model.responseBo.DepartmentInfosBo;
import com.lz.modules.job.model.responseBo.DepartmentStaffBo;
import com.lz.modules.third.entity.ThirdAppConfig;
import com.lz.modules.third.service.ThirdAppConfigService;
import com.lz.modules.third.service.impl.ThirdAppConfigServiceImpl;
import com.taobao.api.ApiException;
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("dingtalkRobotUtil")
public class DingTalkUtil {
    protected static Logger logger = LoggerFactory.getLogger(DingTalkUtil.class);

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    ThirdAppConfigService thirdAppConfigService;



    CloseableHttpClient getHttpClient(){
        return null;
    }



    /**
     * 获取机器人的有效token值
     *
     * @return
     * @throws IOException
     */
    public String getAccessToken(String appid) {
        try {

            ThirdAppConfig thirdAppConfig = thirdAppConfigService.getByAppId(appid);
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
            OapiGettokenRequest req = new OapiGettokenRequest();
            req.setAppkey(thirdAppConfig.getAppKey());
            req.setAppsecret(thirdAppConfig.getAppSecret());
            req.setHttpMethod("GET");
            OapiGettokenResponse rsp = client.execute(req);
            String resultStr = rsp.getBody();
            JSONObject dataObj = JSON.parseObject(resultStr);
            String tenant_access_token = dataObj.getString("access_token");
            return tenant_access_token;
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return null;
    }



    /**
     * 批量获取部门详情
     *
     * @param accessToken
     * @return
     */
    public List<DepartmentInfosBo> getDepartmentDetails(String accessToken, String departmentIds) {
        try {
            //下面获取所有部门的i就按单信息
            List<DepartmentInfosBo> list = new ArrayList<>();
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/department/list");
            OapiDepartmentListRequest req = new OapiDepartmentListRequest();
            req.setFetchChild(true);
            req.setId("1");
            req.setHttpMethod("GET");
            OapiDepartmentListResponse rsp = client.execute(req, accessToken);
            JSONObject json = JSONObject.parseObject(rsp.getBody());
            if(json.getInteger("errcode") == 0){
                JSONArray array = json.getJSONArray("department");
                for (int i = 0; i < array.size(); i++){
                    json = array.getJSONObject(i);
                    DepartmentInfosBo departmentInfosBo = new DepartmentInfosBo();
                    departmentInfosBo.setName(json.getString("name"));
                    departmentInfosBo.setId(json.getString("id"));//自身ID
                    departmentInfosBo.setParentId(json.getString("parentid"));//父级ID

                    //下面获取详细信息
                    client = new DefaultDingTalkClient("https://oapi.dingtalk.com/department/get");
                    OapiDepartmentGetRequest deReq = new OapiDepartmentGetRequest();
                    deReq.setId(departmentInfosBo.getId());
                    deReq.setHttpMethod("GET");
                    OapiDepartmentGetResponse deRsp = client.execute(deReq, accessToken);
                    json = JSONObject.parseObject(deRsp.getBody());
                    departmentInfosBo.setChatId(json.getString("deptGroupChatId"));
                    departmentInfosBo.setLeaderEmployeeId(json.getString("deptManagerUseridList"));//部门主管,多个主管以|隔开
                    departmentInfosBo.setStatus(1);
                    departmentInfosBo.setOrder(json.getInteger("order"));

                    list.add(departmentInfosBo);
                }
            }else{
                logger.info("获取部门详情异常{}", rsp.getBody());
            }
            return list;
        } catch (ApiException e) {
            logger.info("获取部门详情异常{}", e);
        }
        return null;
    }

    /**
     * 获取部门用户详情
     *
     * @param accessToken
     * @return
     */
    public List<DepartmentStaffBo> getDepartmentStaffDetails(String accessToken, String departmentId) {
        try {
            List<DepartmentStaffBo> list =new ArrayList<>();
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/listbypage");

            OapiUserListbypageRequest req = new OapiUserListbypageRequest();
            req.setDepartmentId(Long.parseLong(departmentId));

            req.setSize(100L);
            req.setHttpMethod("GET");

            boolean isNext = true;
            for(long page = 0; isNext; page++){
                req.setOffset(page);
                OapiUserListbypageResponse rsp = client.execute(req, accessToken);
                JSONObject json = JSONObject.parseObject(rsp.getBody());
                if(json.getInteger("errcode") == 0){
                    JSONArray array = json.getJSONArray("userlist");
                    isNext = json.getBoolean("hasMore");//获取是否由更多数据
                    for (int i = 0; i < array.size(); i++) {
                        json = array.getJSONObject(i);
                        DepartmentStaffBo departmentStaffBo = new DepartmentStaffBo();
                        departmentStaffBo.setEmployeeId(json.getString("userid"));//用户在企业内部的唯一编号，创建时可指定。可代表一定的含义
                        departmentStaffBo.setName(json.getString("name"));
                        departmentStaffBo.setEmployeeNo(json.getString("jobnumber"));//工号
                        departmentStaffBo.setUnionId(json.getString("unionid"));//企业内部id,唯一
                        departmentStaffBo.setOpenId(json.getString("openId"));//和上面的值目前是一样的，未找到说明
                        departmentStaffBo.setMobile(json.getString("mobile"));//手机，需要单独授权手机权限
                        departmentStaffBo.setEmail(json.getString("email"));//邮箱，钉钉的企业邮箱才可以，需要单独授权手机权限
                        departmentStaffBo.setAvatar(json.getString("avatar"));//头像
                        departmentStaffBo.setPosition(json.getString("position"));
                        if(json.getBoolean("active")){
                            //在职已激活
                            departmentStaffBo.setStatus(0);
                        }else{
                            //在职未激活
                            departmentStaffBo.setStatus(4);
                        }
                        if(json.getBoolean("isLeader")){
                            departmentStaffBo.setIsLeader(1);

                        }else{
                            departmentStaffBo.setIsLeader(0);
                        }
                        list.add(departmentStaffBo);
                    }


                }else{
                    logger.info("获取部门详情异常{}", rsp.getBody());
                }
            }

            return list;
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 获取图片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;
    }

    public static void main(String[] args) {

        DingTalkUtil dingTalkUtil = new DingTalkUtil();
        String token = dingTalkUtil.getAccessToken("855818566");
    }



}
