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

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tuoheng.admin.entity.*;
import com.tuoheng.admin.enums.*;
import com.tuoheng.admin.enums.code.accident.AddAccidentEnum;
import com.tuoheng.admin.mapper.*;
import com.tuoheng.admin.request.accident.AddAccidentRequest;
import com.tuoheng.admin.request.accident.AirportRoute;
import com.tuoheng.admin.utils.AliyunOSSUtil;
import com.tuoheng.admin.utils.CurrentUserUtil;
import com.tuoheng.admin.websocket.WebSocketService;
import com.tuoheng.common.core.common.BaseEntity;
import com.tuoheng.common.core.exception.ServiceException;
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.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.UUID;

/**
 * 添加应急事故业务层处理
 *
 * @author wanjing
 * @team tuoheng
 * @date 2023-04-14
 */
@Slf4j
@Service
public class AddAccidentService {

    @Autowired
    private AccidentMapper accidentMapper;

    @Autowired
    private InspectionMapper inspectionMapper;

    @Autowired
    private AliyunOSSUtil aliyunOSSUtil;

    @Autowired
    private AccidentInspectionMapper accidentInspectionMapper;

    @Autowired
    private AirportLineMapper airportLineMapper;

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private WebSocketService webSocketService;

    @Autowired
    private QuestionTypeMapper questionTypeMapper;

    @Autowired
    private ChannelMapper channelMapper;

    @Autowired
    private LegMapper legMapper;


    /**
     * 添加应急事故
     *
     * @return
     */
    @Transactional
    public JsonResult add(AddAccidentRequest request) {
        log.info("进入添加应急事故业务");
        User user = CurrentUserUtil.getUserInfo();
        String tenantId = user.getTenantId();
        JsonResult result = this.checkParam(user.getId(), tenantId, request);
        if (0 != result.getCode()) {
            log.info("添加任务业务：校验参数失败：{}", result.getMsg());
            return result;
        }
        //构建request对象
        request = this.buildRequest(request, user);
        // 构造accident对象
        Accident accident = this.createAccident(user, tenantId, request);

        //创建应急任务
        Inspection inspection = this.createInspection(user, request);

        //创建航线
        AirportLine airportLine = this.createAirportLine(user, accident.getId(), inspection.getId(), request);

        //创建任务与事故关联表相关
        AccidentInspection accidentInspection = this.createInspectionAccident(accident, inspection, user);

        webSocketService.accidentNotice(accident.getTenantId());

        return JsonResult.success(accident);
    }

    /**
     * 构建request对象
     *
     * @param request
     * @return
     */
    private AddAccidentRequest buildRequest(AddAccidentRequest request, User user) {

        Leg leg = legMapper.selectById(request.getLegId());
        if (StringUtils.isNull(leg)) {
            throw new ServiceException(HttpStatus.BAD_REQUEST.value(), "该航段不存在");
        }
        request.setLegName(leg.getName());
        Channel channel = channelMapper.selectById(request.getChannelId());
        if (StringUtils.isNull(channel)) {
            throw new ServiceException(HttpStatus.BAD_REQUEST.value(), "该航道不存在");
        }
        request.setChannelName(channel.getName());
        Dept dept = deptMapper.selectById(user.getDeptId());
        if (StringUtils.isNull(dept)) {
            throw new ServiceException(HttpStatus.BAD_REQUEST.value(), "该部门不存在");
        }
        request.setDeptName(dept.getName());
        QuestionType questionType = questionTypeMapper.selectOne(Wrappers.<QuestionType>lambdaQuery()
                .eq(QuestionType::getCode, request.getQuestionCode())
                .eq(BaseEntity::getMark, MarkEnum.VALID.getCode()));
        if (StringUtils.isNull(questionType)) {
            throw new ServiceException(HttpStatus.BAD_REQUEST.value(), "该问题类型不存在");
        }
        request.setQuestionName(questionType.getContent());

        return request;

    }

    /**
     * 检查参数
     *
     * @param tenantId
     * @param request
     * @return
     */
    private JsonResult checkParam(String userId, String tenantId, AddAccidentRequest request) {
        if (ObjectUtil.isEmpty(request.getAirportId())) {
            return JsonResult.error(AddAccidentEnum.AIRPORT_IS_FAILED);
        }
        if (StringUtils.isEmpty(request.getDspServiceInstId())) {
            return JsonResult.error(AddAccidentEnum.DSP_IS_FAILED);
        }
        if (StringUtils.isEmpty(request.getQuestionId()) || StringUtils.isEmpty(request.getQuestionCode())) {
            return JsonResult.error("事故不能为空");
        }
        if (StringUtils.isEmpty(request.getChannelId())) {
            return JsonResult.error(AddAccidentEnum.CHANNEL_IS_FAILED);
        }
        if (StringUtils.isEmpty(request.getLegId())) {
            return JsonResult.error(AddAccidentEnum.LEG_IS_FAILED);
        }
        if (StringUtils.isNull(request.getDroneId())) {
            return JsonResult.error("无人机id不能为空");
        }
        return JsonResult.success();
    }

    /**
     * 创建任务与事故关联表相关
     *
     * @param accident
     * @param inspection
     * @param user
     * @return
     */
    private AccidentInspection createInspectionAccident(Accident accident, Inspection inspection, User user) {
        AccidentInspection accidentInspection = new AccidentInspection();
        accidentInspection.setTenantId(user.getTenantId());
        accidentInspection.setAccidentId(accident.getId());
        accidentInspection.setInspectionId(inspection.getId());
        accidentInspection.setCreateUser(user.getId());
        accidentInspection.setName(inspection.getAirportName() + "执行任务");
        accidentInspection.setDroneForwardType(AccidentDroneForwardTypeEnum.NEW_DRONE_FORWARD_BY_MANUAL.getCode());
        int count = accidentInspectionMapper.insert(accidentInspection);
        if (count <= 0) {
            log.info("创建应急任务关联表失败");
            throw new ServiceException("创建应急任务关联表失败");
        }
        return accidentInspection;
    }

