package com.tuoheng.admin.service.warning.ignore;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tuoheng.admin.entity.domain.Warning;
import com.tuoheng.admin.enums.MarkEnum;
import com.tuoheng.admin.enums.WarningStatusEnum;
import com.tuoheng.admin.mapper.WarningMapper;
import com.tuoheng.common.exception.ServiceException;
import com.tuoheng.common.utils.DateUtils;
import com.tuoheng.common.utils.JsonResult;
import com.tuoheng.system.entity.User;
import com.tuoheng.system.utils.ShiroUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 预警忽略业务层处理
 *
 * @author wanjing
 * @team tuoheng
 * @date 2023-02-07
 */
@Slf4j
@Service
public class WarningIgnoreService {

    @Autowired
    private WarningMapper warningMapper;

    public JsonResult ignore(Integer id) {
        log.info("进入预警忽略业务, id:{}", id);
        User user = ShiroUtils.getUserInfo();
        Integer tenantId = user.getTenantId();
        JsonResult result = this.check(tenantId, id);
        if (0 != result.getCode()) {
            log.info("进入预警忽略业务：校验失败：{}", result.getMsg());
            return result;
        }

        // 忽略任务问题
        result = this.updateStatus(user, id);

        return result;
    }

    /**
     * 检查参数
     *
     * @param tenantId
     * @param id
     * @return
     */
    private JsonResult check(Integer tenantId, Integer id) {
        // 判断预警id是否为空
        if (ObjectUtil.isNotNull(id)) {
            throw new ServiceException("预警ID为空");
        }
        Warning warning = warningMapper.selectOne(new LambdaQueryWrapper<Warning>()
                .in(Warning::getId, id)
                .eq(Warning::getMark, MarkEnum.VALID.getCode()));
        if (ObjectUtil.isNull(warning)) {
            throw new ServiceException("预警信息不存在");
        }
        if (!tenantId.equals(warning.getTenantId())) {
            throw new ServiceException("该租户没有查询该预警信息的权限");
        }
        return JsonResult.success(warning);
    }

    /**
     * 预警状态，改为忽略
     *
     * @param user
     * @param id
     */
    private JsonResult updateStatus(User user, Integer id) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("status", WarningStatusEnum.IGNORE.getCode());
        map.put("updateUser", user.getId());
        map.put("updateTime", DateUtils.now());
        map.put("checkUser", user.getId());
        map.put("checkTime", DateUtils.now());
        Integer rowCount = warningMapper.confirm(map);
        if (rowCount <= 0) {
            log.info("修改预警状态， 确认失败");
            throw new ServiceException("修改预警状态， 确认失败");
        }
        return JsonResult.success();
    }

}
