package com.rongwei.sfcommon.sys.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rongwe.scentity.domian.AspSpecialEquipmentCertificateDo;
import com.rongwe.scentity.vo.UserMailOrgVo;
import com.rongwei.rwadmincommon.system.domain.SysDictDo;
import com.rongwei.rwadmincommon.system.service.SysDictService;
import com.rongwei.rwcommon.base.R;
import com.rongwei.safecommon.utils.JSCommonUtils;
import com.rongwei.sfcommon.sys.dao.AspSpecialEquipmentCertificateDao;
import com.rongwei.sfcommon.sys.dao.SaveCheckCommonDao;
import com.rongwei.sfcommon.sys.service.AspSpecialEquipmentCertificateService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

import static com.rongwei.safecommon.utils.SaveConstans.*;
import static com.rongwei.safecommon.utils.SaveConstans.NotifyContent.PERSONNEL_CERTIFICATES_CONTENT;
import static com.rongwei.safecommon.utils.SaveConstans.NotifyTitle.PERSONNEL_CERTIFICATES_TITLE;
import static com.rongwei.safecommon.utils.SaveConstans.NotifyType.PERSONNEL_CERTIFICATES;

/**
 *
 */
@Service
public class AspSpecialEquipmentCertificateServiceImpl extends ServiceImpl<AspSpecialEquipmentCertificateDao, AspSpecialEquipmentCertificateDo>
        implements AspSpecialEquipmentCertificateService {
    /**
     * 组织机构代码
     */
    public static final List<String> ROLE_CODE_LIST = new ArrayList<String>() {{
        add("code-safe");
        add("role031");
    }};
    /**
     * 特种设备管理员
     */
    public static final String SPECIAL_EQUIPMENT_ADMINISTRATOR = "role031";

    private final Logger log = LoggerFactory.getLogger(this.getClass().getName());
    @Autowired
    private SaveCheckCommonDao saveCheckCommonDao;
    @Autowired
    private SysDictService sysDictService;

    @Override
    public R stateUpdateScheduledTasks() {
        // 获取所有的安全附件
        List<AspSpecialEquipmentCertificateDo> safeAttachmentsDos = this.list();
        if (safeAttachmentsDos.isEmpty()) {
            return R.ok("暂无安全附件");
        }
        // 对数据按照租户ID 分组
        Map<String, List<AspSpecialEquipmentCertificateDo>> dataMap = safeAttachmentsDos.stream().collect(Collectors.groupingBy(AspSpecialEquipmentCertificateDo::getTenantid));
        List<AspSpecialEquipmentCertificateDo> saveData = new ArrayList<>();
        // 发送消息提醒的参数
        Map<AspSpecialEquipmentCertificateDo, List<String>> sendNotifyMap = new HashMap<>();
        dataMap.forEach((k, v) -> {
            //获取工厂对应的 安全管理员和特种设备管理员
            List<UserMailOrgVo> userInfO = saveCheckCommonDao.getUserInfoByTenantIdAndRoleCode(k, ROLE_CODE_LIST);
            Date manufacturedate;
            long daysBetween;
            List<String> alertUser;
            for (AspSpecialEquipmentCertificateDo data : v) {
                manufacturedate = data.getReviewdate();
                LocalDate date1 = manufacturedate.toInstant()
                        .atZone(ZoneId.systemDefault())
                        .toLocalDate();
                daysBetween = ChronoUnit.DAYS.between(LocalDate.now(), date1);
                if (daysBetween <= 30) {
                    data.setReminderstate(HIGH);
                    alertUser = userInfO.stream().map(UserMailOrgVo::getId).collect(Collectors.toList());
                    sendNotifyMap.put(data, alertUser);
                } else if (daysBetween <= 90) {
                    alertUser = userInfO.stream().filter(user -> SPECIAL_EQUIPMENT_ADMINISTRATOR.equals(user.getRoleCode())).map(UserMailOrgVo::getId).collect(Collectors.toList());
                    sendNotifyMap.put(data, alertUser);
                    data.setReminderstate(MIDDLE);
                } else {
                    data.setReminderstate(LOW);
                }

                saveData.add(data);
            }
        });
        this.updateBatchById(saveData);
        sendNotify(sendNotifyMap);
        return R.ok();
    }


    public void sendNotify(Map<AspSpecialEquipmentCertificateDo, List<String>> sendNotifyMap) {
        // 获取数据字典
        List<SysDictDo> aspCheckItemType = sysDictService.getDictsByType("asp_check_item_type");
        sendNotifyMap.forEach((k, v) -> {
            SysDictDo sysDictDo = aspCheckItemType.stream()
                    .filter(info -> info.getValue().equals(k.getCertificatesort()))
                    .findFirst().orElse(null);
            // 发送消息提醒
            JSCommonUtils.sendNotify(PERSONNEL_CERTIFICATES_TITLE,
                    String.format(PERSONNEL_CERTIFICATES_CONTENT, k.getName(), k.getOrgname(), sysDictDo == null ? "" : sysDictDo.getName(),
                            k.getReviewdate()), null, v.stream().distinct().collect(Collectors.toList()),
                    k.getId(), PERSONNEL_CERTIFICATES, false);
        });
    }
}




