<?php

namespace App\Console\Commands;

use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Symfony\Component\DomCrawler\Crawler;


/**
 * 导入相册内容到产品表
 * php artisan sync:brsiteFix
 */
class SyncBrFix extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'sync:brsiteFix';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';


    public function handle()
    {
        exit;

        $sqlFile = fopen('update_products.sql', 'a') or die("无法创建SQL文件");

        $ossHost = 'https://mietubl-website.oss-accelerate.aliyuncs.com';
        //$ossHost = 'https://mietubl-dev.oss-accelerate.aliyuncs.com';
        $baseUrl = 'https://mietubloficial.com.br';
        $urlList = [
            ['slug'=>'tws', 'url'=>'/tws/'],
            ['slug'=>'protetor-de-tela-de-vidro-temperado', 'url'=>'/protetor-de-tela-de-vidro-temperado/'],
            ['slug'=>'protetor-da-tela-do-tablet', 'url'=>'/protetor-da-tela-do-tablet/'],
            ['slug'=>'maquina-de-corte-de-protetor-de-tela', 'url'=>'/maquina-de-corte-de-protetor-de-tela/'],

            ['slug'=>'folhas-de-protetor-de-tela-de-hidrogel', 'url'=>'/folhas-de-protetor-de-tela-de-hidrogel/'],

            ['slug'=>'lightning', 'url'=>'/lightning/'],
            ['slug'=>'type-c', 'url'=>'/type-c/'],
            ['slug'=>'micro-usb', 'url'=>'/micro-usb/'],
            ['slug'=>'fones-de-ouvido-auricular-com-fio', 'url'=>'/fones-de-ouvido-auricular-com-fio/'],
            ['slug'=>'fones-de-ouvido', 'url'=>'/fones-de-ouvido/'],
            ['slug'=>'alto-falantes-bluetooth', 'url'=>'/alto-falantes-bluetooth/'],
            ['slug'=>'carregador-de-parede', 'url'=>'/carregador-de-parede/'],
            ['slug'=>'produtos-perifericos', 'url'=>'/produtos-perifericos/'],
        ];

        foreach ($urlList as $entry) {
            try {
                $category = DB::table('dist_product_category')
                    ->where('slug', $entry['slug'])
                    ->where('dist_id', 3)
                    ->first();

                if (!$category) {
                    echo "分类未找到，slug: {$entry['slug']}\n";
                    continue;
                }
                echo "分类 {$category->name} \n";
                if ($entry['slug'] == 'produtos-perifericos') {
                    $detailUrls = ['https://mietubloficial.com.br/produto/mini-impressora-de-pele-para-celular-mtb-pp01/'];
                } else {
                    $html = file_get_contents($baseUrl . $entry['url']);
                    $listCrawler = new Crawler($html);
                    $detailUrls = $listCrawler->filter('.elementor-shortcode a')->extract(['href']);

                }
                foreach ($detailUrls as $detailUrl) {

                    $detailHtml = file_get_contents($detailUrl);
                    $detailCrawler = new Crawler($detailHtml);

                    // 解析基础数据
                    $title = $detailCrawler->filter('.product_title')->text();

                    // 插入产品获取ID
                    $productId = DB::table('dist_product')->where('title', $title)->where('dist_id', 3)->first();
                    if (!$productId) {
                        echo "产品未找到，title: {$title}\n";
                        continue;
                    }

                    // 1. 去除最后一个字符（仅当末尾是斜杠时）
                    $trimmedUrl = substr($detailUrl, 0, -1);
                    // 2. 分割路径并取末段
                    $path = parse_url($trimmedUrl, PHP_URL_PATH);
                    $segments = explode('/', $path);
                    $slug = end($segments);

                    // 生成更新SQL
                    $escapedTitle = addslashes($title); // 转义特殊字符
                    $escapedSlug = addslashes($slug);

                    $sql = "UPDATE dist_product SET seo_title = title,slug = '{$escapedSlug}' WHERE title = '{$title}' AND dist_id = 3;\n";

                    // 写入SQL文件
                    fwrite($sqlFile, $sql);
                    echo "生成SQL：{$sql}\n";



                    echo "处理主图完成，下一个产品 \n";
                    echo "------------------------------------------\n";
                }

            } catch (\Exception $e) {
                echo "数据采集失败: " . $e->getMessage() . "\n";
                continue;
            }
        }
        dd('所有处理完成');
    }

}
