package cn.iocoder.yudao.module.system.job;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.iocoder.yudao.framework.quartz.core.handler.JobHandler;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import cn.iocoder.yudao.framework.tenant.core.job.TenantJob;
import cn.iocoder.yudao.module.system.dal.dataobject.tenant.TenantDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.dal.mysql.tenant.TenantMapper;
import cn.iocoder.yudao.module.system.dal.mysql.user.AdminUserMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;/*
 * @author: ziin
 * @date: 2025/12/11 20:55
 */
@Slf4j
@Component
public class DisableWebAIExpiredAccount implements JobHandler{

    /**
 * 租户数据访问对象
 * 用于查询租户信息和过期时间
 */
    @Resource
    TenantMapper tenantMapper;

    /**
     * 管理员用户数据访问对象
     * 用于查询和更新用户权限状态
     */
    @Resource
    private AdminUserMapper userMapper;


    @Override
    @TenantJob
    public String execute(String param) throws Exception {
        Long tenantId = TenantContextHolder.getTenantId();
        TenantDO tenant = tenantMapper.selectById(tenantId);
        if (tenant.getAiExpireTime()!=null) {
            Duration brotherDuration = LocalDateTimeUtil.between(tenant.getAiExpireTime(), LocalDateTime.now());
            long minutes = brotherDuration.toMinutes();
            LambdaQueryWrapper<AdminUserDO> aiUserQueryWrapper = new LambdaQueryWrapper<>();
            aiUserQueryWrapper.eq(AdminUserDO::getTenantId, tenantId);
            aiUserQueryWrapper.eq(AdminUserDO::getWebAi, 1);
            List<AdminUserDO> aiUserList = userMapper.selectList(aiUserQueryWrapper);
            int aiAccountNum = 0 ;
            if (minutes >= 0) {
                for (AdminUserDO adminUserDO : aiUserList) {
                    adminUserDO.setWebAi((byte) 0);
                    userMapper.updateById(adminUserDO);
                    aiAccountNum++;
                    log.info("禁用过期WebAI账号，账号ID：{}", adminUserDO.getId());
                }
            }
            // 返回操作结果：包含禁用的AI账号和大哥账号数量统计
            return "禁用过期账号成功，禁用了 " + aiAccountNum + " 个 WebAI 账号。";
        }
        return "租户未配置过期时间";
    }
}

