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

import com.rongwe.scentity.domian.CheckItemsDo;
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.SPECIAL_EQUIPMENT_URGING_CONTENT;
import static com.rongwei.safecommon.utils.SaveConstans.NotifyTitle.SPECIALEQUIPMENT_URGING_TITLE;
import static com.rongwei.safecommon.utils.SaveConstans.NotifyType.SPECIALEQUIPMENT;

/**
 * SpecialEquipmentUrgingServiceImpl class
 *
 * @author XH
 * @date 2024/09/13
 */
@Service
public class SpecialEquipmentUrgingServiceImpl implements UrgingService {
    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】";
    public static final List<String> ROLE_CODE_LIST = new ArrayList<String>() {{
        add("code-safe");
        add("role031");
    }};
    private final Logger log = LoggerFactory.getLogger(this.getClass().getName());
    @Autowired
    private CheckItemsServiceImpl checkItemsService;
    @Autowired
    private SaveCheckCommonDao saveCheckCommonDao;
    @Autowired
    private SysDictService sysDictService;

    @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<CheckItemsDo> checkItemsDos = checkItemsService.getBaseMapper().selectBatchIds(ids);
        if (checkItemsDos.isEmpty()) {
            log.debug("根据id:{}没有找到特种设备信息", ids);
            return R.ok();
        }
        //获取工厂对应的 安全管理员和特种设备管理员
        List<UserMailOrgVo> userInfo = saveCheckCommonDao.getUserInfoByTenantIdAndRoleCode(currentUserFactoryId, ROLE_CODE_LIST);
        // 发生通知信息
        sendNotify(SPECIALEQUIPMENT_URGING_TITLE, String.format(SPECIAL_EQUIPMENT_URGING_CONTENT, currentUser.getName(),
                        checkItemsDos.size())
                , userInfo.stream().map(UserMailOrgVo::getId).collect(Collectors.toList()),
                checkItemsDos.stream().map(CheckItemsDo::getId).collect(Collectors.joining(","))
                , SPECIALEQUIPMENT);

        // 收件箱
        String[] array = userInfo.stream().map(UserMailOrgVo::getEmail).filter(StringUtils::isNotBlank).toArray(String[]::new);
        if (array.length == 0) {
            log.error("收件人邮箱为空");
            throw new CustomException("收件人邮箱为空无法发送通知邮件");
        }
        // 数据字典替换
        List<SysDictDo> aspCheckItemType = sysDictService.getDictsByType("asp_check_item_type");
        CheckItemsDo checkItemsDo;
        List<String> str = new ArrayList<>();
        for (int i = 0; i < checkItemsDos.size(); i++) {
            checkItemsDo = checkItemsDos.get(i);
            String checkitemtype = checkItemsDo.getCheckitemtype();
            SysDictDo sysDictDo = aspCheckItemType.stream()
                    .filter(data -> data.getValue().equals(checkitemtype))
                    .findFirst()
                    .orElse(null);
            str.add(String.format(MAIL_CONTENT_ITEM, i + 1, sysDictDo == null ? "" : sysDictDo.getName(),
                    checkItemsDo.getDeviceoutcode(), checkItemsDo.getCheckitemname(),
                    checkItemsDo.getNextcheckdate()));
        }

        // 发送通知邮件
        sendEmail(SPECIALEQUIPMENT_URGING_TITLE, String.format(MAIL_CONTENT, currentUser.getName(), StringUtils.join(str, "\n")), array);
        return R.ok("催办成功");
    }
}
