package com.ruoyi.excel.wecom.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.excel.wecom.domain.CorpDepartment;
import com.ruoyi.excel.wecom.domain.CorpUser;
import com.ruoyi.excel.wecom.model.WecomConfig;
import com.ruoyi.excel.wecom.model.WecomCustomer;
import com.ruoyi.excel.wecom.model.WecomTagGroup;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 企业微信客户联系服务类
 */
@Component
public class WecomContactService extends WecomBaseService {

    public WecomContactService(WecomConfig wecomConfig) {
        super(wecomConfig);
    }

    /**
     * 获取配置了客户联系功能的成员列表
     *
     * @return 成员ID列表
     * @throws IOException IO异常
     */
    public List<String> getFollowUserList() throws IOException {
        String accessToken = getAccessToken();
        String url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_follow_user_list?access_token=" + accessToken;
        String response = doGet(url);
        JSONObject jsonObject = JSON.parseObject(response);

        if (jsonObject.getInteger("errcode") == 0) {
            return jsonObject.getJSONArray("follow_user").toJavaList(String.class);
        } else {
            throw new RuntimeException("获取配置了客户联系功能的成员列表失败: " + jsonObject.getString("errmsg"));
        }
    }

    /**
     * 获取指定成员的客户列表
     *
     * @param userid 成员ID
     * @return 客户外部联系人ID列表
     * @throws IOException IO异常
     */
    public List<String> getExternalContactList(String userid) throws IOException {
        String accessToken = getAccessToken();
        String url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/list?access_token=" + accessToken + "&userid=" + userid;
        String response = doGet(url);
        JSONObject jsonObject = JSON.parseObject(response);

        if (jsonObject.getInteger("errcode") == 0) {
            return jsonObject.getJSONArray("external_userid").toJavaList(String.class);
        } else {
            throw new RuntimeException("获取成员客户列表失败: " + jsonObject.getString("errmsg"));
        }
    }

    /**
     * 获取所有成员的客户列表
     *
     * @return 成员客户映射关系
     * @throws IOException IO异常
     */
    public List<MemberCustomer> getAllMembersCustomers() throws IOException {
        List<String> userList = getFollowUserList();
        List<MemberCustomer> result = new ArrayList<>();

        for (String userid : userList) {
            List<String> customerList = getExternalContactList(userid);
            MemberCustomer memberCustomer = new MemberCustomer();
            memberCustomer.setUserid(userid);
            memberCustomer.setExternalUserids(customerList);
            result.add(memberCustomer);
        }

        return result;
    }

    /**
     * 批量获取客户详情
     *
     * @param useridList 成员ID列表，最多100个
     * @param cursor     分页游标，首次调用传空
     * @param limit      分页大小，默认100
     * @return 客户详情列表
     * @throws IOException IO异常
     */
    public String batchGetCustomerDetails(List<String> useridList,List<WecomCustomer> finalResult, String cursor, Integer limit) throws IOException {
        if (useridList.size() > 100) {
            throw new IllegalArgumentException("成员ID列表不能超过100个");
        }
        System.out.println("获取用户数据****" + cursor);

        String accessToken = getAccessToken();
        String url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/batch/get_by_user?access_token=" + accessToken;

        JSONObject requestBody = new JSONObject();
        requestBody.put("userid_list", useridList);
        if (cursor != null) {
            requestBody.put("cursor", cursor);
        }
        if (limit != null) {
            requestBody.put("limit", limit);
        }

        String response = doPost(url, requestBody.toJSONString());
        JSONObject jsonObject = JSON.parseObject(response);

        if (jsonObject.getInteger("errcode") == 0) {
            List<WecomCustomer> customerList = new ArrayList<>();
            if (jsonObject.containsKey("external_contact_list")) {
                customerList = jsonObject.getJSONArray("external_contact_list").toJavaList(WecomCustomer.class);

                finalResult.addAll(customerList);
            }

            String nextCursor = null;
            if (finalResult.size() >= 2000) {
                if (jsonObject.containsKey("next_cursor") && StringUtils.isNotEmpty(jsonObject.getString("next_cursor"))) {
                    nextCursor = jsonObject.getString("next_cursor");
                    return nextCursor;
                } else {
                    return null;
                }
            } else if (jsonObject.containsKey("next_cursor") && StringUtils.isNotEmpty(jsonObject.getString("next_cursor"))) {
                nextCursor = jsonObject.getString("next_cursor");
                return batchGetCustomerDetails(useridList, finalResult, nextCursor, limit);
            } else {
                return null;
            }

          /*  // 处理分页
            if (jsonObject.containsKey("next_cursor") && StringUtils.isNotEmpty(jsonObject.getString("next_cursor"))) {
                String nextCursor = jsonObject.getString("next_cursor");
                //如果发现数量已经存储了2000条则先退出 由外部存储
                if (finalResult.size() >= 2000) {
                    return nextCursor;
                } else {
                    return batchGetCustomerDetails(useridList, finalResult, nextCursor, limit);
                }
            } else {
                return null;
            }*/
        } else {
            throw new RuntimeException("批量获取客户详情失败: " + jsonObject.getString("errmsg"));
        }
    }

