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

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tuoheng.admin.entity.Accident;
import com.tuoheng.admin.entity.AccidentInspection;
import com.tuoheng.admin.entity.User;
import com.tuoheng.admin.enums.MarkEnum;
import com.tuoheng.admin.enums.code.accident.AddAccidentEnum;
import com.tuoheng.admin.enums.code.inspection.AddInspectionCodeEnum;
import com.tuoheng.admin.mapper.AccidentInspectionMapper;
import com.tuoheng.admin.mapper.AccidentMapper;
import com.tuoheng.admin.request.accident.AccidentRecordRequest;
import com.tuoheng.admin.request.accident.AddAccidentRequest;
import com.tuoheng.admin.utils.CurrentUserUtil;
import com.tuoheng.common.core.common.BaseEntity;
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 wanjing
 * @team tuoheng
 * @date 2023-04-14
 */
@Slf4j
@Service
public class RecordAccidentService {

    @Autowired
    private AccidentMapper accidentMapper;
    @Autowired
    private AccidentInspectionMapper accidentInspectionMapper;

    /**
     * 添加任务
     *
     * @return
     */
    public JsonResult record(AccidentRecordRequest 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("该应急事故不存在");
        }
        //查询出对应的应急任务关联表
        AccidentInspection accidentInspection = accidentInspectionMapper.selectOne(Wrappers.<AccidentInspection>lambdaQuery()
                .eq(AccidentInspection::getAccidentId, request.getAccidentId()).eq(BaseEntity::getMark, MarkEnum.VALID.getCode()));
        //更新记录
        accidentInspection.setRemark(request.getRemark());
        int count = accidentInspectionMapper.updateById(accidentInspection);
        if (count <= 0) {
            return JsonResult.error("记录修改失败");
        }
        return JsonResult.success();
    }

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

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


}
