package com.tuoheng.task;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tuoheng.constant.CommonConstant;
import com.tuoheng.mapper.ClientUserMapper;
import com.tuoheng.mapper.ClientUserRoleMapper;
import com.tuoheng.mapper.TenantItemMapper;
import com.tuoheng.mapper.TenantMapper;
import com.tuoheng.model.entity.TenantItem;
import com.tuoheng.model.po.TenantPo;
import com.tuoheng.model.po.UserPo;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 定时监控系统到期时间并修改
 *
 * @Author xiaoying
 * @Date 2023/6/30 10:36
 */
@Component
@Slf4j
public class StatusTask {

    @Autowired
    private TenantItemMapper tenantItemMapper;
    @Autowired
    private TenantMapper tenantMapper;
    @Autowired
    private ClientUserMapper clientUserMapper;


    @XxlJob("statusTask")
    public void statusTask() {
        //获取所有租户对应系统的过期时间
        log.info("定时任务开始");
        List<TenantItem> tenantItems = tenantItemMapper.selectList(Wrappers.<TenantItem>lambdaQuery());
        for (TenantItem tenantItem : tenantItems) {
            //当前时间与项目结束时间进行对比
            DateTime date = DateUtil.date();
            //判断项目是否已过有效期
            boolean falg = date.after(tenantItem.getEndTime());
            if (falg) {
                //过了则更新租户对应项目状态
                TenantPo tenantPo = tenantMapper.selectById(tenantItem.getTenantId());
                tenantPo.setStatus(CommonConstant.ZERO);
                //变更租户状态
                tenantMapper.updateById(tenantPo);
                UserPo userPo = clientUserMapper.selectByUserId(tenantPo.getUserId());
                if (CommonConstant.ZERO.equals(userPo.getIsExpire())) {
                    log.info("开始禁用对应租户及其用户状态,对应租户id:{}", tenantItem.getTenantId());
                    userPo.setIsExpire(CommonConstant.ZERO);
                    //租户状态完毕
                    clientUserMapper.updatePass(userPo);
                    //租户更新完毕 更新对应租户下的用户
                    List<UserPo> userPoList = clientUserMapper.selectByTenantId(userPo.getId());
                    for (UserPo po : userPoList) {
                        po.setIsExpire(CommonConstant.ZERO);
                        clientUserMapper.updatePass(userPo);
                    }
                    log.info("禁用对应租户及其用户状态完毕");
                }
            }
        }
    }
}