    /**
     * 批量获取所有客户详情
     *
     * @param useridList 成员ID列表
     * @return 客户详情列表
     * @throws IOException IO异常
     */
    public List<WecomCustomer> batchGetAllCustomerDetails(List<String> useridList) throws IOException {
        List<WecomCustomer> allCustomers = new ArrayList<>();

        // 分批处理，每次最多100个用户
        for (int i = 0; i < useridList.size(); i += 100) {
            int endIndex = Math.min(i + 100, useridList.size());
            List<String> batchUserids = useridList.subList(i, endIndex);
            batchGetCustomerDetails(batchUserids, allCustomers,null, 100);
        }

        return allCustomers;
    }

    /**
     * 获取单个客户详情
     *
     * @param externalUserid 外部联系人ID
     * @return 客户详情
     * @throws IOException IO异常
     */
    public WecomCustomer getCustomerDetail(String externalUserid) throws IOException {
        String accessToken = getAccessToken();
        String url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get?access_token=" + accessToken + "&external_userid=" + externalUserid;
        String response = doGet(url);
        JSONObject jsonObject = JSON.parseObject(response);

        if (jsonObject.getInteger("errcode") == 0) {
            WecomCustomer customer = new WecomCustomer();
            customer.setExternalContact(jsonObject.getObject("external_contact", WecomCustomer.ExternalContact.class));
            if (jsonObject.containsKey("follow_info")) {
                customer.setFollowInfo(jsonObject.getObject("follow_info", WecomCustomer.FollowInfo.class));
            }
            return customer;
        } else {
            throw new RuntimeException("获取客户详情失败: " + jsonObject.getString("errmsg"));
        }
    }

    /**
     * 获取企业标签库
     *
     * @return 标签库列表
     * @throws IOException IO异常
     */
    public List<WecomTagGroup> getCorpTagList() throws IOException {
        String accessToken = getAccessToken();
        String url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_corp_tag_list?access_token=" + accessToken;
        String response = doGet(url);
        JSONObject jsonObject = JSON.parseObject(response);

        if (jsonObject.getInteger("errcode") == 0) {
            List<WecomTagGroup> tagGroupList = new ArrayList<>();
            if (jsonObject.containsKey("tag_group")) {
                tagGroupList = jsonObject.getJSONArray("tag_group").toJavaList(WecomTagGroup.class);
            }
            return tagGroupList;
        } else {
            throw new RuntimeException("获取企业标签库失败: " + jsonObject.getString("errmsg"));
        }
    }

    /**
     * 成员客户映射类
     */
    public static class MemberCustomer {
        private String userid;
        private List<String> externalUserids;

        public String getUserid() {
            return userid;
        }

        public void setUserid(String userid) {
            this.userid = userid;
        }

        public List<String> getExternalUserids() {
            return externalUserids;
        }

        public void setExternalUserids(List<String> externalUserids) {
            this.externalUserids = externalUserids;
        }
    }


    /**
     * 获取子部门id列表
     *
     * @param departmentId 部门ID，根部门传1
     * @return 子部门ID列表
     * @throws IOException IO异常
     */
    public List<CorpDepartment> getDepartmentList(Long departmentId) throws IOException {
        String accessToken = getAccessToken();
        String url = "https://qyapi.weixin.qq.com/cgi-bin/department/simplelist?access_token=" + accessToken;
        if (departmentId != null) {
            url += "&id=" + departmentId;
        }
        String response = doGet(url);
        JSONObject jsonObject = JSON.parseObject(response);

        if (jsonObject.getInteger("errcode") == 0) {
            List<CorpDepartment> departmentIds = new ArrayList<>();
            if (jsonObject.containsKey("department_id")) {
                departmentIds = jsonObject.getJSONArray("department_id").toJavaList(CorpDepartment.class);
            }
            return departmentIds;
        } else {
            throw new RuntimeException("获取子部门id列表失败: " + jsonObject.getString("errmsg"));
        }
    }

