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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tuoheng.admin.conver.InspectionConverMapper;
import com.tuoheng.admin.entity.*;
import com.tuoheng.admin.enums.InspectionStatusEnum;
import com.tuoheng.admin.enums.InspectionTypeEnum;
import com.tuoheng.admin.enums.MarkEnum;
import com.tuoheng.admin.enums.code.inspection.ResubmitInspectionCodeEnum;
import com.tuoheng.admin.mapper.*;
import com.tuoheng.admin.request.inspection.EditInspectionRequest;
import com.tuoheng.admin.service.third.pilot.PilotService;
import com.tuoheng.admin.utils.CurrentUserUtil;
import com.tuoheng.common.core.utils.DateUtils;
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;

/**
 * 重新提交任务业务层处理
 *
 * @author wanjing
 * @team tuoheng
 * @date 2022-12-01
 */
@Slf4j
@Service
public class ResubmitInspectionService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private ChannelMapper channelMapper;

    @Autowired
    private LegMapper legMapper;

    @Autowired
    private InspectionMapper inspectionMapper;

    @Autowired
    private PilotService pilotService;

    /**
     * 重新提交任务
     *
     * @return
     */
    public JsonResult resubmit(EditInspectionRequest request) {
        log.info("进入重新提交任务业务");
        User user = CurrentUserUtil.getUserInfo();
        String tenantId = user.getTenantId();
        JsonResult result = this.checkParam(tenantId, request);
        if (0 != result.getCode()) {
            log.info("重新提交任务业务：校验参数失败：{}", result.getMsg());
            return result;
        }
        Inspection inspectionOld = (Inspection) result.getData();

        // 构造inspection对象
        result = this.buildInspection(user, tenantId, request, inspectionOld);
        if (0 != result.getCode()) {
            log.info("重新提交任务业务：构建inspection对象失败：{}", result.getMsg());
            return result;
        }
        Inspection inspection = (Inspection) result.getData();

        // 调用第三方平台
        result = this.callThirdPlatform(user, tenantId, inspection);
        if (0 != result.getCode()) {
            log.info("重新提交任务业务：对接第三方平台失败：{}", result.getMsg());
            return result;
        }
        Integer rowId = inspectionMapper.insert(inspection);
        log.info("重新提交任务, 返回结果: deptId={}", rowId);
        if (rowId <= 0) {
            log.info("重新提交任务业务：重新提交任务失败：{}", result.getMsg());
            return JsonResult.error(ResubmitInspectionCodeEnum.RESUBMIT_IS_FAILED.getCode(), ResubmitInspectionCodeEnum.RESUBMIT_IS_FAILED.getMsg());
        }
        log.info("重新提交任务业务：重新提交任务成功：{}", inspection);
        return JsonResult.success(inspection);
    }

    /**
     * 检查参数
     * @param tenantId
     * @param request
     * @return
     */
    private JsonResult checkParam(String tenantId, EditInspectionRequest request) {
        if (StringUtils.isEmpty(request.getId())) {
            return JsonResult.error(ResubmitInspectionCodeEnum.ID_IS_NULL.getCode(), ResubmitInspectionCodeEnum.ID_IS_NULL.getMsg());
        }

        if (StringUtils.isEmpty(request.getName())) {
            return JsonResult.error(ResubmitInspectionCodeEnum.NAME_IS_NULL.getCode(), ResubmitInspectionCodeEnum.NAME_IS_NULL.getMsg());
        }
        if (null == request.getType()) {
            return JsonResult.error(ResubmitInspectionCodeEnum.TYPE_IS_NULL.getCode(), ResubmitInspectionCodeEnum.TYPE_IS_NULL.getMsg());
        }
        if (null == request.getInspectionType()) {
            return JsonResult.error(ResubmitInspectionCodeEnum.INSPECTION_TYPE_IS_NULL.getCode(), ResubmitInspectionCodeEnum.INSPECTION_TYPE_IS_NULL.getMsg());
        }
        if (null == request.getChannelId() || StringUtils.isEmpty(request.getChannelName())) {
            return JsonResult.error(ResubmitInspectionCodeEnum.ROAD_IS_NULL.getCode(), ResubmitInspectionCodeEnum.ROAD_IS_NULL.getMsg());
        }

        if (null == request.getLegId() || StringUtils.isEmpty(request.getLegName())) {
            return JsonResult.error(ResubmitInspectionCodeEnum.SECTION_IS_NULL.getCode(), ResubmitInspectionCodeEnum.SECTION_IS_NULL.getMsg());
        }
        if (InspectionTypeEnum.AIRPORT.getCode() == request.getInspectionType()) {
            // 巡检方式：机场巡逻，可选择巡检机场和巡检路线
            if (null == request.getAirportId() || StringUtils.isEmpty(request.getAirportName())) {
                return JsonResult.error(ResubmitInspectionCodeEnum.AIRPORT_IS_NULL.getCode(), ResubmitInspectionCodeEnum.AIRPORT_IS_NULL.getMsg());
            }
            if (null == request.getInspectionLine() || StringUtils.isEmpty(request.getInspectionLineName())) {
                return JsonResult.error(ResubmitInspectionCodeEnum.INSPECTION_LINE_IS_NULL.getCode(), ResubmitInspectionCodeEnum.INSPECTION_LINE_IS_NULL.getMsg());
            }
        } else if (InspectionTypeEnum.MABNNEDFLIGHT.getCode() == request.getInspectionType()) {
            // 巡检方式：飞手值飞，可选择是否直播，起点坐标，终点坐标
            if (null == request.getIsLive()) {
                return JsonResult.error(ResubmitInspectionCodeEnum.LIVE_IS_NULL.getCode(), ResubmitInspectionCodeEnum.LIVE_IS_NULL.getMsg());
            }
            if (StringUtils.isEmpty(request.getStartLongitude())) {
                return JsonResult.error(ResubmitInspectionCodeEnum.START_LONGITUDE_IS_NULL.getCode(), ResubmitInspectionCodeEnum.START_LONGITUDE_IS_NULL.getMsg());
            }
            if (StringUtils.isEmpty(request.getStartLatitude())) {
                return JsonResult.error(ResubmitInspectionCodeEnum.START_LATITUDE_IS_NULL.getCode(), ResubmitInspectionCodeEnum.START_LATITUDE_IS_NULL.getMsg());
            }
            if (StringUtils.isEmpty(request.getEndLongitude())) {
                return JsonResult.error(ResubmitInspectionCodeEnum.END_LONGITUDE_IS_NULL.getCode(), ResubmitInspectionCodeEnum.END_LONGITUDE_IS_NULL.getMsg());
            }
            if (StringUtils.isEmpty(request.getEndLatitude())) {
                return JsonResult.error(ResubmitInspectionCodeEnum.END_LATITUDE_IS_NULL.getCode(), ResubmitInspectionCodeEnum.END_LATITUDE_IS_NULL.getMsg());
            }
        }

        if (null == request.getInspectionTime()) {
            return JsonResult.error(ResubmitInspectionCodeEnum.INSPECTION_TIME_IS_NULL.getCode(), ResubmitInspectionCodeEnum.INSPECTION_TIME_IS_NULL.getMsg());
        }

        Inspection inspectionOld = inspectionMapper.selectById(request.getId());
        if (null == inspectionOld) {
            return JsonResult.error(ResubmitInspectionCodeEnum.INSPECTION_IS_NOT_EXIST.getCode(), ResubmitInspectionCodeEnum.INSPECTION_IS_NOT_EXIST.getMsg());
        }

        if (inspectionOld.getStatus() != InspectionStatusEnum.FLIGHT_FAILED.getCode()) {
            return JsonResult.error(ResubmitInspectionCodeEnum.FAILED_INSPECTION_CANNOT_RESUBMIT.getCode(), ResubmitInspectionCodeEnum.FAILED_INSPECTION_CANNOT_RESUBMIT.getMsg());
        }

        if (inspectionOld.getType() != request.getType()) {
            return JsonResult.error(ResubmitInspectionCodeEnum.TYPE_IS_NOT_EDIT.getCode(), ResubmitInspectionCodeEnum.TYPE_IS_NOT_EDIT.getMsg());
        }

        if (inspectionOld.getInspectionType() != request.getInspectionType()) {
            return JsonResult.error(ResubmitInspectionCodeEnum.INSPECTION_TYPE_IS_NOT_EDIT.getCode(), ResubmitInspectionCodeEnum.INSPECTION_TYPE_IS_NOT_EDIT.getMsg());
        }

        Integer count = channelMapper.selectCount(Wrappers.<Channel>lambdaQuery()
                                .eq(Channel::getTenantId, tenantId)
                                .eq(Channel::getId, request.getChannelId())
                                .eq(Channel::getMark, MarkEnum.VALID.getCode()));

        if (count <= 0) {
            return JsonResult.error(ResubmitInspectionCodeEnum.ROAD_IS_NOT_EXIST.getCode(), ResubmitInspectionCodeEnum.ROAD_IS_NOT_EXIST.getMsg());
        }

        count = legMapper.selectCount(Wrappers.<Leg>lambdaQuery()
                                .eq(Leg::getTenantId, tenantId)
                                .eq(Leg::getId, request.getLegId())
                                .eq(Leg::getMark, MarkEnum.VALID.getCode()));
        if (count <= 0) {
            return JsonResult.error(ResubmitInspectionCodeEnum.SECTION_IS_NOT_EXIST.getCode(), ResubmitInspectionCodeEnum.SECTION_IS_NOT_EXIST.getMsg());
        }
        return JsonResult.success(inspectionOld);
    }

    /**
     *
     *  构造Inspection对象
     *
     * @param user
     * @param tenantId
     * @param request
     * @return
     */
    private JsonResult buildInspection(User user, String tenantId, EditInspectionRequest request, Inspection inspectionOld) {
        Dept dept = deptMapper.selectOne(new LambdaQueryWrapper<Dept>()
                .eq(Dept::getTenantId, tenantId)
                .eq(Dept::getId, user.getDeptId())
                .eq(Dept::getMark, MarkEnum.VALID.getCode()));
        if (null == dept) {
            return JsonResult.error(ResubmitInspectionCodeEnum.DEPT_IS_NOT_EXIST.getCode(), ResubmitInspectionCodeEnum.DEPT_IS_NOT_EXIST.getMsg());
        }
        Inspection inspection = InspectionConverMapper.INSTANCE.fromEditInspectionRequestToInspection(request);
        String code = DateUtils.generateCode("XJRW");
        inspection.setCode(code);
        inspection.setId("");
        inspection.setTenantId(tenantId);
        inspection.setDeptId(dept.getId());
        inspection.setCreateUser(user.getId());
        inspection.setCreateTime(DateUtils.now());
        inspection.setMobile(user.getMobile());
        inspection.setDspServiceInstId(inspectionOld.getDspServiceInstId());
        inspection.setStatus(InspectionStatusEnum.WAIT_FLIGHT.getCode());  // 重新提交，状态设置为等待飞行
        return JsonResult.success(inspection);
    }

    /**
     *  与第三方平台（飞手、高德）对接
     *
     * @param user
     * @param tenantId
     * @param inspection
     * @return
     */
    private JsonResult callThirdPlatform(User user, String tenantId, Inspection inspection) {
        // 对接高德地图
        JsonResult result = this.callGaode(inspection);
        if (0 != result.getCode()) {
            return result;
        }

        if (InspectionTypeEnum.MABNNEDFLIGHT.getCode() == inspection.getInspectionType()) {
            // 对接飞手平台
            result = pilotService.addTask(user, inspection);
            if (0 != result.getCode()) {
                return result;
            }
        }
        return JsonResult.success();
    }

    /**
     *
     * 对接高德地图平台：将经纬度转换成巡逻地点
     *
     * @return
     */
    private JsonResult callGaode(Inspection inspection) {
        // 经纬度转换成巡逻地点
        // 接口暂未调通，直接返回成功
//        String patrolLocation = GaodeUtil.getGaodeAddress(inspection.getStartLongitude(), inspection.getStartLatitude());
//        if (StringUtils.isEmpty(patrolLocation)) {
//            return JsonResult.error(ResubmitInspectionCodeEnum.CALL_AMAP_IS_FAILED.getCode(), ResubmitInspectionCodeEnum.CALL_AMAP_IS_FAILED.getMsg());
//        }
//        inspection.setPatrolLocation(patrolLocation);
        return JsonResult.success();
    }

}
