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

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tuoheng.admin.entity.Accident;
import com.tuoheng.admin.entity.Inspection;
import com.tuoheng.admin.entity.InspectionFile;
import com.tuoheng.admin.entity.User;
import com.tuoheng.admin.enums.AccidentStatusEnum;
import com.tuoheng.admin.enums.MarkEnum;
import com.tuoheng.admin.mapper.AccidentMapper;
import com.tuoheng.admin.mapper.InspectionFileMapper;
import com.tuoheng.admin.mapper.InspectionMapper;
import com.tuoheng.admin.request.accident.ReportAccidentRequest;
import com.tuoheng.admin.request.accident.ReportNoAccidentRequest;
import com.tuoheng.admin.service.third.airport.DroneControlService;
import com.tuoheng.admin.utils.CurrentUserUtil;
import com.tuoheng.common.core.exception.ServiceException;
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 wanjing
 * @team tuoheng
 * @date 2023-03-15
 */
@Slf4j
@Service
public class ReportNoAccidentService {

    @Autowired
    private AccidentMapper accidentMapper;

    @Autowired
    private InspectionMapper inspectionMapper;

    @Autowired
    private InspectionFileMapper inspectionFileMapper;

    @Autowired
    private DroneControlService droneControlService;

    public JsonResult report(ReportNoAccidentRequest request) {
//        log.info("进入无事故业务");
        User user = CurrentUserUtil.getUserInfo();
        String userId = user.getId();
        String tenantId = user.getTenantId();
        JsonResult result = this.check(tenantId, request);
        if (0 != result.getCode()) {
            log.info("无事故业务：校验失败：{}", result.getMsg());
            return result;
        }
        Accident accident = (Accident) result.getData();

        this.updateAccident(accident.getId(), userId);

        // 无人机回仓
        this.droneReturn(accident.getInspectionId());

        return JsonResult.success();
    }

    /**
     * 检查参数
     *
     * @param tenantId
     * @param request
     * @return
     */
    private JsonResult check(String tenantId, ReportNoAccidentRequest request) {
        if (StringUtils.isEmpty(request.getAccidentId())) {
            throw new ServiceException("事故ID为空");
        }
        Accident accident = accidentMapper.selectOne(new LambdaQueryWrapper<Accident>()
                .eq(Accident::getTenantId, tenantId)
                .eq(Accident::getId, request.getAccidentId())
                .eq(Accident::getMark, MarkEnum.VALID.getCode()));
        if (ObjectUtil.isNull(accident)) {
            throw new ServiceException("事故不存在");
        }
        if (AccidentStatusEnum.PROCESSING.getCode() != accident.getStatus()) {
            throw new ServiceException("处理中的事故才能上报为无事故");
        }
        return JsonResult.success(accident);
    }

    /**
     * 无人机回仓
     *
     * @param inspectionId
     */
    private void droneReturn(String inspectionId) {
        log.info("事故确认是无事故，无人机回仓");
        Inspection inspection = inspectionMapper.selectOne(new LambdaQueryWrapper<Inspection>()
                .eq(Inspection::getId, inspectionId)
                .eq(Inspection::getMark, MarkEnum.VALID.getCode()));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("zhilin", "03");
        jsonObject.put("taskId", inspection.getId());
        jsonObject.put("airportId", inspection.getAirportId());
        jsonObject.put("msg", "回仓");
        JsonResult jsonResult = droneControlService.execute(jsonObject);
        if (0 != jsonResult.getCode()) {
            log.info("机场平台返回，返回无人机回仓失败");
        }
    }

    /**
     * 修改预警记录信息
     *
     * @param id
     * @param userId
     */
    private void updateAccident(String id, String userId) {
        Accident accidentUpdate = new Accident();
        accidentUpdate.setId(id);
        accidentUpdate.setIsAccident(0);
        accidentUpdate.setStatus(AccidentStatusEnum.PROCESSED.getCode());
        accidentUpdate.setUpdateUser(userId);
        accidentUpdate.setUpdateTime(DateUtils.now());
        accidentUpdate.setNoAccidentTime(DateUtils.now());
        Integer count = accidentMapper.updateById(accidentUpdate);
        if (count <= 0) {
            log.info("无事故，修改预警信息失败");
        }
    }

}
