package com.sys.bus.sys.wx;

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;

public class WxUtil {

    public final static String token_url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ID&corpsecret=SECRET";
    public final static String dept_url ="https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=ACCESS_TOKEN";
    public final static String person_url ="https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?access_token=ACCESS_TOKEN&department_id=DEPARTMENT_ID";
    public final static String msg_url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=ACCESS_TOKEN";
    static Log log = LogFactory.getLog(WxUtil.class);

    public static String token ="";
    public static LocalDateTime tokenTime = null;


    //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 corpid,String secret){
        if(StringUtils.isBlank(corpid) || StringUtils.isBlank(secret)){
            log.error("获取token异常corpid 或secret 为空");
            return null;
        }
        corpid = corpid.trim();
        secret = secret.trim();
        LocalDateTime currTime = LocalDateTime.now();
        if(tokenTime!=null && tokenTime.isAfter(currTime)){
            return token;
        }
        String url = token_url.replace("ID",corpid).replace("SECRET",secret);
        try {
            HttpResponse httpResponse = HttpRequest.get(url).execute();
            int status = httpResponse.getStatus();
            String result = httpResponse.body();
            if(status != 200){
                log.error("获取token异常url："+url+",status:"+status+",result："+result);
                return null;
            }
            JSONObject jsonObject = JSONObject.parseObject(result);
            Integer errcode = jsonObject.getInteger("errcode");
            if(errcode != 0){
                log.error("获取token异常1url："+url+",status:"+status+",result："+result);
                return null;
            }
            int expires_in = jsonObject.getInteger("expires_in");
            tokenTime = LocalDateTime.now().plusSeconds(expires_in - 60);
            token =  jsonObject.getString("access_token");
            log.info("成功获取token:"+token);
            return token;

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

        return null;
    }
    public static Integer getDeptId(String token){
        String deptUrl = dept_url.replace("ACCESS_TOKEN",token);
        HttpResponse httpResponse = HttpRequest.get(deptUrl).execute();
        int status = httpResponse.getStatus();
        String result = httpResponse.body();
        if(status != 200){
            log.error("获取部门信息异常,status:"+status);
            return null;
        }
        JSONObject jsonObject = JSONObject.parseObject(result);
        Integer errcode = jsonObject.getInteger("errcode");
        if(errcode != 0){
            log.error("获取部门信息异常,errcode:"+errcode);
            return null;
        }
        JSONArray department = jsonObject.getJSONArray("department");
        if(department == null || department.size()==0){
            log.error("获取部门信息异常,department:"+department);
            return null;
        }
        String  obj = department.get(0).toString();
        JSONObject dept = JSONObject.parseObject(obj);
        return dept.getInteger("id");

    }
    public static JSONArray getPerson(int deptId,String token){
        String personUrl = person_url.replace("ACCESS_TOKEN",token).replace("DEPARTMENT_ID",""+deptId).replace("FETCH_CHILD","1");
        HttpResponse httpResponse = HttpRequest.get(personUrl).execute();
        int status = httpResponse.getStatus();
        String result = httpResponse.body();
        if(status != 200){
            log.error("获取员工信息异常,status:"+status);
            return null;
        }
        JSONObject jsonObject = JSONObject.parseObject(result);
        Integer errcode = jsonObject.getInteger("errcode");
        if(errcode != 0){
            log.error("获取员工信息异常,errcode:"+errcode);
            return null;
        }
        JSONArray userlist = jsonObject.getJSONArray("userlist");
        if(userlist == null || userlist.size()==0){
            log.error("获取员工信息异常,userlist:"+userlist);
            return null;
        }
       return userlist;
    }

    public static boolean sendMsg(String userId,String msg,String token,int agentId,Integer checkMinute){
        String msgUrl = msg_url.replace("ACCESS_TOKEN",token);

        JSONObject jo = new JSONObject();
        jo.put("touser",userId);
        jo.put("toparty","");
        jo.put("totag","");
        jo.put("msgtype","text");
        jo.put("agentid",agentId);
        jo.put("safe",0);
        jo.put("enable_id_trans",0);
        if(checkMinute != null && checkMinute>0){
            jo.put("enable_duplicate_check",1);//是否检查重复消息   0表示否，1表示是
        }else{
            jo.put("enable_duplicate_check",0);
        }
        jo.put("duplicate_check_interval",60*checkMinute-10);//重复消息秒

        JSONObject text = new JSONObject();
        text.put("content",msg);
        jo.put("text",text);

        HttpRequest post = HttpRequest.post(msgUrl);
        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 errcode = jsonObject.getInteger("errcode");
        if(errcode != 0){
            log.error("发送微信信息异常,errcode:"+errcode+"userId："+userId+"，msg："+msg);
            return false;
        }
        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));
//    }
}