package com.zhentao.controller;

import com.zhentao.common.Result;
import com.zhentao.entity.PointRule;
import com.zhentao.entity.PointsOrder;
import com.zhentao.entity.PointsProduct;
import com.zhentao.service.PointsMallService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

/**
 * 积分商城控制器
 */
@RestController
@RequestMapping("/points")
@CrossOrigin(origins = "*")
public class PointsMallController {
    
    @Autowired
    private PointsMallService pointsMallService;
    
    /**
     * 获取商品列表
     * @param category 分类(可选): 1-实物商品 2-虚拟商品
     * @param pageNum 页码
     * @param pageSize 每页数量
     */
    @GetMapping("/products")
    public Result<Map<String, Object>> getProductList(
            @RequestParam(value = "category", required = false) Integer category,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        try {
            Map<String, Object> data = pointsMallService.getProductList(category, pageNum, pageSize);
            return Result.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取商品列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取推荐商品
     * @param limit 数量限制
     */
    @GetMapping("/products/recommend")
    public Result<List<PointsProduct>> getRecommendProducts(
            @RequestParam(value = "limit", defaultValue = "10") Integer limit) {
        try {
            List<PointsProduct> products = pointsMallService.getRecommendProducts(limit);
            return Result.success(products);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取推荐商品失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取商品详情
     * @param id 商品ID
     */
    @GetMapping("/products/{id}")
    public Result<PointsProduct> getProductDetail(@PathVariable Long id) {
        try {
            PointsProduct product = pointsMallService.getProductDetail(id);
            if (product == null) {
                return Result.error("商品不存在");
            }
            return Result.success(product);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取商品详情失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取积分余额
     * @param makerId 红娘ID
     */
    @GetMapping("/balance")
    public Result<Map<String, Object>> getPointsBalance(@RequestParam Long makerId) {
        try {
            Integer balance = pointsMallService.getPointsBalance(makerId);
            Map<String, Object> data = new HashMap<>();
            data.put("balance", balance);
            data.put("makerId", makerId);
            return Result.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取积分余额失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取积分明细
     * @param makerId 红娘ID
     * @param pageNum 页码
     * @param pageSize 每页数量
     */
    @GetMapping("/records")
    public Result<Map<String, Object>> getPointsRecords(
            @RequestParam("makerId") Long makerId,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize) {
        try {
            Map<String, Object> data = pointsMallService.getPointsRecords(makerId, pageNum, pageSize);
            // 同时返回当前余额
            Integer balance = pointsMallService.getPointsBalance(makerId);
            data.put("balance", balance);
            return Result.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取积分明细失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取积分规则(赚取积分方式)
     */
    @GetMapping("/rules")
    public Result<List<PointRule>> getPointRules() {
        try {
            List<PointRule> rules = pointsMallService.getPointRules();
            return Result.success(rules);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取积分规则失败: " + e.getMessage());
        }
    }
    
    /**
     * 兑换商品（提交到后台审核）
     */
    @PostMapping("/exchange")
    public Result<PointsOrder> exchangeProduct(@RequestBody Map<String, Object> params) {
        try {
            Long makerId = Long.valueOf(params.get("makerId").toString());
            Long productId = Long.valueOf(params.get("productId").toString());
            Integer quantity = params.get("quantity") != null ? 
                    Integer.valueOf(params.get("quantity").toString()) : 1;
            String contactPhone = (String) params.get("contactPhone");
            
            if (contactPhone == null || contactPhone.length() != 11) {
                return Result.error("请输入正确的11位手机号");
            }
            
            PointsOrder order = pointsMallService.exchangeProduct(
                    makerId, productId, quantity, contactPhone);
            
            return Result.success("提交成功，等待审核", order);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("兑换失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取兑换订单列表
     * @param makerId 红娘ID
     * @param status 订单状态(可选): 0-待发货 1-已发货 2-已完成 3-已取消
     * @param pageNum 页码
     * @param pageSize 每页数量
     */
    @GetMapping("/orders")
    public Result<Map<String, Object>> getOrderList(
            @RequestParam("makerId") Long makerId,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        try {
            Map<String, Object> data = pointsMallService.getOrderList(makerId, status, pageNum, pageSize);
            return Result.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取订单列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取订单详情
     * @param orderNo 订单编号
     */
    @GetMapping("/orders/{orderNo}")
    public Result<PointsOrder> getOrderDetail(@PathVariable String orderNo) {
        try {
            PointsOrder order = pointsMallService.getOrderDetail(orderNo);
            if (order == null) {
                return Result.error("订单不存在");
            }
            return Result.success(order);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取订单详情失败: " + e.getMessage());
        }
    }
    
    /**
     * 增加积分(签到、上传线索等)
     */
    @PostMapping("/add")
    public Result<Map<String, Object>> addPoints(@RequestBody Map<String, Object> params) {
        try {
            Long makerId = Long.valueOf(params.get("makerId").toString());
            Integer ruleType = Integer.valueOf(params.get("ruleType").toString());
            String reason = (String) params.get("reason");
            
            Integer addedPoints = pointsMallService.addPoints(makerId, ruleType, reason);
            Integer newBalance = pointsMallService.getPointsBalance(makerId);
            
            Map<String, Object> data = new HashMap<>();
            data.put("addedPoints", addedPoints);
            data.put("newBalance", newBalance);
            
            return Result.success("积分增加成功", data);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("积分增加失败: " + e.getMessage());
        }
    }
}
