package com.tuoheng.admin.service.inspection.execute;

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.Inspection;
import com.tuoheng.admin.entity.InspectionHistory;
import com.tuoheng.admin.entity.Tenant;
import com.tuoheng.admin.entity.User;
import com.tuoheng.admin.enums.code.inspection.ExecuteInspectionCodeEnum;
import com.tuoheng.admin.mapper.InspectionHistoryMapper;
import com.tuoheng.admin.mapper.InspectionMapper;
import com.tuoheng.admin.mapper.TenantMapper;
import com.tuoheng.admin.mapper.UserMapper;
import com.tuoheng.admin.service.third.airport.AirportService;
import com.tuoheng.admin.utils.CurrentUserUtil;
import com.tuoheng.common.core.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 立即执行任务业务层处理
 *
 * @author wanjing
 * @team tuoheng
 * @date 2022-12-01
 */
@Slf4j
@Service
public class ExecuteInspectionService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private InspectionMapper inspectionMapper;

    @Autowired
    private TenantMapper tenantMapper;

    @Autowired
    private InspectionHistoryMapper inspectionHistoryMapper;

    @Autowired
    private AirportService airportService;

    /**
     * 重新提交任务
     *
     * @return
     */
    public JsonResult execute(String id) {
        log.info("进入立即执行任务业务");
        String userId = CurrentUserUtil.getUserId();
        String tenantId = CurrentUserUtil.getTenantId();

        JsonResult result = this.check(userId, tenantId, id);
        if (0 != result.getCode()) {
            log.info("立即执行任务业务：校验参数失败：{}", result.getMsg());
            return result;
        }

        Inspection inspection = (Inspection) result.getData();

        // 立即执行任务
        airportService.executeTask(userId, inspection);

        log.info("立即执行任务业务：立即执行成功：id:{}", inspection.getId());
        return JsonResult.success();
    }

    /**
     * 检查参数
     *     注意：1）、超级管理员不能执行任务
     *          2）、管理员和普通用户只能执行本部门任务，不能执行子部门任务
     * @param id
     * @return
     */
    private JsonResult check(String userId, String tenantId, String id) {
        if (StringUtils.isEmpty(id)) {
            return JsonResult.error(ExecuteInspectionCodeEnum.ID_IS_NULL.getCode(), ExecuteInspectionCodeEnum.ID_IS_NULL.getMsg());
        }
        Inspection inspection = inspectionMapper.selectById(id);
        if (null == inspection) {
            return JsonResult.error(ExecuteInspectionCodeEnum.INSPECTION_IS_NOT_EXIST.getCode(), ExecuteInspectionCodeEnum.INSPECTION_IS_NOT_EXIST.getMsg());
        }

        if (2 == inspection.getExecutionStatus()) {
            return JsonResult.error(ExecuteInspectionCodeEnum.INSPECTION_CANNOT_REPEATED_EXECUTE.getCode(), ExecuteInspectionCodeEnum.INSPECTION_CANNOT_REPEATED_EXECUTE.getMsg());
        }

        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getTenantId, tenantId)
                .eq(User::getId, userId)
                .eq(User::getMark, 1));

        if (!user.getDeptId().equals(inspection.getDeptId())) {
            return JsonResult.error(ExecuteInspectionCodeEnum.USER_ONLY_EXECUTE_DEPARTMENT_TASK.getCode(), ExecuteInspectionCodeEnum.USER_ONLY_EXECUTE_DEPARTMENT_TASK.getMsg());
        }
        return JsonResult.success(inspection);
    }

}
