<?php
/**
 * VR票务插件 - C端商品API控制器
 * 
 * 路由: /api.php?s=plugins/index&pluginsname=vr_ticket&pluginscontrol=goods&pluginsaction=xxx
 *
 * @package vr_ticket\api
 */

namespace app\plugins\vr_ticket\api;

use app\plugins\vr_ticket\service\SeatMapService;
use app\service\GoodsService;

/**
 * C端商品 API
 */
class Goods
{
    private static function success($data = [], string $msg = 'success')
    {
        return [
            'code' => 0,
            'msg'  => $msg,
            'data' => $data,
        ];
    }

    private static function error(string $msg = '请求失败', int $code = -1)
    {
        return [
            'code' => $code,
            'msg'  => $msg,
            'data' => [],
        ];
    }

    /**
     * 获取热门推荐商品
     * 
     * GET /api.php?s=plugins/index&pluginsname=vr_ticket&pluginscontrol=goods&pluginsaction=recommend
     */
    public function recommend()
    {
        try {
            // 调用 ShopXO 商品服务获取热门商品
            // VR票务插件的 category_id 需要在商品管理中设置
            $params = [
                'is_new'          => 0,
                'is_recommend'    => 1,
                'is_error'        => 0,
                'is_delete_time'  => 0,
                'start'           => 0,
                'num'            => 10,
                'order_by'       => 'sales',
                'sort'           => 'desc',
            ];
            
            $result = GoodsService::GoodsList($params);
            $list = self::formatGoodsList($result);
            
            return self::success([
                'list' => $list,
                'count' => count($list),
            ]);
        } catch (\Exception $e) {
            return self::error('获取推荐失败: ' . $e->getMessage());
        }
    }

    /**
     * 获取商品列表
     * 
     * GET /api.php?s=plugins/index&pluginsname=vr_ticket&pluginscontrol=goods&pluginsaction=lists
     * @param int city_id 城市ID筛选
     * @param int page 页码
     * @param int size 每页数量
     */
    public function lists()
    {
        try {
            $page = input('page', 1, 'intval');
            $size = input('size', 10, 'intval');
            $cityId = input('city_id', 0, 'intval');
            if (empty($cityId)) {
                $cityId = input('cityid', 0, 'intval');
            }
            
            $start = ($page - 1) * $size;
            
            $params = [
                'is_new'          => 0,
                'is_error'        => 0,
                'is_delete_time'  => 0,
                'start'          => $start,
                'num'            => $size,
                'order_by'       => 'add_time',
                'sort'           => 'desc',
            ];
            
            // 城市筛选（如果有设置produce_region）
            if (!empty($cityId)) {
                $params['produce_region'] = $cityId;
            }
            
            $result = GoodsService::GoodsList($params);
            $list = self::formatGoodsList($result);
            
            return self::success([
                'list'   => $list,
                'count'  => count($list),
                'page'   => $page,
                'size'   => $size,
            ]);
        } catch (\Exception $e) {
            return self::error('获取列表失败: ' . $e->getMessage());
        }
    }

    /**
     * 获取周边商品
     * 
     * GET /api.php?s=plugins/index&pluginsname=vr_ticket&pluginscontrol=goods&pluginsaction=merchandise
     */
    public function merchandise()
    {
        try {
            $page = input('page', 1, 'intval');
            $size = input('size', 20, 'intval');
            
            $start = ($page - 1) * $size;
            
            // 获取VR票务相关的周边商品（非票务类型）
            $params = [
                'is_new'          => 0,
                'is_error'        => 0,
                'is_delete_time'  => 0,
                'start'          => $start,
                'num'            => $size,
                'order_by'       => 'sales',
                'sort'           => 'desc',
                // 可以根据实际情况添加商品分类筛选
            ];
            
            $result = GoodsService::GoodsList($params);
            $list = self::formatGoodsList($result);
            
            return self::success([
                'list'   => $list,
                'count'  => count($list),
            ]);
        } catch (\Exception $e) {
            return self::error('获取周边商品失败: ' . $e->getMessage());
        }
    }

