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

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.metadata.TableStyle;
import com.alibaba.excel.support.ExcelTypeEnum;
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.biz.common.utils.ExcelUtils;
import com.yeejoin.amos.boot.module.common.api.dto.ExcelDto;
import com.yeejoin.amos.boot.module.common.api.dto.FormValue;
import com.yeejoin.amos.boot.module.common.api.excel.ExcelUtil;
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.AircraftDtos;
import com.yeejoin.amos.boot.module.jcs.api.dto.AircraftListTreeDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.KeyValueLabel;
import com.yeejoin.amos.boot.module.jcs.api.entity.Aircraft;
import com.yeejoin.amos.boot.module.jcs.api.entity.AlertFormValue;
import com.yeejoin.amos.boot.module.jcs.biz.service.impl.AircraftServiceImpl;
import com.yeejoin.amos.boot.module.jcs.biz.service.impl.AlertCalledServiceImpl;
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 org.apache.commons.collections.map.HashedMap;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.slf4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
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.Bean;
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.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;


/**
 * 航空器信息
 *
 * @author system_generator
 * @date 2021-06-29
 */
@RestController
@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));
    }

    /**
     * <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 = "/{sequenceNbr}")
    @ApiOperation(httpMethod = "GET", value = "根据sequenceNbr查询单个航空器信息", notes = "根据sequenceNbr查询单个航空器信息")
    public ResponseModel<AircraftDto> seleteOne(@PathVariable Long sequenceNbr) {
        return ResponseHelper.buildResponse(aircraftServiceImpl.queryByAircraftSeq(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) {
            Map<String, Object> map = dataModel.getResult();
            if (map != null) {
                map1.put("aircraftModel", map.get("aircraftType"));
                map1.put("dynamicFlightId", map.get("dynamicFlightId"));
                map1.put("landingTime", map.get("sta"));
                /* 任务 3488 根据航班号查询航班信息回填  增加跑道,机位字段 start*/
                map1.put("runway", map.get("runway"));
                map1.put("stand", map.get("stand"));
                /* 任务 3488 根据航班号查询航班信息回填 end*/
//    	          map1.put("fuelQuantity", map.get(""));
                map1.put("passengerCapacity", map.get("psgNumTotal"));
            }
        }
        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)
        @GetMapping(value = "/exportData")
    @ApiOperation(httpMethod = "GET", value = "导出航空器信息", notes = "导出航空器信息")
    public void exportData ( HttpServletResponse response)throws IOException {
        String fileName = "Aircraft";
        response.setContentType("multipart/form-data");
        response.setCharacterEncoding("utf-8");
        response.addHeader("Content-Disposition", "attachment;filename=" + fileName+ ".xlsx");
        String sheetName = "航空器信息";
        ExcelWriter writer = new ExcelWriter(response.getOutputStream(), ExcelTypeEnum.XLSX);
        Sheet sheet = new Sheet(1, 0,AircraftDtos.class);
        List<AircraftDto> list = aircraftServiceImpl.queryAircraftDtoForList(false);
        sheet.setSheetName(sheetName);
        writer.write(list, sheet);
        writer.finish();
    }

    /**
     *
     * 导入航空器信息
     *
     * **/
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/ImportData")
    @ApiOperation(httpMethod = "POST", value = "导入航空器信息", notes = "导入航空器信息")
    public Boolean ImportData (@RequestPart MultipartFile multipartFile)  {
        List<Aircraft> aircraftList = new ArrayList<>();
        try {
//            list = ExcelUtil.readFirstSheetExcel(multipartFile, AircraftDto.class, 0);
            EasyExcel.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) {
                    System.out.println("读取完成");
                }
            }).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());

    }
}