    /**
     * 获取单个部门详情
     *
     * @param departmentId 部门ID
     * @return 部门详情
     * @throws IOException IO异常
     */
    public String getDepartmentDetail(Long departmentId) throws IOException {
        String accessToken = getAccessToken();
        String url = "https://qyapi.weixin.qq.com/cgi-bin/department/get?access_token=" + accessToken + "&id=" + departmentId;
        String response = doGet(url);
        JSONObject jsonObject = JSON.parseObject(response);

        if (jsonObject.getInteger("errcode") == 0) {
            if (jsonObject.containsKey("department")) {
                JSONObject departInfo = jsonObject.getJSONObject("department");
                if(departInfo.containsKey("name")) {
                    return departInfo.get("name").toString();
                }
            }
            throw new RuntimeException("获取部门详情失败: " + jsonObject.getString("errmsg"));
        } else {
            throw new RuntimeException("获取部门详情失败: " + jsonObject.getString("errmsg"));
        }
    }

    /**
     * 获取部门成员详情
     *
     * @param departmentId 部门ID
     * @param fetchChild 是否递归获取子部门成员
     * @param status 成员状态，0-全部，1-已激活，2-已禁用，4-未激活，5-退出企业
     * @return 部门成员详情列表
     * @throws IOException IO异常
     */
    public List<CorpUser> getDepartmentMemberList(Long departmentId, Integer fetchChild, Integer status) throws IOException {
        String accessToken = getAccessToken();
        String url = "https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?access_token=" + accessToken + "&department_id=" + departmentId;
        if (fetchChild != null) {
            url += "&fetch_child=" + fetchChild;
        }
        if (status != null) {
            url += "&status=" + status;
        }
        String response = doGet(url);
        JSONObject jsonObject = JSON.parseObject(response);

        if (jsonObject.getInteger("errcode") == 0) {
            List<CorpUser> memberList = new ArrayList<>();
            if (jsonObject.containsKey("userlist")) {
                List<JSONObject> userList = jsonObject.getJSONArray("userlist").toJavaList(JSONObject.class);
                for (JSONObject user : userList) {
                    CorpUser member = new CorpUser();
                    member.setUserid(user.getString("userid"));
                    member.setName(user.getString("name"));
                    if (user.containsKey("department")) {
                        member.setDepartmentIds(user.getJSONArray("department").toJSONString());
                    }
                    if (user.containsKey("open_userid")) {
                        member.setOpenUserid(user.getString("open_userid"));
                    }
                    memberList.add(member);
                }
            }
            return memberList;
        } else {
            throw new RuntimeException("获取部门成员详情失败: " + jsonObject.getString("errmsg"));
        }
    }

    /**
     * 获取联系客户统计数据
     *
     * @param startTime 开始时间戳（秒）
     * @param endTime 结束时间戳（秒）
     * @param useridList 成员ID列表
     * @return 统计数据
     * @throws IOException IO异常
     */
    public JSONObject getUserBehaviorData(Long startTime, Long endTime, List<String> useridList) throws IOException {
        String accessToken = getAccessToken();
        String url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_user_behavior_data?access_token=" + accessToken;

        JSONObject requestBody = new JSONObject();
        requestBody.put("start_time", startTime);
        requestBody.put("end_time", endTime);
        if (useridList != null && !useridList.isEmpty()) {
            requestBody.put("userid_list", useridList);
        }

        String response = doPost(url, requestBody.toJSONString());
        JSONObject jsonObject = JSON.parseObject(response);

        if (jsonObject.getInteger("errcode") == 0) {
            return jsonObject;
        } else {
            throw new RuntimeException("获取联系客户统计数据失败: " + jsonObject.getString("errmsg"));
        }
    }

    /**
     * 获取某一天的联系客户统计数据
     *
     * @param date 日期（格式：yyyy-MM-dd）
     * @param useridList 成员ID列表
     * @return 统计数据
     * @throws IOException IO异常
     */
    public JSONObject getDayUserBehaviorData(String date, List<String> useridList) throws IOException {
        try {
            // 解析日期字符串为Date对象
            java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
            Date targetDate = sdf.parse(date);
            
            // 计算当天的开始时间戳（00:00:00）
            java.util.Calendar calendar = java.util.Calendar.getInstance();
            calendar.setTime(targetDate);
            calendar.set(java.util.Calendar.HOUR_OF_DAY, 0);
            calendar.set(java.util.Calendar.MINUTE, 0);
            calendar.set(java.util.Calendar.SECOND, 0);
            Long startTime = calendar.getTimeInMillis() / 1000;
            
            // 计算当天的结束时间戳（23:59:59）
            calendar.set(java.util.Calendar.HOUR_OF_DAY, 23);
            calendar.set(java.util.Calendar.MINUTE, 59);
            calendar.set(java.util.Calendar.SECOND, 59);
            Long endTime = calendar.getTimeInMillis() / 1000;
            
            // 调用获取统计数据的方法
            return getUserBehaviorData(startTime, endTime, useridList);
        } catch (java.text.ParseException e) {
            throw new RuntimeException("日期格式错误，请使用yyyy-MM-dd格式", e);
        }
    }
}