    /**
     * 获取商品详情
     * 
     * GET /api.php?s=plugins/index&pluginsname=vr_ticket&pluginscontrol=goods&pluginsaction=detail&id=X
     */
    public function detail()
    {
        $goodsId = input('id', 0, 'intval');
        if ($goodsId <= 0) {
            return self::error('参数错误：商品ID无效');
        }
        
        try {
            $goods = GoodsService::GoodsDetail($goodsId);
            
            if (empty($goods)) {
                return self::error('商品不存在', -404);
            }
            
            return self::success([
                'goods' => self::formatGoodsDetail($goods),
            ]);
        } catch (\Exception $e) {
            return self::error('获取详情失败: ' . $e->getMessage());
        }
    }

    /**
     * 搜索商品
     *
     * GET /api.php?s=plugins/index&pluginsname=vr_ticket&pluginscontrol=goods&pluginsaction=search&keyword=X
     */
    public function search()
    {
        $keyword = input('keyword', '', 'trim');
        $page = input('page', 1, 'intval');
        $size = input('size', 10, 'intval');
        
        if (empty($keyword)) {
            return self::error('请输入搜索关键词');
        }
        
        try {
            $start = ($page - 1) * $size;
            
            $params = [
                'is_new'          => 0,
                'is_error'        => 0,
                'is_delete_time'  => 0,
                'start'          => $start,
                'num'            => $size,
                'title_like'     => $keyword,
                'order_by'       => 'sales',
                'sort'           => 'desc',
            ];
            
            $result = GoodsService::GoodsList($params);
            $list = self::formatGoodsList($result);
            
            return self::success([
                'list'    => $list,
                'count'   => count($list),
                'keyword' => $keyword,
            ]);
        } catch (\Exception $e) {
            return self::error('搜索失败: ' . $e->getMessage());
        }
    }

    /**
     * 获取座位图（含实时库存）
     *
     * GET /api.php?s=plugins/index&pluginsname=vr_ticket&pluginscontrol=goods&pluginsaction=seatmap&goods_id=118
     *
     * @return array { code, msg, data: { seatSpecMap, goods_spec_data } }
     */
    public function seatmap()
    {
        $goodsId = input('goods_id', 0, 'intval');
        if ($goodsId <= 0) {
            return self::error('参数错误：goods_id 无效');
        }

        try {
            $data = SeatMapService::GetSeatMap($goodsId);
            return self::success($data);
        } catch (\Exception $e) {
            return self::error('获取座位图失败: ' . $e->getMessage());
        }
    }

    /**
     * 格式化商品列表数据
     */
    private static function formatGoodsList($result)
    {
        $list = [];
        
        if (!empty($result)) {
            foreach ($result as $goods) {
                $list[] = [
                    'id'          => $goods['id'],
                    'title'       => $goods['title'],
                    'image'       => $goods['image'],
                    'price'       => $goods['price'],
                    'original_price' => $goods['original_price'] ?? $goods['price'],
                    'sales'       => $goods['sales'] ?? 0,
                    'stock'       => $goods['stock'] ?? 0,
                    'venue'       => isset($goods['produce_venue']) ? $goods['produce_venue'] : '',
                    'date'        => isset($goods['produce_date']) ? $goods['produce_date'] : '',
                    'add_time'   => $goods['add_time'] ?? '',
                ];
            }
        }
        
        return $list;
    }

    /**
     * 格式化商品详情数据
     */
    private static function formatGoodsDetail($goods)
    {
        return [
            'id'               => $goods['id'],
            'title'            => $goods['title'],
            'image'            => $goods['image'],
            'images'           => !empty($goods['images']) ? explode(',', $goods['images']) : [$goods['image']],
            'price'            => $goods['price'],
            'original_price'   => $goods['original_price'] ?? $goods['price'],
            'sales'            => $goods['sales'] ?? 0,
            'stock'            => $goods['stock'] ?? 0,
            'content'          => htmlspecialchars_decode($goods['content'] ?? ''),
            'spec_type'        => $goods['spec_type'] ?? 0,
            'spec_value_id'    => $goods['spec_value_id'] ?? '',
            // 票务相关字段
            'venue'            => $goods['produce_venue'] ?? '',
            'date'             => $goods['produce_date'] ?? '',
            'time'             => $goods['produce_time'] ?? '',
            'region'           => $goods['produce_region'] ?? '',
            'add_time'         => $goods['add_time'] ?? '',
        ];
    }
}
