package cn.iocoder.yudao.module.pms.job.qhse;

import cn.iocoder.yudao.framework.quartz.core.handler.JobHandler;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.framework.tenant.core.util.TenantUtils;
import cn.iocoder.yudao.module.pms.constant.PmsConstants;
import cn.iocoder.yudao.module.pms.controller.admin.qhse.jsa.vo.QhseJsaPageReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.qhse.ptw.vo.QhsePtwPageReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.qhse.soc.vo.IotSocSummaryPageReqVO;
import cn.iocoder.yudao.module.pms.dal.dataobject.qhse.report.QhseMonthReportDO;
import cn.iocoder.yudao.module.pms.dal.mysql.qhse.jsa.QhseJsaMapper;
import cn.iocoder.yudao.module.pms.dal.mysql.qhse.ptw.QhsePtwMapper;
import cn.iocoder.yudao.module.pms.dal.mysql.qhse.report.QhseMonthReportMapper;
import cn.iocoder.yudao.module.pms.dal.mysql.qhse.soc.IotSocSummaryMapper;
import cn.iocoder.yudao.module.pms.message.PmsMessage;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO;
import cn.iocoder.yudao.module.system.api.permission.RoleApi;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import cn.iocoder.yudao.module.system.service.dept.DeptService;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CompletableFuture;

import static cn.iocoder.yudao.framework.common.util.date.DateUtils.getFirstDayOfLastMonth;
import static cn.iocoder.yudao.framework.common.util.date.DateUtils.getLastDayOfLastMonth;

@Component
public class MonthReportJob implements JobHandler {
    private final RoleApi roleApi;
    private final IotSocSummaryMapper iotSocSummaryMapper;
    private final AdminUserApi adminUserApi;
    private final DeptService deptService;
    private final QhseJsaMapper qhseJsaMapper;
    private final QhsePtwMapper qhsePtwMapper;
    private final DeptApi deptApi;
    private final QhseMonthReportMapper qhseMonthReportMapper;
    private final PmsMessage pmsMessage;

    public MonthReportJob(RoleApi roleApi, IotSocSummaryMapper iotSocSummaryMapper, AdminUserApi adminUserApi, DeptService deptService, QhseJsaMapper qhseJsaMapper, QhsePtwMapper qhsePtwMapper, DeptApi deptApi, QhseMonthReportMapper qhseMonthReportMapper, PmsMessage pmsMessage) {
        this.roleApi = roleApi;
        this.iotSocSummaryMapper = iotSocSummaryMapper;
        this.adminUserApi = adminUserApi;
        this.deptService = deptService;
        this.qhseJsaMapper = qhseJsaMapper;
        this.qhsePtwMapper = qhsePtwMapper;
        this.deptApi = deptApi;
        this.qhseMonthReportMapper = qhseMonthReportMapper;
        this.pmsMessage = pmsMessage;
    }

    @Override
    @TenantIgnore
    public String execute(String param) throws Exception {
        LocalDateTime firstDayOfLastMonth = getFirstDayOfLastMonth();
        // 上个月结束：yyyy-MM-最后一天 23:59:59
        LocalDateTime lastDayOfLastMonth = getLastDayOfLastMonth();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
        String yearMonth = firstDayOfLastMonth.format(formatter);
        List<Long> userIds = roleApi.getRoleUserIds("QHSE月报");
        userIds.forEach(e ->{
            Set<Long> ids = new HashSet<>();
            AdminUserRespDTO user = adminUserApi.getUser(e);
            if (Objects.nonNull(user.getDeptId())) {
                ids = deptService.getChildDeptIdListFromCache(user.getDeptId());
                ids.add(user.getDeptId());
            }
            IotSocSummaryPageReqVO pageReqVO = new IotSocSummaryPageReqVO();
            pageReqVO.setObservationDate(new LocalDateTime[]{firstDayOfLastMonth, lastDayOfLastMonth});
            Long socCount = iotSocSummaryMapper.selectCountBySocClassAndTime(pageReqVO, ids);
            QhseJsaPageReqVO qhseJsaPageReqVO = new QhseJsaPageReqVO();
            qhseJsaPageReqVO.setJsaTime(new LocalDateTime[]{firstDayOfLastMonth, lastDayOfLastMonth});
            Long jsaCount = qhseJsaMapper.selectCountByDeptAndTime(qhseJsaPageReqVO, ids);
            QhsePtwPageReqVO qhsePtwPageReqVO = new QhsePtwPageReqVO();
            qhsePtwPageReqVO.setPtwTime(new LocalDateTime[]{firstDayOfLastMonth, lastDayOfLastMonth});
            Long ptwCount = qhsePtwMapper.selectCountByDeptAndTime(qhsePtwPageReqVO, ids);
            TenantUtils.execute(1L, () -> {
                QhseMonthReportDO qhseMonthReportDO = new QhseMonthReportDO();
                DeptRespDTO dept = deptApi.getDept(user.getDeptId());

                qhseMonthReportDO.setTitle(dept.getName()+yearMonth+"QHSE月报");
                qhseMonthReportDO.setYearMonths(yearMonth);
                qhseMonthReportDO.setDeleted(false);
                qhseMonthReportDO.setSocCards(String.valueOf(socCount));
                qhseMonthReportDO.setJsa(String.valueOf(jsaCount));
                qhseMonthReportDO.setPtwAudit(String.valueOf(ptwCount));
                qhseMonthReportDO.setDutyPerson(e);
                qhseMonthReportDO.setDeptId(dept.getId());
                qhseMonthReportMapper.insert(qhseMonthReportDO);
                //异步线程发送消息
                CompletableFuture.runAsync(() -> {
                    pmsMessage.sendMessage(qhseMonthReportDO.getId(), dept.getName() + yearMonth + "QHSE月报已生成，请前往QHSE系统月报模块进行填报。", PmsConstants.QHSE_MONTH_REPORT, user.getId(), user.getMobile());
                });
            });
        });
        return "";
    }
}
