package com.sys.bus.sys.lark;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LarkUtil {

    public final static String token_url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal";
    public final static String dept_url ="https://open.feishu.cn/open-apis/contact/v3/departments/0/children?fetch_child=true&page_size=50";//page_token
    public final static String person_url ="https://open.feishu.cn/open-apis/contact/v3/users/find_by_department?page_size=50";//department_id
    public final static String msg_url = "https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=user_id";
    static Log log = LogFactory.getLog(LarkUtil.class);

    public static String token ="";
    public static LocalDateTime tokenTime = null;
    public static Map<String,LocalDateTime> userMsgTime = new HashMap<>(); //记录最后发送的时间，短时间不重复发送消息

    //url = "https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?access_token="+getToken1()+"&department_id="+deptId;
    // String url = "https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token="+getToken1();

    public static synchronized  String getToken(String appid,String secret){
        if(StringUtils.isBlank(appid) || StringUtils.isBlank(secret)){
            log.error("获取token异常appid 或secret 为空");
            return null;
        }
        appid = appid.trim();
        secret = secret.trim();
        LocalDateTime currTime = LocalDateTime.now();
        if(tokenTime!=null && tokenTime.isAfter(currTime)){
            return token;
        }
        try {
            JSONObject bodyObject = new JSONObject();
            bodyObject.put("app_id",appid);
            bodyObject.put("app_secret",secret);
            String body = bodyObject.toJSONString();
            HttpResponse httpResponse = HttpRequest.post(token_url).header("Content-Type","application/json; charset=utf-8")
                    .body(body).execute();
            int status = httpResponse.getStatus();
            String result = httpResponse.body();
            if(status != 200){
                log.error("获取飞书token异常url："+token_url+",status:"+status+",result："+result);
                return null;
            }
            JSONObject jsonObject = JSONObject.parseObject(result);
            Integer code = jsonObject.getInteger("code");
            if(code != 0){
                log.error("获取飞书token异常1url："+token_url+",status:"+status+",result："+result);
                return null;
            }
            int expire = jsonObject.getInteger("expire");
            tokenTime = LocalDateTime.now().plusSeconds(expire - 1800 -10); //30分内重新获取会刷新token
            token =  jsonObject.getString("tenant_access_token");
            log.info("成功获取飞书token:"+token);
            return token;

        }catch (Exception e){
            log.error("获取飞书token异常",e);
        }

        return null;
    }
    public static List<String> getDept(String token){
        List<String> ids = new ArrayList<>();
        ids.add("0"); // 根目录为0
        return getDept(token,null,ids);
    }
    public static List<String> getDept(String token,String page_token,List<String> ids){
        String deptUrl = dept_url;
        if(deptUrl.indexOf("&page_token")<0 && StringUtils.isNotBlank(page_token)){
            deptUrl += "&page_token="+page_token;
        }
        HttpResponse httpResponse = HttpRequest.get(deptUrl).header("Authorization","Bearer "+token).execute();
        int status = httpResponse.getStatus();
        String result = httpResponse.body();
        if(status != 200){
            log.error("获取飞书部门信息异常,status:"+status);
            return null;
        }
        JSONObject jsonObject = JSONObject.parseObject(result);
        Integer code = jsonObject.getInteger("code");
        if(code != 0){
            log.error("获取飞书部门信息异常,code:"+code);
            return null;
        }
        JSONArray department = jsonObject.getJSONObject("data").getJSONArray("items");
        if(department == null || department.size()==0){
            log.error("获取飞书部门信息异常:"+jsonObject.toJSONString());
            return null;
        }
        for(int i =0;i<department.size();i++){
            String id = department.getJSONObject(i).getString("open_department_id");
            ids.add(id);
        }
        if(jsonObject.getJSONObject("data").getBoolean("has_more")){//has_more
              return getDept(token,jsonObject.getJSONObject("data").getString("page_token"),ids);
        }
        return ids;

    }
    public static JSONArray getAllPerson(String token){
        List<String> ids = getDept(token);
        log.info("同步飞书部门id:"+ids.toString());
        JSONArray deptArray = new JSONArray();
        for(String id:ids){
            deptArray.addAll(getPerson(id,token));
        }
        return deptArray;
    }
    public static JSONArray getPerson(String deptId,String token){
        return getPerson(deptId,token,null,new JSONArray());
    }
    public static JSONArray getPerson(String deptId,String token,String page_token,JSONArray personArray){
        String personUrl = person_url+"&department_id="+deptId;
        if(personUrl.indexOf("&page_token")<0 && StringUtils.isNotBlank(page_token)){
            personUrl += "&page_token="+page_token;
        }
        HttpResponse httpResponse = HttpRequest.get(personUrl).header("Authorization","Bearer "+token).execute();
        int status = httpResponse.getStatus();
        String result = httpResponse.body();
        if(status != 200){
            log.error("获取飞书员工信息异常,status:"+status);
            return null;
        }
        JSONObject jsonObject = JSONObject.parseObject(result);
        Integer code = jsonObject.getInteger("code");
        if(code != 0){
            log.error("获取飞书员工信息异常,code:"+code);
            return null;
        }
        JSONArray userlist = jsonObject.getJSONObject("data").getJSONArray("items");
        if(userlist == null || userlist.size()==0){
            return personArray;
        }else{
            personArray.addAll(userlist);
        }
        if(jsonObject.getJSONObject("data").getBoolean("has_more")){//has_more
            return getPerson(deptId,token,jsonObject.getJSONObject("data").getString("page_token"),personArray);
        }
        List<String> list = new ArrayList<>();
        for(Object person:personArray){
            JSONObject jsonPerson = JSONObject.parseObject(person.toString());
            String userid = jsonPerson.getString("user_id");
            list.add(userid);
        }
       //log.info("飞书部门员工信息："+deptId+"："+list.toString());

       return personArray;
    }

    public static boolean sendMsg(String userId,String msg,String token,int duplicateCheckSecond){
        String msgUrl = msg_url;
//        {
//            "receive_id": "eaa99335",
//                "msg_type": "text",
//                "content": "{\"text\":\"测试内容\"}"
//        }
        JSONObject content = new JSONObject();
        content.put("text",msg);
        JSONObject jo = new JSONObject();
        jo.put("receive_id",userId);
        jo.put("msg_type","text");
        jo.put("content",content.toJSONString());
        String key = userId+msg;
        if(userMsgTime.containsKey(key)){
            LocalDateTime dateTime = userMsgTime.get(key);
            if(dateTime.plusSeconds(duplicateCheckSecond).isAfter(LocalDateTime.now())){
                log.error("重复飞书消息，本次不发送！消息内容："+msg);
                return true;
            }
        }
        HttpRequest post = HttpRequest.post(msgUrl).header("Content-Type","application/json; charset=utf-8").header("Authorization","Bearer "+token);
        post.body(jo.toJSONString());

        HttpResponse httpResponse = post.execute();
        int status = httpResponse.getStatus();
        String result = httpResponse.body();
        if(status != 200){
            log.error("发送飞书信息异常,status:"+status+"userId："+userId+"，msg："+msg);
            return false;
        }
        JSONObject jsonObject = JSONObject.parseObject(result);
        Integer code = jsonObject.getInteger("code");
        if(code != 0){
            log.error("发送飞书信息异常,code:"+code+"userId："+userId+"，msg："+msg);
            return false;
        }
        userMsgTime.put(key,LocalDateTime.now());
        return true;
    }
//    public static void main(String[]args){
//        String token = WxUtil.getToken("111","222");
//        JSONArray person = WxUtil.getPerson(WxUtil.getDeptId(token), token);
//        System.out.println(person.size());
//        System.out.println(person.get(0));
//    }
}