package com.tuoheng.admin.service.inspection.update.status;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tuoheng.admin.entity.domain.Inspection;
import com.tuoheng.admin.entity.domain.InspectionHistory;
import com.tuoheng.admin.enums.InspectionStatusEnum;
import com.tuoheng.admin.enums.MarkEnum;
import com.tuoheng.admin.mapper.InspectionHistoryMapper;
import com.tuoheng.admin.mapper.InspectionMapper;
import com.tuoheng.admin.entity.request.inspection.ExecuteTaskStatusRequest;
import com.tuoheng.common.core.utils.DateUtils;
import com.tuoheng.common.core.utils.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 被硬件调用，执行任务后，回调执行状态
 *
 * @author wanjing
 * @team tuoheng
 * @date 2023-01-10
 */
@Slf4j
@Service
public class UpdateExecuteTaskStatusService {

    @Autowired
    private InspectionMapper inspectionMapper;

    @Autowired
    private InspectionHistoryMapper inspectionHistoryMapper;

    /**
     * 被硬件调用，执行任务后，回调执行状态
     *
     * @return
     */
    public JsonResult updateStatus(ExecuteTaskStatusRequest executeTaskStatusRequest) {
        JsonResult result = this.check(executeTaskStatusRequest);
        if (0 != result.getCode()) {
            log.info("被硬件调用，执行任务后，回调执行状态业务：校验失败：{}", result.getMsg());
            return result;
        }
        Inspection inspection = (Inspection) result.getData();
        if (!"0".equals(executeTaskStatusRequest.getCode())) {
            log.info("被硬件调用，执行任务后，回调执行状态业务, 机场接口返回结果：失败：{}", executeTaskStatusRequest.getMsg());
            inspection.setStatus(InspectionStatusEnum.FLIGHT_FAILED.getCode());
            this.updateInspection("", inspection);

            this.insertInspectionHistory("", inspection.getTenantId(), inspection, executeTaskStatusRequest.getMsg());

        } else {
            inspection.setStatus(InspectionStatusEnum.IN_FLIGHT.getCode());
            this.updateInspection("", inspection);
        }
        log.info("被硬件调用，任务执行后，回调执行状态业务成功");
        return JsonResult.success("被硬件调用，任务执行后，回调执行状态业务成功");
    }

    /**
     * 检查参数
     *
     * @param executeTaskStatusRequest
     * @return
     */
    private JsonResult check(ExecuteTaskStatusRequest executeTaskStatusRequest) {
        //查询出对应的巡检任务
        Inspection inspection = inspectionMapper.selectOne(new LambdaQueryWrapper<Inspection>()
                .eq(Inspection::getMark, MarkEnum.VALID.getCode())
                .eq(Inspection::getId, executeTaskStatusRequest.getRequestId()));
        if (ObjectUtil.isEmpty(inspection)) {
            log.info("任务不存在, inspectionId:{}", executeTaskStatusRequest.getRequestId());
            return JsonResult.error(500, "任务不存在" + executeTaskStatusRequest.getRequestId());
        }
        return JsonResult.success(inspection);
    }

    /**
     * 修改任务执行时数据
     *
     * @param userId
     * @param inspection
     */
    private void updateInspection(String userId, Inspection inspection) {
        inspection.setStatus(inspection.getStatus());
        inspection.setUpdateUser(userId);
        inspection.setUpdateTime(DateUtils.now());
        inspection.setExecutionStartTime(DateUtils.now());
        inspectionMapper.updateStatus(inspection);
    }

    /**
     * 更新任务中
     *
     * @param tenantId
     * @param inspection
     */
    private void insertInspectionHistory(String userId, String tenantId, Inspection inspection, String msg) {
        InspectionHistory inspectionHistory = new InspectionHistory();
        inspectionHistory.setTenantId(tenantId);
        inspectionHistory.setInspectionId(inspection.getId());
        inspectionHistory.setHistoryName(msg);
        inspectionHistory.setCreateUser(userId);
        inspectionHistory.setCreateTime(DateUtils.now());
        inspectionHistoryMapper.insert(inspectionHistory);
    }
}
