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

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tuoheng.admin.conver.InspectionConverMapper;
import com.tuoheng.admin.entity.domain.AirportLine;
import com.tuoheng.admin.entity.domain.DspServiceInst;
import com.tuoheng.admin.entity.domain.Inspection;
import com.tuoheng.admin.entity.domain.User;
import com.tuoheng.admin.entity.request.inspection.AddInspectionRequest;
import com.tuoheng.admin.enums.InspectionStatusEnum;
import com.tuoheng.admin.enums.InspectionTypeEnum;
import com.tuoheng.admin.enums.code.inspection.AddInspectionCodeEnum;
import com.tuoheng.admin.mapper.*;
import com.tuoheng.admin.service.third.pilot.PilotService;
import com.tuoheng.admin.utils.CurrentUserUtil;
import com.tuoheng.admin.utils.GaodeUtil;
import com.tuoheng.common.core.constant.CommonConstants;
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-11-23
 */
@Slf4j
@Service
public class AddInspectionService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private InspectionMapper inspectionMapper;

    @Autowired
    private TenantMapper tenantMapper;

    @Autowired
    private PilotService pilotService;
    @Autowired
    private DspServiceInstMapper dspServiceInstMapper;

    @Autowired
    private AirportLineMapper airportLineMapper;


    /**
     * 添加任务
     *
     * @return
     */
    public JsonResult add(AddInspectionRequest addInspectionRequest) {
        log.info("进入添加任务业务");
        User user = CurrentUserUtil.getUserInfo();
        String userId = user.getId();
        String tenantId = user.getTenantId();
        JsonResult result = this.checkParam(userId, tenantId, addInspectionRequest);
        if (0 != result.getCode()) {
            log.info("添加任务业务：校验参数失败：{}", result.getMsg());
            return result;
        }
        //User user = (User) result.getData();

        // 构造inspection对象
        Inspection inspection = this.buildInspection(user, tenantId, addInspectionRequest);

        // 调用第三方平台
        result = this.callThirdPlatform(user, tenantId, inspection);
//        if (0 != result.getCode()) {
//            log.info("添加任务业务：对接第三方平台失败：{}", result.getMsg());
//            return result;
//        }
        //保存任务
        Integer rowId = inspectionMapper.insert(inspection);
        log.info("添加任务, 返回结果: rowId={}", rowId);
        if (rowId <= 0) {
            log.info("添加任务业务：添加任务失败：{}", result.getMsg());
            return JsonResult.error(AddInspectionCodeEnum.ADD_IS_FAILED.getCode(), AddInspectionCodeEnum.ADD_IS_FAILED.getMsg());
        }
        log.info("添加任务业务：添加任务成功：{}", inspection);

        //判断是机场巡逻的任务,航线数据关联任务id
        if(inspection.getInspectionType() == 2){
            log.info("查询巡检任务对应新增航线");
            Integer inspectionLine = inspection.getInspectionLine();
            if(null != inspectionLine){
                AirportLine airportLine = airportLineMapper.selectOne(Wrappers.<AirportLine>lambdaQuery()
                        .eq(AirportLine::getInspectionLineId, inspectionLine));
                if(ObjectUtil.isNotEmpty(airportLine)){
                    airportLine.setInspectionId(inspection.getId());
                    log.info("航线对应的任务id添加成功");
                }
            }
        }
        return JsonResult.success(inspection);
    }

    /**
     * 检查参数
     *
     * @param tenantId
     * @param addInspectionRequest
     * @return
     */
    private JsonResult checkParam(String userId, String tenantId, AddInspectionRequest addInspectionRequest) {
        if (StringUtils.isEmpty(addInspectionRequest.getName())) {
            return JsonResult.error(AddInspectionCodeEnum.NAME_IS_NULL.getCode(), AddInspectionCodeEnum.NAME_IS_NULL.getMsg());
        }
        if(null == addInspectionRequest.getInspectionType()){
            return JsonResult.error(AddInspectionCodeEnum.INSPECTION_TYPE_IS_NULL.getCode(),AddInspectionCodeEnum.INSPECTION_TYPE_IS_NULL.getMsg());
        }
        if (InspectionTypeEnum.AIRPORT.getCode() == addInspectionRequest.getInspectionType()) {
            // 巡检方式：机场巡逻，可选择巡检机场和巡检路线
            if (null == addInspectionRequest.getAirportId() || StringUtils.isEmpty(addInspectionRequest.getAirportName())) {
                return JsonResult.error(AddInspectionCodeEnum.AIRPORT_IS_NULL.getCode(), AddInspectionCodeEnum.AIRPORT_IS_NULL.getMsg());
            }

            if (null == addInspectionRequest.getInspectionLine() || StringUtils.isEmpty(addInspectionRequest.getInspectionLineName())) {
                return JsonResult.error(AddInspectionCodeEnum.INSPECTION_LINE_IS_NULL.getCode(), AddInspectionCodeEnum.INSPECTION_LINE_IS_NULL.getMsg());
            }
            if(StringUtils.isEmpty(addInspectionRequest.getFlyHeight())){
                return JsonResult.error(AddInspectionCodeEnum.FLY_HEIGHT_IS_NULL.getCode(),AddInspectionCodeEnum.FLY_HEIGHT_IS_NULL.getMsg());
            }
        } else if (InspectionTypeEnum.MABNNEDFLIGHT.getCode() == addInspectionRequest.getInspectionType()) {
            // 巡检方式：飞手值飞，可选择是否直播，起点坐标，终点坐标
//            if (null == addInspectionRequest.getIsLive()) {
//                return JsonResult.error(AddInspectionCodeEnum.LIVE_IS_NULL.getCode(), AddInspectionCodeEnum.LIVE_IS_NULL.getMsg());
//            }
            if (StringUtils.isEmpty(addInspectionRequest.getStartLongitude())) {
                return JsonResult.error(AddInspectionCodeEnum.START_LONGITUDE_IS_NULL.getCode(), AddInspectionCodeEnum.START_LONGITUDE_IS_NULL.getMsg());
            }
            if (StringUtils.isEmpty(addInspectionRequest.getStartLatitude())) {
                return JsonResult.error(AddInspectionCodeEnum.START_LATITUDE_IS_NULL.getCode(), AddInspectionCodeEnum.START_LATITUDE_IS_NULL.getMsg());
            }
            if (StringUtils.isEmpty(addInspectionRequest.getEndLongitude())) {
                return JsonResult.error(AddInspectionCodeEnum.END_LONGITUDE_IS_NULL.getCode(), AddInspectionCodeEnum.END_LONGITUDE_IS_NULL.getMsg());
            }
            if (StringUtils.isEmpty(addInspectionRequest.getEndLatitude())) {
                return JsonResult.error(AddInspectionCodeEnum.END_LATITUDE_IS_NULL.getCode(), AddInspectionCodeEnum.END_LATITUDE_IS_NULL.getMsg());
            }
//            if(StringUtils.isEmpty(addInspectionRequest.getNote())){
//                return JsonResult.error(AddInspectionCodeEnum.INSPECTION_NOTE_IS_NOT_EXIST.getCode(),AddInspectionCodeEnum.INSPECTION_NOTE_IS_NOT_EXIST.getMsg());
//            }
        }
        if (null == addInspectionRequest.getInspectionTime()) {
            return JsonResult.error(AddInspectionCodeEnum.INSPECTION_TIME_IS_NULL.getCode(), AddInspectionCodeEnum.INSPECTION_TIME_IS_NULL.getMsg());
        }
        return JsonResult.success();
    }

    /**
     * 构造Inspection对象
     *
     * @param user
     * @param tenantId
     * @param addInspectionRequest
     * @return
     */
    private Inspection buildInspection(User user, String tenantId, AddInspectionRequest addInspectionRequest) {
        Inspection inspection = InspectionConverMapper.INSTANCE.fromAddInspectionRequestToInspection(addInspectionRequest);
        //Inspection inspection = new Inspection();
        //BeanUtils.copyProperties(addInspectionRequest,inspection);
        String code = DateUtils.generateCode("XJRW");
        inspection.setType(1);
        inspection.setCode(code);
        inspection.setTenantId(tenantId);
        inspection.setCreateUser(user.getId());
        inspection.setCreateTime(DateUtils.now());
        inspection.setMobile(user.getMobile());
        inspection.setStatus(InspectionStatusEnum.WAIT_FLIGHT.getCode());
        if (StringUtils.isEmpty(addInspectionRequest.getDspServiceInstId())) {
            //提供默认服务实例id
            DspServiceInst dspServiceInst = dspServiceInstMapper.selectOne(Wrappers.<DspServiceInst>lambdaQuery()
                    .eq(DspServiceInst::getIsDefault, CommonConstants.ONE));
            inspection.setDspServiceInstId(dspServiceInst.getDspServiceInstId());
        }
        if (InspectionTypeEnum.AIRPORT.getCode() == addInspectionRequest.getInspectionType()) {
            // 机场巡逻，只有直播，将isLive设置为1
            inspection.setIsLive(1);
        }
        return 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();
    }

    /**
     * 对接高德地图平台：将经纬度转换成巡逻地点
     * 1)、飞手值飞才有经纬度
     * 2）、机场巡逻没有经纬度，因此也不需要查看巡逻地点
     *
     * @return
     */
    private JsonResult callGaode(Inspection inspection) {
        if (InspectionTypeEnum.AIRPORT.getCode() == inspection.getInspectionType()) {
            return JsonResult.success();
        }
        String patrolLocation = GaodeUtil.getGaodeAddress(inspection.getStartLongitude(), inspection.getStartLatitude());
        if (StringUtils.isEmpty(patrolLocation)) {
            log.info("调用高德接口返回地址为空");
            return JsonResult.error(AddInspectionCodeEnum.CALL_AMAP_IS_FAILED.getCode(), AddInspectionCodeEnum.CALL_AMAP_IS_FAILED.getMsg());
        }
        inspection.setPatrolLocation(patrolLocation);
        return JsonResult.success();
    }

}
