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.utils.ShiroUtils;
import com.tuoheng.common.core.utils.*;
import lombok.Data;
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;

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

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

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

        // 立即执行任务
        this.executeTask(userId, tenantId, 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());
        }

        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);
    }

    /**
     * 调用机场平台
     *
     * @param tenantId
     * @param inspection
     * @return
     */
    public JsonResult executeTask(String userId, String tenantId, Inspection inspection) {
        //读取不同租户的机场平台url
        Tenant tenant = tenantMapper.selectById(inspection.getTenantId());
        if (ObjectUtil.isEmpty(tenant)) {
            return JsonResult.error(ExecuteInspectionCodeEnum.TENANT_IS_NOT_EXIST.getCode(), ExecuteInspectionCodeEnum.TENANT_IS_NOT_EXIST.getMsg());
        }

        if (StringUtils.isEmpty(tenant.getAirportUrl())) {
            return JsonResult.error(ExecuteInspectionCodeEnum.AIRPORT_URL_IS_NULL.getCode(), ExecuteInspectionCodeEnum.AIRPORT_URL_IS_NULL.getMsg());
        }

        String url = tenant.getAirportUrl() + SystemConstant.API_AIRPORT_EXECUTE_TASK;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("taskId", inspection.getInspectionLine());
        jsonObject.put("requestId", inspection.getId());

        String airPortStr = HttpUtils.doSend(url, jsonObject, null, "POST");
        if (StringUtils.isEmpty(airPortStr)) {
            log.info("立即执行任务业务：机场接口返回数据为空，任务id：{}，任务名称：{}，机场id：{}，机场名称：{}， 路线id：{}，路线名称：{}",
                    inspection.getId(), inspection.getName(), inspection.getAirportId(), inspection.getAirportName(), inspection.getInspectionLine(), inspection.getInspectionLineName());
            return JsonResult.error(ExecuteInspectionCodeEnum.AIRPORT_RETURN_DATA_IS_NULL.getCode(), ExecuteInspectionCodeEnum.AIRPORT_RETURN_DATA_IS_NULL.getMsg());
        }

        this.updateInspection(userId, inspection);

        JsonResult jsonResult = JacksonUtil.json2pojo(airPortStr, JsonResult.class);
        if (jsonResult.getCode() != 0) {
            log.info("立即执行任务业务：机场接口返回结果：失败：{}", jsonResult.getMsg());
            this.insertInspectionHistory(userId, tenantId, inspection, jsonResult.getMsg());
            return JsonResult.error(jsonResult.getMsg());
        } else {
            return JsonResult.success();
        }
    }

    /**
     * 修改任务执行状态
     *
     * @param userId
     * @param inspection
     */
    private void updateInspection(String userId, Inspection inspection) {
        inspection.setExecutionStatus(2);
        inspection.setUpdateUser(userId);
        inspection.setUpdateTime(DateUtils.now());
        inspectionMapper.update(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);
    }

}
