<?php

namespace App\Distributor\Repositories;

use App\Admin\Repositories\DistAppearanceTemplateLog;
use App\Models\DistAppearanceTemplate as Model;
use App\Models\SiteAppearanceTemplate;
use Dcat\Admin\Repositories\EloquentRepository;
use DOMDocument;
use Illuminate\Support\Carbon;
use Symfony\Component\DomCrawler\Crawler;

class DistAppearanceTemplate extends EloquentRepository
{
    /**
     * Model.
     *
     * @var string
     */
    protected $eloquentClass = Model::class;


    /*
     * 同步模版到正式表上
     */
    public static function syncAppearanceTemplates($appearanceId,$distId)
    {
        $model = new Model();
        return $model->syncAppearanceTemplates($appearanceId,$distId);
    }

    /*
     * 得到独立页的模版数组
     */
    public static function getLandingPageTemplateOptions()
    {
        $distInfo = DistAdminDistributor::getInfo();
        $distId = $distInfo->id;
        $appearanceId = $distInfo->appearance_id;
        $model = new Model();
        $result =  $model->where('appearance_id', $appearanceId)->where('dist_id', $distId)->select('file_name')->get();
        $options = ['pages_detail.liquid'=>config('dictionary.landing_page_default_template')];
        foreach ($result as $key => $value) {
            // 检查字符串是否以 "pages_sp_" 开头
            if (strpos($value->file_name, 'pages_sp_') === 0) {
                // 提取 "xxxx" 部分
              //  $part = str_replace('pages_sp_', '', $value->file_name);
               // $part = str_replace('.liquid', '', $part);
                $part = $value->file_name;
                $options[$part] = $part;
            }
        }
        return $options;
    }

    public static function previewSave($data)
    {
        $distInfo = DistAdminDistributor::getInfo();
        $distId = $distInfo->id;
        $appearanceId = $distInfo->appearance_id;
        //查找$data中是否存在mtb_id
        $inputElements = self::findElementsWithMtbId($data);
        foreach ($inputElements as $prefix => $elements) {
            //找查找对应的模板
            $template = Model::where('dist_id', $distId)->where('appearance_id', $appearanceId)->where('template_code',$prefix)->first();
            if ($template) {
                //替换模板内容
                $oldContent = self::contentChange($template->content,$template->template_code);//旧模板内容
                $newContent = self::contentReplace($oldContent,$elements);
                //更新模板内容
                $template->content = $newContent;
                $template->updated_at = Carbon::now();
                $template->save();
                //记录日志
                DistAppearanceTemplateLog::insertLog($appearanceId,$distId,$template->file_name,$template->file_path,$template->template_code,$newContent,$oldContent);
            }
        }
    }



    /*
     * 替换模板内容
     * @param $content 模板内容
     * @param $elements Array([mtb_id] => 676a6d11f1a57_1,[outHtml] => <div mtb_id="abc_2"><p>Again3</p></div>)
     */
    public static function contentReplace($content,$elements) {

        foreach ($elements as $element) {
            $mtbId = $element['mtb_id'];
            $outHtml = $element['outHtml'];
            $content = preg_replace_callback(
                '/<([a-zA-Z0-9]+)[^>]*mtb_id="' . preg_quote($mtbId, '/') . '"[^>]*>(.*?)<\/\1>/s',
                function ($matches) use ($outHtml) {
                    // 返回替换后的内容
                    return $outHtml;
                },
                $content
            );

            //替换img等标签的情况
            $content = preg_replace_callback(
                '/<([a-zA-Z0-9]+)[^>]*mtb_id="' . preg_quote($mtbId, '/') . '"[^>]*>/s',
                function ($matches) use ($outHtml) {
                    // 返回替换后的内容
                    return $outHtml;
                },
                $content
            );
        }

        return $content;
    }


    /*
     * 查找带有 mtb_id 属性的 HTML 元素
     */
    public static function findElementsWithMtbId($html) {
        // 定义正则表达式来匹配所有带有 mtb_id 属性的 HTML 元素
        $pattern = '/<([a-zA-Z0-9-_]+)([^>]*\smtb_id="([^"]+)")([^>]*)>(.*?)<\/\1>/is';
        preg_match_all($pattern, $html, $matches, PREG_SET_ORDER);
        // 存储结果
        $result = [];
        foreach ($matches as $match) {
            // 提取 mtb_id 和匹配的 HTML 内容
            $outHtml = $match[0];
            //如果第一个字符>后边有<，则加上空格
            $pattern = '/>(?=<)/'; // 匹配 > 后紧跟 <
            $replacement = '> '; // 在 > 和 < 之间添加一个空格
            $outHtml = preg_replace($pattern, $replacement, $outHtml, 1);

            //去掉mtb_id属性
            $outHtml = preg_replace('/\s*mtb_id="[^"]*"/', '', $outHtml);
            $result[] = [
                'mtb_id' => $match[3],  // mtb_id 的值
                'outHtml' => $outHtml, // 匹配到的完整 HTML 元素
            ];
        }

        //匹配img等标签
        $pattern = '/<([a-zA-Z0-9]+)[^>]*\smtb_id="([^"]+)"[^>]*>/is';  // 匹配所有含有 mtb_id 属性的标签
        preg_match_all($pattern, $html, $matches, PREG_SET_ORDER);
        foreach ($matches as $match) {
            //去掉mtb_id属性
            $outHtml = $match[0];
            $outHtml = preg_replace('/\s*mtb_id="[^"]*"/', '', $outHtml);
            $result[] = [
                'mtb_id' => $match[2],  // mtb_id 的值，这里改为 $match[2]
                'outHtml' => $outHtml,  // 匹配到的完整 HTML 元素
            ];
        }



        $result = array_reduce($result, function ($carry, $item) {
            // 获取 mtb_id 的前缀
            $prefix = explode('_', $item['mtb_id'])[0];
            // 如果前缀不存在，初始化一个空数组
            if (!isset($carry[$prefix])) {
                $carry[$prefix] = [];
            }
            // 将当前项添加到对应的前缀数组中
            $carry[$prefix][] = $item;
            return $carry;
        }, []);


        return $result;
    }



    /*
     * TODO: 模板内容增加 mtb_id 属性，用于区分不同模板
     */
    public static function contentChange($content,$templateCode)
    {
        $count = 1;
        $newContent = preg_replace_callback(
            '/(<[^>]+?mtb_edit=[\'"][^\'"]+[\'"][^>]*>)/',
            function ($matches) use (&$count, $templateCode) {
                // 在匹配到的 HTML 元素后添加 mtb_id 属性
                return preg_replace('/(mtb_edit=[\'"][^\'"]+[\'"])([^>]*)>/', '$1 mtb_id="' . $templateCode .'_'. $count++ . '"$2>', $matches[0]);
            },
            $content
        );

        return $newContent;
    }

}