    /**
     * 构造Accident对象
     *
     * @param user
     * @param tenantId
     * @param request
     * @return
     */
    private Accident createAccident(User user, String tenantId, AddAccidentRequest request) {
        Accident accident = new Accident();
        accident.setTenantId(tenantId);
        accident.setDeptId(user.getDeptId());
        accident.setDeptName(request.getDeptName());
        accident.setCheckUser(user.getId());
        accident.setChannelCode(request.getChannelCode());
        accident.setSource(AccidentSourceEnum.MANUAL.getCode());
        accident.setStatus(AccidentStatusEnum.UNTREATED.getCode());
        accident.setQuestionId(request.getQuestionId());
        accident.setQuestionCode(request.getQuestionCode());
        accident.setQuestionName(request.getQuestionName());
        accident.setChannelId(request.getChannelId());
        accident.setChannelName(request.getChannelName());
        accident.setLegId(request.getLegId());
        accident.setLegName(request.getLegName());
        accident.setCreateUser(user.getId());
        int rowId = accidentMapper.insert(accident);
        if (rowId <= 0) {
            log.info("创建事故失败");
            throw new ServiceException("创建事故失败");
        }
        return accident;
    }

    /**
     * 创建应急任务
     *
     * @param user
     * @param request
     * @return
     */
    private Inspection createInspection(User user, AddAccidentRequest request) {
        Inspection inspection = new Inspection();
        String code = DateUtils.generateCode("XJRW");
        inspection.setDeptId(user.getDeptId());
        inspection.setTenantId(user.getTenantId());
        inspection.setCode(code);
        inspection.setName("应急任务" + code);
        inspection.setDeptId(user.getDeptId());
        inspection.setTenantId(user.getTenantId());
        inspection.setType(2);
        inspection.setDspServiceInstId(request.getDspServiceInstId());
        inspection.setStatus(InspectionStatusEnum.WAIT_FLIGHT.getCode());  // 设置应急任务状态为待飞行
        inspection.setInspectionType(InspectionTypeEnum.AIRPORT.getCode());
        inspection.setAirportId(request.getAirportId());
        inspection.setDroneId(request.getDroneId());
        inspection.setInspectionLine(0);
        inspection.setInspectionLineName("");
        inspection.setExecutionStartTime(DateUtils.now());
        inspection.setCreateUser(user.getId());
        inspection.setCreateTime(DateUtils.now());
        inspection.setChannelId(request.getChannelId());
        inspection.setChannelName(request.getChannelName());
        inspection.setLegId(request.getLegId());
        inspection.setLegName(request.getLegName());
        inspection.setIsLive(1);
        int count = inspectionMapper.insert(inspection);
        if (count <= 0) {
            log.info("创建应急任务失败");
            throw new ServiceException("创建应急任务失败");
        }
        return inspection;
    }

    /**
     * 创建航线
     *
     * @param user
     * @param request
     * @return
     */
    private AirportLine createAirportLine(User user, String accidentId, String inspectionId, AddAccidentRequest request) {
        AirportLine airportLine = new AirportLine();
        airportLine.setAccidentId(accidentId);
        airportLine.setInspectionId(inspectionId);
        airportLine.setCreateTime(DateUtil.date());
        airportLine.setCreateUser(user.getId());
        airportLine.setTenantId(user.getTenantId());
        airportLine.setLineType(request.getLineType());
        String accidentRegionJsonStr = JSON.toJSONString(request.getAccidentRegionList());
        airportLine.setAccidentRegion(accidentRegionJsonStr);
        String jsonString = JSON.toJSONString(request.getAirportRouteList());
        airportLine.setCoordinates(jsonString);
        airportLine.setOssUrl(this.createPointLineForOss(request.getAirportRouteList()));

        int count = airportLineMapper.insert(airportLine);
        if (count <= 0) {
            log.info("创建航线失败");
            throw new ServiceException("创建航线失败");
        }
        return airportLine;
    }

    /**
     * 生成指点航线
     *
     * @param airportRouteList
     * @return
     */
    public String createPointLineForOss(List<AirportRoute> airportRouteList) {
        String fileUrl = "";
        try {
            String s = "QGC WPL 110\n";
            String tmp = "\t0.00000000\t0.00000000\t0.00000000\t0.00000000\t";
            String tmp16 = "\t0\t3\t16" + tmp;
            String tmp22 = "\t0\t3\t22" + tmp;
            String tmp20 = "\t0\t3\t20" + tmp;
            String end = ".000000\t1\n";
            AirportRoute airportRoute;
            for (int i = 1; i <= airportRouteList.size(); i++) {
                airportRoute = airportRouteList.get(i - 1);
                if (1 == i) {
                    s += i + tmp22;
                } else if (airportRouteList.size() == i) {
                    s += i + tmp20;
                } else {
                    s += i + tmp16;
                }
                s += airportRoute.getLat() + "\t" + airportRoute.getLng() + "\t" + airportRoute.getAltitude() + end;
            }
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            out.write(s.getBytes());
            // 将outputstream转成inputstream
            ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
            String filename = UUID.randomUUID().toString() + ".waypoints";
            aliyunOSSUtil.uploadFile2OSS(in, filename);
            fileUrl = aliyunOSSUtil.getFileUrl(filename);
            out.close();
            in.close();
        } catch (Exception e) {
            log.error("创建航线，上传oss失败", e);
            throw new ServiceException("创建航线，上传oss失败");
        }
        return fileUrl;
    }

}
