package com.haha.admin.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.haha.admin.annotation.RequirePermission;
import com.haha.admin.dto.ProductQueryDTO;
import com.haha.common.annotation.Log;
import com.haha.common.enums.OperationType;
import com.haha.common.vo.Result;
import com.haha.entity.Product;
import com.haha.service.ProductService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 商品管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/products")
@RequiredArgsConstructor
public class ProductController {

    private final ProductService productService;

    /**
     * 分页查询商品列表
     * @param queryDTO 查询参数
     * @return 商品列表
     */
    @RequirePermission("product:read")
    @GetMapping("/list")
    public Result<Map<String, Object>> list(ProductQueryDTO queryDTO) {
        queryDTO.validate();

        IPage<Product> productPage = productService.getPage(
                queryDTO.getPage(),
                queryDTO.getPageSize(),
                queryDTO.getName(),
                queryDTO.getBarcode(),
                queryDTO.getCategory(),
                queryDTO.getSyncStatus()
        );

        // 构造前端需要的分页数据格式
        Map<String, Object> result = new HashMap<>();
        result.put("list", productPage.getRecords());
        result.put("total", productPage.getTotal());
        result.put("pageSize", productPage.getSize());
        result.put("currentPage", productPage.getCurrent());
        result.put("totalPages", productPage.getPages());
        
        return Result.success("查询成功", result);
    }

    /**
     * 获取商品详情
     * @param id 商品ID
     * @return 商品详情
     */
    @RequirePermission("product:read")
    @GetMapping("/{id}")
    public Result<Product> getById(@PathVariable Long id) {
        Product product = productService.getDetailById(id);
        if (product == null) {
            return Result.error(404, "商品不存在");
        }
        return Result.success("查询成功", product);
    }

    /**
     * 获取商品统计数据
     * @return 统计数据
     */
    @RequirePermission("product:read")
    @GetMapping("/statistics")
    public Result<Map<String, Object>> getStatistics() {
        Map<String, Object> statistics = productService.getStatistics();
        return Result.success("查询成功", statistics);
    }

    /**
     * 添加商品
     * @param product 商品信息
     * @return 添加结果
     */
    @RequirePermission("product:create")
    @Log(module = "商品管理", operation = OperationType.INSERT, summary = "添加商品")
    @PostMapping
    public Result<Product> add(@RequestBody Product product) {
        Product saved = productService.add(product);
        return Result.success("添加成功", saved);
    }

    /**
     * 编辑商品
     * @param id 商品ID
     * @param product 商品信息
     * @return 编辑结果
     */
    @RequirePermission("product:update")
    @Log(module = "商品管理", operation = OperationType.UPDATE, summary = "编辑商品")
    @PutMapping("/{id}")
    public Result<Product> update(@PathVariable Long id, @RequestBody Product product) {
        Product saved = productService.edit(id, product);
        return Result.success("更新成功", saved);
    }

    /**
     * 删除商品（软删除）
     * @param id 商品ID
     * @return 删除结果
     */
    @RequirePermission("product:delete")
    @Log(module = "商品管理", operation = OperationType.DELETE, summary = "删除商品")
    @DeleteMapping("/{id}")
    public Result<Void> delete(@PathVariable Long id) {
        boolean success = productService.softDelete(id);
        return success ? Result.success("删除成功", null) : Result.error(500, "删除失败");
    }

    /**
     * 同步商品到哈哈平台
     * @param id 商品ID
     * @return 同步结果
     */
    @RequirePermission("product:update")
    @Log(module = "商品管理", operation = OperationType.SYNC, summary = "同步商品")
    @PostMapping("/{id}/sync")
    public Result<Void> sync(@PathVariable Long id) {
        boolean success = productService.syncToHaha(id);
        return success ? Result.success("同步成功", null) : Result.error(500, "同步失败");
    }
}
