<?php
namespace App\Services\LiquidTags;

use App\Models\DistProduct;
use Liquid\AbstractBlock;
use Liquid\template;
use Liquid\Context;
use App\Services\LiquidRenderer;


// 使用你的 DistProduct 模型

class LiquidTagProduct extends AbstractBlock
{
    private $mode;
    private $productId;
    private $quantity;
    private $limit;
    private $categoryId;

    private $templateFile;

    // 构造函数用于解析传入的参数
    public function __construct($markup, array &$tokens, $file_system = null)
    {

        // 初始化默认值
        $this->mode = 'single';
        $this->productId = 0;
        $this->quantity = 0;
        $this->limit = 10;
        $this->categoryId = 0;
        $this->templateFile = null;

        // 正则表达式解析传入的参数
        $syntax = '/(\w+)=("[^"]*"|\'[^\']*\'|\d+)/';

        if (preg_match_all($syntax, $markup, $matches, PREG_SET_ORDER)) {

            foreach ($matches as $match) {
                $key = $match[1];
                $value = trim($match[2], '"\''); // 同时去除双引号和单引号

                switch ($key) {
                    case 'mode':
                        $this->mode = $value;
                        break;
                    case 'id':
                        $this->productId = (int)$value;
                        break;
                    case 'quantity':
                        $this->quantity = (int)$value;
                        break;
                    case 'limit':
                        $this->limit = (int)$value;
                        break;
                    case 'category_id':
                        $this->categoryId = (int)$value;
                        break;
                    case 'template':
                        $this->templateFile = $value;
                        break;
                }
            }
        }
    }

    // render 方法执行逻辑并返回渲染结果
    public function render($context)
    {
        if ($this->mode === 'list') {
            return $this->renderList();
        } elseif ($this->mode === 'single') {
            return $this->renderSingle();
        }

        // 如果模式不正确，返回空字符串
        return '';
    }

    private function renderList()
    {
        // 从数据库获取产品列表
        $products = DistProduct::getProducts($this->categoryId, $this->limit);

         if ($products->count() > 0) {
            return $this->renderTemplate(['products' => $products->toArray()]);
        }

        // 如果没有产品，返回空字符串
        return '';
    }

    private function renderSingle()
    {
        // 从数据库获取单个产品信息
        $product = DistProduct::getProduct($this->productId);

        if ($product && $this->quantity > 0) {
            return $this->renderTemplate(['product' => $product->toArray()]);
        }

        // 如果产品不存在或参数不完整，返回空字符串
        return '';
    }

    private function renderTemplate(array $data)
    {

        if (!$this->templateFile) {
            return ''; // 如果未提供模板文件，返回空字符串
        }
        return LiquidRenderer::render($this->templateFile,$data);


    }
}
