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

import com.rongwe.scentity.domian.AspSafeAttachmentsDo;
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.rwadmincommon.system.vo.SysUserVo;
import com.rongwei.rwcommon.base.R;
import com.rongwei.rwcommon.base.exception.CustomException;
import com.rongwei.rwcommon.utils.StringUtils;
import com.rongwei.safecommon.utils.CXCommonUtils;
import com.rongwei.sfcommon.sys.dao.SaveCheckCommonDao;
import com.rongwei.sfcommon.sys.service.UrgingService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.rongwei.safecommon.utils.SaveConstans.NotifyContent.PERSONNEL_CERTIFICATES_URGING_CONTENT;
import static com.rongwei.safecommon.utils.SaveConstans.NotifyContent.SAFETY_ATTACHMENT_VERIFICATION_URGING_CONTENT;
import static com.rongwei.safecommon.utils.SaveConstans.NotifyTitle.PERSONNEL_CERTIFICATES_URGING_TITLE;
import static com.rongwei.safecommon.utils.SaveConstans.NotifyTitle.SAFETY_ATTACHMENT_VERIFICATION_URGING_TITLE;
import static com.rongwei.safecommon.utils.SaveConstans.NotifyType.PERSONNEL_CERTIFICATES;
import static com.rongwei.safecommon.utils.SaveConstans.NotifyType.SPECIALEQUIPMENT;

/**
 * SpecialCertificateUrgingServiceImpl class
 *
 * @author XH
 * @date 2024/09/13
 */
@Service
public class SpecialCertificateUrgingServiceImpl implements UrgingService {
    private final Logger log = LoggerFactory.getLogger(this.getClass().getName());
    @Autowired
    private AspSpecialEquipmentCertificateServiceImpl aspSpecialEquipmentCertificateService;
    @Autowired
    private SaveCheckCommonDao saveCheckCommonDao;
    @Autowired
    private SysDictService sysDictService;
    public static final String MAIL_CONTENT=" 您好！【%s】提醒您，有如下特种设备人员证书即将年检到期，请尽快处理！\n" +
            "%s" +
            "\n详见安全生产平台，如果无法点击请复制链接到浏览器中：http://192.168.100.77/#/page/lr/9329c07dd31b4b8b95d4decaa021adc3";
    public static final String MAIL_CONTENT_ITEM="%d、姓名:【%s】，所属部门:【%s】，证书类别:【%s】，复审日期：【%tF】\n";

    public static final List<String> ROLE_CODE_LIST = new ArrayList<String>() {{
        add("code-safe");
        add("role031");
    }};

    @Override
    public R emailAndNotifyUrging(List<String> ids) {
        if (ids == null || ids.isEmpty()) {
            log.error("id为空");
        }
        SysUserVo currentUser = CXCommonUtils.getCurrentUser();
        String currentUserFactoryId = CXCommonUtils.getCurrentUserFactoryId(currentUser);
        List<AspSpecialEquipmentCertificateDo> aspSpecialEquipmentCertificateDos = aspSpecialEquipmentCertificateService.getBaseMapper().selectBatchIds(ids);
        if (aspSpecialEquipmentCertificateDos.isEmpty()) {
            log.debug("根据id:{}没有找到安全附件信息", ids);
            return R.ok();
        }
        //获取工厂对应的 安全管理员和特种设备管理员
        List<UserMailOrgVo> userInfo = saveCheckCommonDao.getUserInfoByTenantIdAndRoleCode(currentUserFactoryId, ROLE_CODE_LIST);
        // 发生通知信息
        sendNotify(PERSONNEL_CERTIFICATES_URGING_TITLE, String.format(PERSONNEL_CERTIFICATES_URGING_CONTENT, currentUser.getName(),
                        aspSpecialEquipmentCertificateDos.size())
                , userInfo.stream().map(UserMailOrgVo::getId).collect(Collectors.toList()),
                aspSpecialEquipmentCertificateDos.stream().map(AspSpecialEquipmentCertificateDo::getId).collect(Collectors.joining(","))
                , PERSONNEL_CERTIFICATES);
        // 收件箱
        String[] array = userInfo.stream().map(UserMailOrgVo::getEmail).filter(StringUtils::isNotBlank).toArray(String[]::new);
        if (array.length == 0) {
            log.error("收件人邮箱为空");
            throw new CustomException("收件人邮箱为空无法发送通知邮件");
        }
        // 数据字典替换
        List<SysDictDo> sysDictDoList= sysDictService.getDictsByType("zslb");

        AspSpecialEquipmentCertificateDo aspSpecialEquipmentCertificateDo;
        List<String> str = new ArrayList<>();
        for (int i = 0; i < aspSpecialEquipmentCertificateDos.size(); i++) {
            aspSpecialEquipmentCertificateDo = aspSpecialEquipmentCertificateDos.get(i);
            String certificatesort = aspSpecialEquipmentCertificateDo.getCertificatesort();
            SysDictDo sysDictDo = sysDictDoList.stream()
                    .filter(data -> data.getValue().equals(certificatesort))
                    .findFirst()
                    .orElse(null);
            str.add(String.format(MAIL_CONTENT_ITEM, i + 1, aspSpecialEquipmentCertificateDo.getName(),
                    aspSpecialEquipmentCertificateDo.getOrgname(), sysDictDo == null ? "" : sysDictDo.getName(),
                    aspSpecialEquipmentCertificateDo.getReviewdate()));
        }
        // 发送通知邮件
        sendEmail(PERSONNEL_CERTIFICATES_URGING_TITLE, String.format(MAIL_CONTENT,currentUser.getName(), StringUtils.join(str, "\n")), array);
        return R.ok("催办成功");
    }
}
