package com.weather.modules.weather.dailydata.controller;

import com.weather.common.annotation.LogOperation;
import com.weather.common.constant.Constant;
import com.weather.common.page.PageData;
import com.weather.common.utils.ExcelUtils;
import com.weather.common.utils.Result;
import com.weather.common.validator.AssertUtils;
import com.weather.common.validator.ValidatorUtils;
import com.weather.common.validator.group.AddGroup;
import com.weather.common.validator.group.DefaultGroup;
import com.weather.common.validator.group.UpdateGroup;
import com.weather.modules.weather.dailydata.WeatherDataImportManager;
import com.weather.modules.weather.dailydata.dto.DailyWeatherSummarizeDto;
import com.weather.modules.weather.dailydata.dto.ImportProgress;
import com.weather.modules.weather.dailydata.dto.WeatherDailyDataDto;
import com.weather.modules.weather.dailydata.dto.WeatherDailyDataQueryDto;
import com.weather.modules.weather.dailydata.excel.WeatherDailyDataExcel;
import com.weather.modules.weather.dailydata.service.WeatherDailyDataService;
import com.weather.modules.weather.station.dto.WeatherStationDTO;
import com.weather.modules.weather.station.service.WeatherStationService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.*;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Collectors;


/**
 * 每日气象监测数据表
 *
 * @author 2333 123
 * @since 1.0.0 2026-03-05
 */
@RestController
@RequestMapping("dailyweather/weatherdailydata")
@Tag(name="气象数据")
public class WeatherDailyDataController {

    @Resource
    private WeatherDailyDataService weatherDailyDataService;

    @Resource
    private WeatherStationService weatherStationService;

    @Resource
    private WeatherDataImportManager weatherDataImportManager;

    @GetMapping("page")
    @Operation(summary = "分页")
    @Parameters({
        @Parameter(name = Constant.PAGE, description = "当前页码，从1开始", in = ParameterIn.QUERY, required = true, ref="int") ,
        @Parameter(name = Constant.LIMIT, description = "每页显示记录数", in = ParameterIn.QUERY,required = true, ref="int") ,
        @Parameter(name = Constant.ORDER_FIELD, description = "排序字段", in = ParameterIn.QUERY, ref="String") ,
        @Parameter(name = Constant.ORDER, description = "排序方式，可选值(asc、desc)", in = ParameterIn.QUERY, ref="String")
    })
    @RequiresPermissions("dailyweather:weatherdailydata:page")
    public Result<PageData<WeatherDailyDataDto>> page(@Parameter(hidden = true) @RequestParam Map<String, Object> params){
        PageData<WeatherDailyDataDto> page = weatherDailyDataService.page(params);

        // 批量查询站点名称，避免 N+1 问题
        Set<Long> stationIds = page.getList().stream()
                .map(WeatherDailyDataDto::getStationId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
        if (!stationIds.isEmpty()) {
            Map<Long, WeatherStationDTO> stationMap = weatherStationService.getByStationCodes(stationIds);
            page.getList().forEach(item -> {
                WeatherStationDTO station = stationMap.get(item.getStationId());
                if (station != null) {
                    item.setStationName(station.getStationName());
                }
            });
        }

        return new Result<PageData<WeatherDailyDataDto>>().ok(page);
    }

    @GetMapping("{id}")
    @Operation(summary = "信息")
    @RequiresPermissions("dailyweather:weatherdailydata:info")
    public Result<WeatherDailyDataDto> get(@PathVariable("id") Long id){
        WeatherDailyDataDto data = weatherDailyDataService.get(id);

        return new Result<WeatherDailyDataDto>().ok(data);
    }

    @PostMapping
    @Operation(summary = "保存")
    @LogOperation("保存")
    @RequiresPermissions("dailyweather:weatherdailydata:save")
    public Result save(@RequestBody WeatherDailyDataDto dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);

        weatherDailyDataService.save(dto);

        return new Result();
    }

    @PostMapping("import")
    @Operation(summary = "Excel导入")
    @LogOperation("Excel导入")
    @RequiresPermissions("dailyweather:weatherdailydata:save")
    public Result<Map<String, String>> importExcel(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return new Result<Map<String, String>>().error("上传文件不能为空");
        }
        String taskId = weatherDataImportManager.submitImport(file);
        Map<String, String> data = new HashMap<>();
        data.put("taskId", taskId);
        return new Result<Map<String, String>>().ok(data);
    }

    @GetMapping("import/progress/{taskId}")
    @Operation(summary = "导入进度")
    public Result<ImportProgress> importProgress(@PathVariable("taskId") String taskId) {
        ImportProgress progress = weatherDataImportManager.getProgress(taskId);
        return new Result<ImportProgress>().ok(progress);
    }

    @PutMapping
    @Operation(summary = "修改")
    @LogOperation("修改")
    @RequiresPermissions("dailyweather:weatherdailydata:update")
    public Result update(@RequestBody WeatherDailyDataDto dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);

        weatherDailyDataService.update(dto);

        return new Result();
    }

    @DeleteMapping
    @Operation(summary = "删除")
    @LogOperation("删除")
    @RequiresPermissions("dailyweather:weatherdailydata:delete")
    public Result delete(@RequestBody Long[] ids){
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");

        weatherDailyDataService.delete(ids);

        return new Result();
    }

    @GetMapping("export")
    @Operation(summary = "导出")
    @LogOperation("导出")
    @RequiresPermissions("dailyweather:weatherdailydata:export")
    public void export(@Parameter(hidden = true) @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        List<WeatherDailyDataDto> list = weatherDailyDataService.list(params);

        ExcelUtils.exportExcelToTarget(response, null, "每日气象监测数据表", list, WeatherDailyDataExcel.class);
    }

    @PostMapping("export-sum")
    @Operation(summary = "天气汇总")
    @LogOperation("天气汇总")
    @RequiresPermissions("dailyweather:weatherdailydata:query")
    public Result<List<DailyWeatherSummarizeDto>> dailyWeatherSummarize(@RequestBody WeatherDailyDataQueryDto dto) {

        List<DailyWeatherSummarizeDto> list = weatherDailyDataService.dailyWeatherSummarize(dto);

        return new Result<List<DailyWeatherSummarizeDto>>().ok(list);
    }

}
