package com.corewing.app.modules.app;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.corewing.app.common.Result;
import com.corewing.app.common.annotation.CommonLog;
import com.corewing.app.entity.AatVersion;
import com.corewing.app.service.AatVersionService;
import com.corewing.app.util.I18nUtil;
import com.corewing.app.util.OSSUploadUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * AAT固件版本 Controller
 */
@Api(tags = "AAT固件版本接口")
@RestController
@RequestMapping("/aat_version")
public class AppAatVersionController {

    private final AatVersionService aatVersionService;

    public AppAatVersionController(AatVersionService aatVersionService) {
        this.aatVersionService = aatVersionService;
    }

    /**
     * 查询所有类型的最新固件版本（返回与原始JSON结构一致）
     */
    @CommonLog("查询所有AAT最新固件版本")
    @ApiOperation("查询所有AAT最新固件版本")
    @GetMapping("/latest")
    public Result<Map<String, Object>> getAllLatestVersions() {
        return Result.success(aatVersionService.getAllLatestVersions());
    }

    /**
     * 根据固件类型查询最新版本
     */
    @CommonLog("根据类型查询AAT最新固件版本")
    @ApiOperation("根据类型查询AAT最新固件版本")
    @GetMapping("/latest/{firmwareType}")
    public Result<AatVersion> getLatestByType(@PathVariable String firmwareType) {
        AatVersion version = aatVersionService.getLatestByType(firmwareType);
        if (version != null) {
            return Result.success(version);
        }
        return Result.error(I18nUtil.getMessage("firmware.not.found"));
    }

    /**
     * 根据固件类型查询版本列表
     */
    @CommonLog("根据类型查询AAT固件版本列表")
    @ApiOperation("根据类型查询AAT固件版本列表")
    @GetMapping("/type/{firmwareType}")
    public Result<List<AatVersion>> listByType(@PathVariable String firmwareType) {
        QueryWrapper<AatVersion> wrapper = new QueryWrapper<>();
        wrapper.eq("firmware_type", firmwareType);
        wrapper.orderByDesc("create_time");
        return Result.success(aatVersionService.list(wrapper));
    }

    /**
     * 分页查询固件版本列表
     */
    @CommonLog("分页查询AAT固件版本列表")
    @ApiOperation("分页查询AAT固件版本列表")
    @GetMapping("/page")
    public Result<IPage<AatVersion>> page(
            @RequestParam(defaultValue = "1") Long current,
            @RequestParam(defaultValue = "10") Long size,
            @RequestParam(required = false) String firmwareType,
            @RequestParam(required = false) String firmwareName) {

        Page<AatVersion> page = new Page<>(current, size);
        QueryWrapper<AatVersion> wrapper = new QueryWrapper<>();

        if (StringUtils.hasText(firmwareType)) {
            wrapper.eq("firmware_type", firmwareType);
        }
        if (StringUtils.hasText(firmwareName)) {
            wrapper.like("firmware_name", firmwareName);
        }
        wrapper.orderByDesc("create_time");

        return Result.success(aatVersionService.page(page, wrapper));
    }

    /**
     * 查询所有固件版本
     */
    @CommonLog("查询所有AAT固件版本")
    @ApiOperation("查询所有AAT固件版本")
    @GetMapping("/list")
    public Result<List<AatVersion>> list() {
        return Result.success(aatVersionService.list());
    }

    /**
     * 根据ID查询固件版本
     */
    @CommonLog("根据ID查询AAT固件版本")
    @ApiOperation("根据ID查询AAT固件版本")
    @GetMapping("/{id}")
    public Result<AatVersion> getById(@PathVariable Long id) {
        AatVersion version = aatVersionService.getById(id);
        if (version != null) {
            return Result.success(version);
        }
        return Result.error(I18nUtil.getMessage("firmware.not.found"));
    }

    /**
     * 新增固件版本
     */
    @CommonLog("新增AAT固件版本")
    @ApiOperation("新增AAT固件版本")
    @PostMapping
    public Result<AatVersion> add(@RequestBody AatVersion aatVersion) {
        boolean saved = aatVersionService.save(aatVersion);
        return saved ? Result.success(aatVersion) : Result.error();
    }

    /**
     * 修改固件版本
     */
    @CommonLog("修改AAT固件版本")
    @ApiOperation("修改AAT固件版本")
    @PutMapping
    public Result<Void> update(@RequestBody AatVersion aatVersion) {
        return Result.isBool(aatVersionService.updateById(aatVersion));
    }

    /**
     * 删除固件版本
     */
    @CommonLog("删除AAT固件版本")
    @ApiOperation("删除AAT固件版本")
    @DeleteMapping("/{id}")
    public Result<Void> delete(@PathVariable Long id) {
        AatVersion version = aatVersionService.getById(id);
        if (version == null) {
            return Result.error(I18nUtil.getMessage("firmware.not.found"));
        }
        // 删除OSS上的文件
        if (StringUtils.hasText(version.getDownloadUrl())) {
            String objectName = version.getDownloadUrl().replace("https://oss.corewing.com/", "");
            OSSUploadUtil.deleteFile(objectName);
        }
        return Result.isBool(aatVersionService.removeById(id));
    }

    /**
     * 上传固件文件
     */
    @CommonLog("上传AAT固件文件")
    @ApiOperation("上传AAT固件文件")
    @PostMapping("/upload/{id}")
    public Result<AatVersion> upload(@PathVariable Long id, @RequestParam("file") MultipartFile file) {
        AatVersion version = aatVersionService.getById(id);
        if (version == null) {
            return Result.error(I18nUtil.getMessage("firmware.not.found"));
        }
        try {
            String objectName = "aat_firmware/" + file.getOriginalFilename();
            String downloadUrl = OSSUploadUtil.uploadFile(file.getInputStream(), objectName);
            version.setDownloadUrl(downloadUrl);
            version.setFirmwareSize(file.getSize());
            version.setFirmwareName(file.getOriginalFilename());
            aatVersionService.updateById(version);
            return Result.success(version);
        } catch (IOException e) {
            return Result.error("上传失败: " + e.getMessage());
        }
    }
}
