package com.corewing.app.modules.app;

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.common.annotation.CommonLog;
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.util.RedisUtil;
import com.corewing.app.vo.ParamsCenterVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 参数配置中心 Controller
 */
@Api(tags = "参数配置中心接口")
@RestController
@RequestMapping("/params")
public class AppParamsCenterController {

    @Resource
    private ParamsCenterService paramsService;

    @Resource
    private RedisUtil redisUtil;

    /**
     * 创建参数配置
     */
    @CommonLog("创建参数配置接口")
    @ApiOperation("创建参数配置接口")
    @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.setStatus("1");
            params.setAuditStatus("0");
            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());
        }
    }

    /**
     * 更新参数配置
     */
    @CommonLog("更新参数配置接口")
    @ApiOperation("更新参数配置接口")
    @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());
        }
    }

    /**
     * 删除参数配置
     */
    @CommonLog("根据id删除参数配置")
    @ApiOperation("根据id删除参数配置")
    @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查询参数配置
     */
    @CommonLog("根据id查询参数配置")
    @ApiOperation("根据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());
        }
    }

    /**
     * 查询所有公共参数列表（公开接口，支持飞控型号过滤）
     */
    @CommonLog("获取所有公共参数集合")
    @ApiOperation("获取所有公共参数集合")
    @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());
        }
    }

    /**
     * 查询当前用户的参数列表（支持飞控型号过滤）
     */
    @CommonLog("获取当前用户的参数列表")
    @ApiOperation("获取当前用户的参数列表")
    @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());
        }
    }

    /**
     * 分页查询所有参数列表（公开接口，支持飞控型号过滤）
     */
    @CommonLog("分页查询所有公共参数集合")
    @ApiOperation("分页查询所有公共参数集合")
    @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());
        }
    }

    /**
     * 分页查询当前用户的参数列表（支持飞控型号过滤）
     */
    @CommonLog("分页查询当前用户参数列表分页")
    @ApiOperation("分页查询当前用户参数列表分页")
    @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());
        }
    }

    /**
     * 增加下载次数
     */
    @CommonLog("增加参数中心下载次数")
    @ApiOperation("增加参数中心下载次数")
    @PostMapping("/{id}/download")
    public Result<String> incrementDownloadCount(@PathVariable Long id) {
        try {

            Object loginId = StpUtil.getLoginId();
            boolean isNew = redisUtil.setIfAbsent("paramCenter_" + loginId, 1, 1, TimeUnit.DAYS);
            // 如果键已存在，递增计数器
            long sendCount = isNew ? 1 : redisUtil.incr("paramCenter_" + loginId, 1);
            if(sendCount > 3) {
                return Result.error(I18nUtil.getMessage("params.download.exceed"));
            }

            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());
        }
    }

    /**
     * 提交审核
     * @param id
     * @return
     */
    @CommonLog("发布公共参数提交审核")
    @ApiOperation("发布公共参数提交审核")
    @GetMapping("/review/{id}")
    public Result<String> review(@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.setAuditStatus("1");
            updateParams.setAuditErrorMsg("");
            boolean success = paramsService.updateById(updateParams);
            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());
        }
    }
}
