package com.testor.module.aptitude.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.testor.biz.sys.role.model.domain.SysRole;
import com.testor.biz.sys.role.service.SysRoleService;
import com.testor.biz.sys.user.model.domain.SysUser;
import com.testor.biz.sys.userRole.model.domain.SysUserRole;
import com.testor.biz.sys.userRole.service.SysUserRoleService;
import com.testor.module.aptitude.model.domain.TPersonAptitude;
import com.testor.module.aptitude.service.TPersonAptitudeService;
import com.testor.module.messageNotice.model.vo.MsgTemplateVO;
import com.testor.module.messageNotice.service.TMsgNoticeService;
import com.testor.module.sys.service.TSysUserService;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@ConditionalOnProperty(prefix = "service", name = "taskEnabled", havingValue = "true")
public class Remind {

    @Autowired
    private TPersonAptitudeService tPersonAptitudeService;

    @Autowired
    private TMsgNoticeService tMsgNoticeService;

    @Autowired
    private TSysUserService sysUserService;

    @Autowired
    private SysRoleService roleService;

    @Autowired
    private SysUserRoleService userRoleService;

    //@XxlJob("checkAndSendReminders")
    @Scheduled(cron = "0 0 1 * * *")
    public void checkAndSendReminders() {
        LocalDate today = LocalDate.now();

        // 提前两个月提醒(60天后到期)
        checkAndSendReminder(today.plusDays(60), "资质将在2个月后到期，及时更新证件信息，以免影响正常使用，谢谢");

        // 提前一个月提醒(30天后到期)
        checkAndSendReminder(today.plusDays(30), "资质将在1个月后到期，及时更新证件信息，以免影响正常使用，谢谢");

        // 提前一周提醒(7天后到期)
        checkAndSendReminder(today.plusDays(7), "资质将在1周后到期，及时更新证件信息，以免影响正常使用，谢谢");

        // 过期提醒
        checkExpired(today);
    }

    private void checkAndSendReminder(LocalDate expiryDate, String message) {
        String format = expiryDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

        // 使用MyBatis-Plus的LambdaQueryWrapper构建查询
        List<TPersonAptitude> aptitudes = tPersonAptitudeService.list(
                new LambdaQueryWrapper<TPersonAptitude>()
                        .eq(TPersonAptitude::getAptitudeValid,format)
        );

        aptitudes.forEach(aptitude -> {
            sendNotification(aptitude, message);
        });
    }

    private void checkExpired(LocalDate today) {
        List<TPersonAptitude> aptitudes = tPersonAptitudeService.list(
                new LambdaQueryWrapper<TPersonAptitude>()
                        .eq(TPersonAptitude::getAptitudeValid, today.atStartOfDay())
        );

        aptitudes.forEach(aptitude -> {
            sendNotification(aptitude, "已过期，及时更新证件信息，以免影响正常使用，谢谢");
        });
    }

    private void sendNotification(TPersonAptitude aptitude, String message) {
        String fullMessage = String.format("%s的%s资质: %s",
                aptitude.getPersonName(),
                aptitude.getAptitudeName(),
                message);
        MsgTemplateVO msgTemplateVO = new MsgTemplateVO();
        msgTemplateVO.setTemplateContent(fullMessage);
        msgTemplateVO.setTemplateType("notice");
        msgTemplateVO.setTemplateTypeName("通知");
        tMsgNoticeService.generateMsgNotice("aptitude",aptitude.getId(),getUserId(aptitude.getOrgId()),msgTemplateVO);
    }

    private List<String> getUserId(String orgId) {
        List<SysUser> userList = sysUserService.findOrgId(orgId);
        List<String> userIds = userList.stream()
                .map(SysUser::getUserId)
                .collect(Collectors.toList());

        List<SysRole> roleList = roleService.list(new QueryWrapper<SysRole>().like(SysRole.ROLE_NAME, "_system_admin"));
        List<String> roleIdList = roleList.stream()
                .map(SysRole::getRoleId)
                .collect(Collectors.toList());

        List<SysUserRole> userRoleList = userRoleService.list(new QueryWrapper<SysUserRole>().in(SysUser.USER_ID, userIds).eq(SysRole.ROLE_ID, roleIdList));

        List<String> returnUserIdList = userRoleList.stream()
                .map(SysUserRole::getUserId)
                .collect(Collectors.toList());

        return returnUserIdList;
    }



}
