package com.haha.admin.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.haha.admin.annotation.RequirePermission;
import com.haha.entity.dto.AddToMerchantDTO;
import com.haha.entity.dto.MasterProductQueryDTO;
import com.haha.entity.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.List;
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, "同步失败");
    }

    /**
     * 查询商品总库列表（调用哈哈平台API）
     * @param queryDTO 查询参数
     * @return 商品总库分页数据
     */
    @RequirePermission("product:read")
    @GetMapping("/master/list")
    public Result<Map<String, Object>> masterList(MasterProductQueryDTO queryDTO) {
        queryDTO.validate();

        Map<String, Object> result = productService.getMasterProductList(
                queryDTO.getPage(),
                queryDTO.getPageSize(),
                queryDTO.getBarcode(),
                queryDTO.getCode(),
                queryDTO.getProductName(),
                queryDTO.getDeviceAdapt()
        );

        return Result.success("查询成功", result);
    }

    /**
     * 添加商品到商家商品库（调用哈哈平台API）
     * @param dto 请求参数
     * @return 添加结果
     */
    @RequirePermission("product:create")
    @Log(module = "商品管理", operation = OperationType.INSERT, summary = "添加商品到商家商品库")
    @PostMapping("/master/add-to-merchant")
    public Result<Void> addToMerchant(@RequestBody AddToMerchantDTO dto) {
        boolean success = productService.addToMerchant(dto.getCodeList());
        return success ? Result.success("添加成功", null) : Result.error(500, "添加失败");
    }

    /**
     * 商品上下架控制
     * @param params 请求参数: deviceId, goodsCode, salesType(IN上架/OUT下架), callType(CHANGE/COVER)
     * @return 操作结果
     */
    @RequirePermission("product:update")
    @Log(module = "商品管理", operation = OperationType.UPDATE, summary = "商品上下架")
    @PostMapping("/shelf-status")
    public Result<Map<String, Object>> setShelfStatus(@RequestBody Map<String, String> params) {
        Map<String, Object> result = productService.setProductShelfStatus(
                params.get("deviceId"),
                params.get("goodsCode"),
                params.get("salesType"),
                params.getOrDefault("callType", "CHANGE"));
        return Result.success("操作成功", result);
    }

    /**
     * 获取指定设备可售卖商品列表
     * @param deviceId 设备SN号
     * @return 商品列表
     */
    @RequirePermission("product:read")
    @GetMapping("/device/{deviceId}")
    public Result<List<Product>> getDeviceProducts(@PathVariable String deviceId) {
        List<Product> list = productService.getProductListBydeviceId(deviceId);
        return Result.success("查询成功", list);
    }

    /**
     * 查询商品ID对应关系
     * @param codeList 哈哈商品编号列表，多个用逗号隔开
     * @return 对应关系
     */
    @RequirePermission("product:read")
    @GetMapping("/id-mapping")
    public Result<Map<String, Object>> getIdMapping(@RequestParam(required = false) String codeList) {
        Map<String, Object> result = productService.getIdMapping(codeList);
        return Result.success("查询成功", result);
    }
}
