package com.jd.lightapplication.task;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jd.lightapplication.easemob.EasemobComtroller;
import com.jd.lightapplication.easemob.dto.QueryPageDto;
import com.jd.lightapplication.model.SysUser;
import com.jd.lightapplication.service.SysUserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 定时任务
 */
@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
@AllArgsConstructor
@Slf4j
public class ScheduledTask {

    private EasemobComtroller easemobComtroller;
    private SysUserService sysUserService;

    /**
     * 定时任务
     * 作用：
     * 因为没有充钱，环信只给了我们100个用户和100个群组
     * 所以我们需要每天定时清理环信里面的用户和群组
     */
    //@Scheduled(cron = "0 0/1 * * * ? ")// TODO: 2022/4/29 定时任务逻辑已经写完并且测试完成。cron表达式还没确定
    public void clearGroupAndUser() {
        System.err.println("清理群组和用户begin");
        //清理环信群聊
        this.clearGroup();
        //清理环信用户和本系统的用户
        this.clearUser();
        System.err.println("清理群组和用户end");
    }

    /**
     * 清理群组
     */
    private void clearGroup() {
        //先查询出环信应用内的所有群组
        JSONObject result = (JSONObject) easemobComtroller.queryGroupPage(new QueryPageDto().setLimit("100")).getData();
        JSONArray data = null;
        try {
            data = result.getJSONArray("data");
            //再根据返回的群组信息去查询群组详情
            result = (JSONObject) easemobComtroller.queryGroupDetails(data.stream().map(t -> {
                JSONObject group = (JSONObject) t;
                return group.getStr("groupid");
            }).collect(Collectors.joining(","))).getData();
            data = result.getJSONArray("data");
        } catch (Exception e) {
            log.error("获取环信群组数据失败。result:" + result);
            e.printStackTrace();
        }
        //过滤掉私有群组，把群组id用join连接成字符串
        List<String> groupIds = data.stream().filter(t -> {
            JSONObject group = (JSONObject) t;
            return "true".equals(group.getStr("public"));
        }).map(t -> {
            JSONObject group = (JSONObject) t;
            return group.getStr("id");
        }).collect(Collectors.toList());
        //再循环删除公开的群
        groupIds.forEach(t -> {
            JSONObject deleteResult = (JSONObject) easemobComtroller.deleteGroup(t).getData();
            System.err.println(deleteResult);
        });
    }

    /**
     * 清理用户
     */
    private void clearUser() {
        //先查询出本系统中所有角色为来宾的用户
        List<SysUser> sysUserList = sysUserService.queryGuestUserAll();
        //再根据手机号去删除环信中的用户，备注：环信中用户的账号就是本系统中的手机号，直接根据手机号去删即可
        sysUserList.forEach(t -> {
            JSONObject result = (JSONObject) easemobComtroller.deleteUser(t.getPhone()).getData();
            //拿到被删除掉的用户信息
            Object entities = result.get("entities");
            if (entities == null) {
                return;
            }
            JSONObject entitiesModel = ((JSONArray) entities).getJSONObject(0);
            //拿到手机号，再根据手机号去删除本系统用户
            String phone = entitiesModel.getStr("username");
            LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SysUser::getPhone, phone);
            sysUserService.remove(wrapper);
        });

    }
}
