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

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tuoheng.admin.constant.SystemConstant;
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.InspectionStatusEnum;
import com.tuoheng.admin.enums.InspectionTypeEnum;
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.AccidentVerifyCompletedRequest;
import com.tuoheng.admin.request.accident.AccidentVerifyRequest;
import com.tuoheng.admin.service.third.airport.DroneControlService;
import com.tuoheng.admin.utils.CurrentUserUtil;
import com.tuoheng.common.core.config.common.CommonConfig;
import com.tuoheng.common.core.exception.ServiceException;
import com.tuoheng.common.core.utils.DateUtils;
import com.tuoheng.common.core.utils.HttpUtils;
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;
import org.springframework.transaction.annotation.Transactional;

/**
 * 事故核实完成业务层处理
 *
 * @author wanjing
 * @team tuoheng
 * @date 2023-03-15
 */
@Slf4j
@Service
public class AccidentVerifyCompletedService {

    @Autowired
    private AccidentMapper accidentMapper;

    @Autowired
    private InspectionMapper inspectionMapper;

    @Autowired
    private InspectionFileMapper inspectionFileMapper;

    @Autowired
    private DroneControlService droneControlService;

    /**
     *
     * 1、向机场推送返舱指令，无人机返回机场
     * 2、修改该事故状态为完成
     * 3、应急任务状态改为已完成
     *
     * @param request
     * @return
     */
    public JsonResult verifyCompleted(AccidentVerifyCompletedRequest 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);

        // 修改原巡检任务状态为已完成
        Inspection inspection = inspectionMapper.selectOne(new LambdaQueryWrapper<Inspection>()
                .eq(Inspection::getId, accident.getAccidentInspectionId())
                .eq(Inspection::getMark, MarkEnum.VALID.getCode()));
        inspection.setStatus(InspectionStatusEnum.FLIGHT_COMPLETED.getCode());
        inspectionMapper.updateById(inspection);

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

        return JsonResult.success();
    }

    /**
     * 检查参数
     *
     * @param tenantId
     * @param request
     * @return
     */
    private JsonResult check(String tenantId, AccidentVerifyCompletedRequest 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.PROCESSED.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.setUpdateUser(userId);
        accidentUpdate.setUpdateTime(DateUtils.now());
        accidentUpdate.setEndTime(DateUtils.now());
        accidentUpdate.setStatus(AccidentStatusEnum.COMPLETED.getCode());
        Integer count = accidentMapper.updateById(accidentUpdate);
        if (count <= 0) {
            log.info("事故核实完成，修改预警信息失败");
        }
    }
}
