package com.yeejoin.amos.boot.module.jcs.biz.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.module.common.api.feign.IotFeignClient;
import com.yeejoin.amos.boot.module.jcs.api.dto.AircraftDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.AircraftListTreeDto;
import com.yeejoin.amos.boot.module.jcs.api.entity.Aircraft;
import com.yeejoin.amos.boot.module.jcs.biz.service.impl.AircraftServiceImpl;
import com.yeejoin.amos.boot.module.jcs.biz.service.impl.AlertFormValueServiceImpl;
import com.yeejoin.amos.boot.module.jcs.biz.service.impl.DataSourcesImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import javax.ws.rs.GET;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * 航空器信息
 *
 * @author system_generator
 * @date 2021-06-29
 */
@RestController
@Slf4j
@Api(tags = "航空器信息Api")
@RequestMapping(value = "/aircraft")
public class AircraftController extends BaseController {

    @Autowired
    private AircraftServiceImpl aircraftServiceImpl;
    @Autowired
    DataSourcesImpl dataSourcesImpl;
    @Autowired
    IotFeignClient iotFeignClient;

    @Autowired
    private AlertFormValueServiceImpl iAlertFormValueService;


    /**
     * 新增航空器信息
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/save")
    @ApiOperation(httpMethod = "POST", value = "新增航空器信息", notes = "新增航空器信息")
    public ResponseModel<AircraftDto> save(@RequestBody AircraftDto model) throws Exception {
        if (ValidationUtil.isEmpty(model)
                || ValidationUtil.isEmpty(model.getAircraftModel()))
            throw new BadRequest("参数校验失败.");

        model = aircraftServiceImpl.createAircraft(RequestContext.getAgencyCode(), model);
        return ResponseHelper.buildResponse(model);
    }

    /**
     * 根据sequenceNbr更新
     *
     * @param sequenceNbr 主键
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PutMapping(value = "/{sequenceNbr}")
    @ApiOperation(httpMethod = "PUT", value = "根据sequenceNbr更新航空器信息", notes = "根据sequenceNbr更新航空器信息")
    public ResponseModel<AircraftDto> updateBySequenceNbrAircraft(@RequestBody AircraftDto model,
                                                                  @PathVariable(value = "sequenceNbr") Long sequenceNbr) throws Exception {
        model.setSequenceNbr(sequenceNbr);
        return ResponseHelper.buildResponse(aircraftServiceImpl.updateAircraft(RequestContext.getAgencyCode(), model));
    }




    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping (value = "/select/{num}")
    @ApiOperation(httpMethod = "PUT", value = "根据sequenceNbr更新航空器信息", notes = "根据sequenceNbr更新航空器信息")
    public ResponseModel<Aircraft> selectBySequenceNbrnumAircraft(
                                                                  @PathVariable(value = "num") String num) throws Exception {


        QueryWrapper<Aircraft> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("aircraft_model", num);

        // 警情动态表单数据
        Aircraft aircraft = aircraftServiceImpl.getOne(queryWrapper);


        return ResponseHelper.buildResponse(aircraft);
    }

    /**
     * <pre>
     * 根据物理主键批量删除航空器信息
     * </pre>
     *
     * @param ids
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @DeleteMapping(value = "/batch")
    @ApiOperation(httpMethod = "DELETE", value = "根据物理主键批量删除航空器信息", notes = "根据物理主键批量删除航空器信息")
    public ResponseModel<List<Long>> deleteBySequenceNbr(@RequestParam(value = "ids") String ids) throws Exception {

        return ResponseHelper.buildResponse(aircraftServiceImpl.multDeleteAircraft(RequestContext.getAgencyCode(),
                ids));
    }

    /**
     * 根据sequenceNbr查询
     *
     * @param sequenceNbr 主键
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "findOne/{sequenceNbr}")
    @ApiOperation(httpMethod = "GET", value = "根据sequenceNbr查询单个航空器信息", notes = "根据sequenceNbr查询单个航空器信息")
    public ResponseModel<AircraftDto> seleteOne(@PathVariable Long sequenceNbr) {
        return ResponseHelper.buildResponse(aircraftServiceImpl.queryByAircraftSeq(RequestContext.getAgencyCode(),
                sequenceNbr));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "findOnex/{sequenceNbr}")
    @ApiOperation(httpMethod = "GET", value = "根据sequenceNbr查询单个航空器信息", notes = "根据sequenceNbr查询单个航空器信息")
    public ResponseModel<AircraftDto> seleteOnex(@PathVariable Long sequenceNbr) {
        return ResponseHelper.buildResponse(aircraftServiceImpl.queryByAircraftSeqx(RequestContext.getAgencyCode(),
                sequenceNbr));
    }



    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "aircraftUrlList/{sequenceNbr}")
    @ApiOperation(httpMethod = "GET", value = "根据sequenceNbr查询单个航空器信息", notes = "根据sequenceNbr查询单个航空器信息")
    public ResponseModel<List<Aircraft>> aircraftUrlList(@PathVariable Long sequenceNbr) {
        return ResponseHelper.buildResponse(aircraftServiceImpl.queryByAircraftSeqList(RequestContext.getAgencyCode(),
                sequenceNbr));
    }


    /**
     * 根据sequenceNbr查询
     *
     * @param sequenceNbr 主键
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/{sequenceNbr}")
    @ApiOperation(httpMethod = "GET", value = "查询航空器详情信息", notes = "查询航空器详情信息")
    public ResponseModel<AircraftDto> queryBySeq(@PathVariable Long sequenceNbr) {
        return ResponseHelper.buildResponse(aircraftServiceImpl.queryBySeq(RequestContext.getAgencyCode(),
                sequenceNbr));
    }

    /**
     * 列表分页查询
     *
     * @param current 当前页
     * @param current 每页大小
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/page")
    @ApiOperation(httpMethod = "GET", value = "航空器信息分页查询", notes = "航空器信息分页查询")
    public ResponseModel<Page<AircraftDto>> queryForPage(
            @RequestParam(value = "aircraftModel", required = false) String aircraftModel,
            @RequestParam(value = "engineTypeCode", required = false) String engineTypeCode,
            @RequestParam(value = "fuelTypeCode", required = false) String fuelTypeCode,
            @RequestParam(value = "current") int current,
            @RequestParam(value = "size") int size) {
        Page<AircraftDto> page = new Page<AircraftDto>();
        page.setCurrent(current);
        page.setSize(size);
        return ResponseHelper.buildResponse(aircraftServiceImpl.queryForAircraftPage(page, false, aircraftModel,
                engineTypeCode, fuelTypeCode));
    }


    /**
     * @param
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getAircraft")
    @ApiOperation(httpMethod = "GET", value = "获取航空器型号列表", notes = "获取航空器型号列表")
    public ResponseModel<List<AircraftListTreeDto>> getAircraft() {
        return ResponseHelper.buildResponse(aircraftServiceImpl.getAircraft());
    }

    /**
     * 获取24小时内的航班号
     **/

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getAircraftNum")
    @ApiOperation(httpMethod = "GET", value = "获取24小时内的航班号", notes = "获取24小时内的航班号")
    public ResponseModel<List<Map<String, Object>>> getAircraftNum() {

        ResponseModel<List<Map<String, Object>>> dataModel = iotFeignClient.findImgByFileCategory();
        if (dataModel != null) {
            List<Map<String, Object>> listmap = dataModel.getResult();
            return ResponseHelper.buildResponse(listmap);
        }
        return ResponseHelper.buildResponse(null);
    }

