package com.corewing.app.controller;

import cn.dev33.satoken.stp.StpUtil;
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.dto.CreateParamRequest;
import com.corewing.app.dto.UpdateParamRequest;
import com.corewing.app.entity.ParamsCenter;
import com.corewing.app.service.ParamsCenterService;
import com.corewing.app.util.I18nUtil;
import com.corewing.app.vo.ParamsCenterVO;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 参数配置中心 Controller
 */
@RestController
@RequestMapping("/params")
public class ParamsCenterController {

    private final ParamsCenterService paramsService;

    public ParamsCenterController(ParamsCenterService paramsService) {
        this.paramsService = paramsService;
    }

    /**
     * 创建参数配置
     */
    @PostMapping
    public Result<String> create(@Valid @RequestBody CreateParamRequest request) {
        try {
            Long userId = StpUtil.getLoginIdAsLong();

            ParamsCenter params = new ParamsCenter();
            params.setUserId(userId);
            params.setParamName(request.getParamName());
            params.setDeviceName(request.getDeviceName());
            params.setDescription(request.getDescription());
            params.setFcModel(request.getFcModel());
            params.setFcType(request.getFcType());
            params.setParamVersion(request.getParamVersion());
            params.setParamDetail(request.getParamDetail());
            params.setDownloadCount(0); // 初始化下载次数为0

            boolean success = paramsService.save(params);
            if (success) {
                return Result.success(I18nUtil.getMessage("params.create.success"));
            }
            return Result.error(I18nUtil.getMessage("params.create.failed"));
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 更新参数配置
     */
    @PutMapping
    public Result<String> update(@Valid @RequestBody UpdateParamRequest request) {
        try {
            Long userId = StpUtil.getLoginIdAsLong();

            // 先查询参数是否存在且属于当前用户
            ParamsCenter existingParam = paramsService.getById(request.getId());
            if (existingParam == null) {
                return Result.error(I18nUtil.getMessage("params.not.found"));
            }
            if (!existingParam.getUserId().equals(userId)) {
                return Result.error(I18nUtil.getMessage("params.no.permission"));
            }

            ParamsCenter params = new ParamsCenter();
            params.setId(request.getId());
            params.setParamName(request.getParamName());
            params.setDeviceName(request.getDeviceName());
            params.setDescription(request.getDescription());
            params.setFcModel(request.getFcModel());
            params.setFcType(request.getFcType());
            params.setParamVersion(request.getParamVersion());
            params.setParamDetail(request.getParamDetail());

            boolean success = paramsService.updateById(params);
            if (success) {
                return Result.success(I18nUtil.getMessage("params.update.success"));
            }
            return Result.error(I18nUtil.getMessage("params.update.failed"));
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 删除参数配置
     */
    @DeleteMapping("/{id}")
    public Result<String> delete(@PathVariable Long id) {
        try {
            Long userId = StpUtil.getLoginIdAsLong();

            // 先查询参数是否存在且属于当前用户
            ParamsCenter existingParam = paramsService.getById(id);
            if (existingParam == null) {
                return Result.error(I18nUtil.getMessage("params.not.found"));
            }
            if (!existingParam.getUserId().equals(userId)) {
                return Result.error(I18nUtil.getMessage("params.no.permission"));
            }

            boolean success = paramsService.removeById(id);
            if (success) {
                return Result.success(I18nUtil.getMessage("params.delete.success"));
            }
            return Result.error(I18nUtil.getMessage("params.delete.failed"));
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 根据ID查询参数配置
     */
    @GetMapping("/{id}")
    public Result<ParamsCenterVO> getById(@PathVariable Long id) {
        try {
            Long userId = StpUtil.getLoginIdAsLong();

            ParamsCenterVO params = paramsService.getVOById(id);
            if (params == null) {
                return Result.error(I18nUtil.getMessage("params.not.found"));
            }
            if (!params.getUserId().equals(userId)) {
                return Result.error(I18nUtil.getMessage("params.no.permission"));
            }

            return Result.success(params);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 查询所有参数列表（公开接口，支持飞控型号过滤）
     */
    @GetMapping("/all/list")
    public Result<List<ParamsCenterVO>> listAll(@RequestParam(required = false) String fcModel) {
        try {
            List<ParamsCenterVO> list = paramsService.listAllByFcModel(fcModel);
            return Result.success(list);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 查询当前用户的参数列表（支持飞控型号过滤）
     */
    @GetMapping("/my/list")
    public Result<List<ParamsCenterVO>> listMy(@RequestParam(required = false) String fcModel) {
        try {
            Long userId = StpUtil.getLoginIdAsLong();
            List<ParamsCenterVO> list = paramsService.listByUserIdAndFcModel(userId, fcModel);
            return Result.success(list);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 分页查询所有参数列表（公开接口，支持飞控型号过滤）
     */
    @GetMapping("/all/page")
    public Result<IPage<ParamsCenterVO>> pageAll(
            @RequestParam(defaultValue = "1") Long current,
            @RequestParam(defaultValue = "10") Long size,
            @RequestParam(required = false) String fcModel) {
        try {
            Page<ParamsCenterVO> page = new Page<>(current, size);
            IPage<ParamsCenterVO> result = paramsService.pageAllByFcModel(fcModel, page);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 分页查询当前用户的参数列表（支持飞控型号过滤）
     */
    @GetMapping("/my/page")
    public Result<IPage<ParamsCenterVO>> pageMy(
            @RequestParam(defaultValue = "1") Long current,
            @RequestParam(defaultValue = "10") Long size,
            @RequestParam(required = false) String fcModel) {
        try {
            Long userId = StpUtil.getLoginIdAsLong();
            Page<ParamsCenterVO> page = new Page<>(current, size);
            IPage<ParamsCenterVO> result = paramsService.pageByUserIdAndFcModel(userId, fcModel, page);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 增加下载次数
     */
    @PostMapping("/{id}/download")
    public Result<String> incrementDownloadCount(@PathVariable Long id) {
        try {
            ParamsCenter params = paramsService.getById(id);
            if (params == null) {
                return Result.error(I18nUtil.getMessage("params.not.found"));
            }

            // 增加下载次数
            ParamsCenter updateParams = new ParamsCenter();
            updateParams.setId(id);
            updateParams.setDownloadCount(params.getDownloadCount() + 1);

            boolean success = paramsService.updateById(updateParams);
            if (success) {
                return Result.success(I18nUtil.getMessage("params.download.success"));
            }
            return Result.error(I18nUtil.getMessage("params.download.failed"));
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
}
