package org.springblade.common.notify.dingding.handler;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

//同步钉钉数据
@Slf4j
@Component
public class DingDingUserSyncHandler {

    private static final String GET_DEPT_LIST_URL = "https://oapi.dingtalk.com/department/list?access_token=%s&id=%s";

    private static final String GET_USER_LIST_URL = "https://oapi.dingtalk.com/user/list?access_token=%s&department_id=%s";

    //private static final String GET_SIMPLE_USER_LIST_URL = "https://oapi.dingtalk.com/user/simplelist?access_token=%s&department_id=%s";

    //总部:48637010   省公司:49984156  技术部:48638008   运营部:49884207
    @Value("${msg.notify.dingding.rootDeptIds:48637010,49984156}")
    private String rootDeptIds = "48637010,49984156";  //根部门编号列表, 总部:48637010 省公司:49984156

    public Map<String, String> doSyncData(String accessToken) throws Exception {
        DateFormat df = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
        log.info("DingDingUserSyncHandler start doing sync data. currentTime is: {}, rootDeptIds is: {}",
                df.format(new Date()), rootDeptIds);
        Map<String, String> mapping = new HashMap<>();
        List<String> deptList = queryAllDeptIds(accessToken);
        for (String deptId : deptList) {
            Map<String, String> subMapping = getUserMappingInfo(accessToken, deptId);
            mapping.putAll(subMapping);
        }
        log.info("DingDingUserSyncHandler finish doing sync data. currentTime is: {}, fetch size is: ",
                df.format(new Date()), mapping.size());
        return mapping;
    }

    public List<String> queryAllDeptIds(String accessToken) throws Exception {
        List<String> list = new ArrayList<>();
        for (String rootDeptId : rootDeptIds.split(",")) {
            list.add(rootDeptId);
            list.addAll(querySubDeptIds(accessToken, rootDeptId));
        }
        return list;
    }

    private List<String> querySubDeptIds(String accessToken, String deptId) throws Exception {
        List<String> list = new ArrayList<>();
        String url = String.format(GET_DEPT_LIST_URL, accessToken, deptId);
        HttpClient httpclient = HttpClients.createDefault();
        HttpGet httpget = new HttpGet(url);
        HttpResponse response = httpclient.execute(httpget);
        log.info("调用钉钉接口的入参：{}", url);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String result = EntityUtils.toString(response.getEntity(), "utf-8");
            log.info("钉钉接口返回参数为：{}", result);
            JSONObject obj = JSONObject.parseObject(result);
            JSONArray array = (JSONArray) obj.get("department");
            List<JSONObject> deptLists = array.toJavaList(JSONObject.class);
            for (JSONObject single : deptLists) {
                //System.out.println(single.get("id") + " " + single.get("name"));
                list.add(String.valueOf(single.getString("id")));
            }
        }
        return list;
    }

    //获取部门下面的员工手机和钉钉ID对应关系
    public Map<String, String> getUserMappingInfo(String accessToken, String deptId) throws Exception {
        Map<String, String> mapping = new HashMap<>();
        String url = String.format(GET_USER_LIST_URL, accessToken, deptId);

        HttpClient httpclient = HttpClients.createDefault();
        HttpGet httpget = new HttpGet(url);
        HttpResponse response = httpclient.execute(httpget);
        log.info("调用钉钉接口的入参：{}", url);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String result = EntityUtils.toString(response.getEntity(), "utf-8");
            log.info("钉钉接口返回参数为：{}", result);
            JSONObject obj = JSONObject.parseObject(result);
            JSONArray array = (JSONArray) obj.get("userlist");
            List<JSONObject> list = array.toJavaList(JSONObject.class);
            for (JSONObject single : list) {
                mapping.put(single.getString("name"), single.getString("userid"));
            }
        }
        return mapping;
    }
}
