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

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.tuoheng.admin.entity.Inspection;
import com.tuoheng.admin.entity.InspectionHistory;
import com.tuoheng.admin.entity.Tenant;
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.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 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(id);
        if (0 != result.getCode()) {
            log.info("立即执行任务业务：校验参数失败：{}", result.getMsg());
            return result;
        }

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


        log.info("立即执行任务业务：重新提交任务成功：{}", inspection);
        return JsonResult.success(inspection);
    }

    /**
     * 检查参数
     *
     * @param id
     * @return
     */
    private JsonResult check(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());
        }
        return JsonResult.success(inspection);
    }

    /**
     *
     * 调用机场平台
     *
     * @param tenantId
     * @param inspection
     * @return
     */
    public JsonResult executeTask(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() + "/api/airportInterface/executeTask";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("taskId", inspection.getInspectionLine());
        jsonObject.put("requestId", String.valueOf(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());
        }

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

            return JsonResult.error(jsonResult.getMsg());
        } else {
            return JsonResult.success();
        }
    }

    /**
     *
     * 更新任务中
     *
     * @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);
    }

}
