package com.tuoheng.admin.service.accident.handle;

import com.tuoheng.admin.entity.Accident;
import com.tuoheng.admin.entity.User;
import com.tuoheng.admin.enums.AccidentStatusEnum;
import com.tuoheng.admin.enums.code.accident.AddAccidentEnum;
import com.tuoheng.admin.mapper.AccidentMapper;
import com.tuoheng.admin.request.accident.AccidentHandleRequest;
import com.tuoheng.admin.utils.CurrentUserUtil;
import com.tuoheng.admin.websocket.WebSocketService;
import com.tuoheng.common.core.utils.DateUtils;
import com.tuoheng.common.core.utils.JsonResult;
import com.tuoheng.common.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 应急事故处理完成业务层处理
 *
 * @Author xiaoying
 * @Date 2023/4/19 10:32
 */
@Service
@Slf4j
public class HandleAccidentService {


    @Autowired
    private AccidentMapper accidentMapper;

    @Autowired
    private WebSocketService webSocketService;

    /**
     * 添加任务
     *
     * @return
     */
    public JsonResult handle(AccidentHandleRequest request) {
        log.info("应急事故处理完成业务");
        User user = CurrentUserUtil.getUserInfo();
        String tenantId = user.getTenantId();
        JsonResult result = this.checkParam(user.getId(), tenantId, request);
        if (0 != result.getCode()) {
            log.info("应急事故处理完成业务：校验参数失败：{}", result.getMsg());
            return result;
        }
        //查询出对应的应急事故
        Accident accident = accidentMapper.selectById(request.getAccidentId());
        if (StringUtils.isNull(accident)) {
            return JsonResult.error("该应急事故不存在");
        }
        //变更对应应急事故状态以及对应应急任务状态
        accident.setStatus(AccidentStatusEnum.PROCESSED.getCode());
        accident.setUpdateUser(user.getId());
        accident.setUpdateTime(DateUtils.now());
        accident.setEndTime(DateUtils.now());
        int count = accidentMapper.updateById(accident);
        if (count <= 0) {
            return JsonResult.error("应急事故处理完成修改状态失败");
        }
        //推送信息
        webSocketService.accidentNotice(accident.getTenantId());
        return JsonResult.success();
    }

    /**
     * 检查参数
     *
     * @param tenantId
     * @param request
     * @return
     */
    private JsonResult checkParam(String userId, String tenantId, AccidentHandleRequest request) {

        if (StringUtils.isEmpty(request.getAccidentId())) {
            return JsonResult.error(AddAccidentEnum.ACCIDENT_ID_IS_FAILED);
        }
        return JsonResult.success();
    }
}