    /**
     * 通过航班号，查询最新的航班信息
     **/
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getAircraftDetails/{num}")
    @ApiOperation(httpMethod = "GET", value = "通过航班号，查询最新的航班信息", notes = "通过航班号，查询最新的航班信息")
    public ResponseModel<Map<String, Object>> getAircraftDetails(@PathVariable String num) {

        Map<String, Object> map1 = new HashedMap();


        ResponseModel<Map<String, Object>> dataModel = iotFeignClient.getDynamicFlightInfo(num);
        if (dataModel != null && dataModel.getResult()!=null) {
            Map<String, Object> map = dataModel.getResult();
                //sonarLint 报错 需要将多次引用的抽成常量
                String dynamicFlightId = "dynamicFlightId";
                String runway = "runway";
                String stand = "stand";
                String passengerCapacity = "passengerCapacity";
                map1.put("aircraftModel", map.containsKey("aircraftType")?map.get("aircraftType"):null);
                map1.put(dynamicFlightId,  map.containsKey(dynamicFlightId)?map.get(dynamicFlightId):null);
                map1.put("landingTime",  map.containsKey("sta")?map.get("sta"):null);
                /* 任务 3488 根据航班号查询航班信息回填  增加跑道,机位字段 start*/
                map1.put(runway,  map.containsKey(runway)?map.get(runway):null);
                map1.put(stand,  map.containsKey(stand)?map.get(stand):null);
                /* 任务 3488 根据航班号查询航班信息回填 end*/
                map1.put(passengerCapacity, map.containsKey(passengerCapacity)?map.get(passengerCapacity):null );

        }
        return ResponseHelper.buildResponse(map1);
    }

    /**
     * 通过航班号，查询最新的航班信息
     **/
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getAircraftDetailsByAlertId/{id}")
    @ApiOperation(httpMethod = "GET", value = "根据灾情id 查询最新的航班信息", notes = "根据灾情id 查询最新的航班信息")
    public ResponseModel<Map<String, Object>> getAircraftDetailsByAlertId(@PathVariable Long id) {
        return ResponseHelper.buildResponse(aircraftServiceImpl.queryAircraftInfo(id));
    }

    /**
     *
     * 导入航空器信息
     *
     * **/
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/ImportData")
    @ApiOperation(httpMethod = "POST", value = "导入航空器信息", notes = "导入航空器信息")
    public Boolean ImportData (@RequestPart MultipartFile multipartFile)  {
        List<Aircraft> aircraftList = new ArrayList<>();
        try {
            EasyExcelFactory.read(multipartFile.getInputStream(), AircraftDto.class, new AnalysisEventListener<AircraftDto>() {
                // 每读取一行就调用该方法
                @Override
                public void invoke(AircraftDto data, AnalysisContext context) {

                    Aircraft aircraft = new Aircraft();
                    BeanUtils.copyProperties(data,aircraft);
                    aircraftList.add(aircraft);
                }
                // 全部读取完成就调用该方法
                @Override
                public void doAfterAllAnalysed(AnalysisContext context) {
                    log.warn("读取完成");
                }
            }).sheet().doRead();
            aircraftServiceImpl.saveBatch(aircraftList);
            return true;
        } catch (Exception e) {
           return false;
        }
    }

    /**
     *
     *
     * @param
     * @return
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/queryAircraftList")
    @ApiOperation(httpMethod = "GET", value = "航空器下拉框", notes = "航空器下拉框")
    public ResponseModel<Object> queryAircraftList() {

        return ResponseHelper.buildResponse(aircraftServiceImpl.queryAircraftList());

    }
}