<?php

namespace App\Admin\Forms;
use App\Admin\Repositories\BaseProductCategory;
use App\Admin\Repositories\RpcAlbum;
use App\Libraries\CommonHelper;
use App\Models\BaseProduct;
use App\Distributor\Repositories\DistProductCategory;
use App\Models\BaseProductImage;
use App\Models\DistProduct;
use App\Models\DistProductImage;
use Dcat\Admin\Widgets\Form;

class ImportAlbum extends Form
{
    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
        $albumIds = explode(',', $input['album_ids']);
        $categoryId = $input['category_id'];

        // 检查 product_ids 是否为空

        if (empty($input['album_ids'])) {
            return $this
                ->response()
                ->error('请选择要导入的产品');
        }

        try {
            //RPC读取相册
            $rpcAlbum = new RpcAlbum();
            $albumResult = $rpcAlbum->getByids($albumIds);

            if ($albumResult['status']= false) {
                return $this
                    ->response()
                    ->error('RPC获取相册失败:'. $albumResult['msg']);
            }

            foreach ($albumResult['data'] as $item) {
                $title = isset($item['title']) ? $item['title'] : $item['model'];
                // 创建新的 DistProduct 记录
                $distProduct = BaseProduct::create([
                    'category_id' => $categoryId,
                    'title' => $title,
                    'sku' => $item['model'], // 假设 $baseProduct 也有 sku 字段
                    'issuance_date' => null, // 假设 $baseProduct 也有 issuance_date 字段
                    'order' => 0, // 假设 $baseProduct 也有 order 字段
                    'enabled' => 1, // 假设 $baseProduct 也有 enabled 字段
                    'content' => $this->changeToimagesHTML($item['en_detail']), // 假设 $baseProduct 也有 content 字段
                    'parameters' => $item['parameters'], // 假设 $baseProduct 也有 parameters 字段
                    'seo_title'=> $title,
                    'seo_keywords' => '',
                    'seo_description' => '',
                    'created_at' => now(), // 自动填充创建时间
                    'updated_at' => now(), // 自动填充更新时间
                ]);
                //DistProduct::where('id', $distProduct->id)->update(['slug' => $distProduct->id]);
                // 遍历 base_product_image 表中的记录，并插入到 dist_product_image 表中
                $cover = json_decode($item['cover'], true);
                foreach ($cover as $baseImage) {
                    $i = 1;
                    BaseProductImage::create([
                        'image_url' => $baseImage,
                        'product_id' => $distProduct->id, // 使用新创建的 DistProduct 的 ID
                        'order' => $i,
                        'created_at' => now(), // 自动填充创建时间
                        'updated_at' => now(), // 自动填充更新时间
                    ]);
                    $i++;
                }
            }
            return $this
                ->response()
                ->success('导入成功')
                ->refresh();
        } catch (\Exception $e) {
            throw $e;
            return $this
                ->response()
                ->error('导入失败: ' . $e->getMessage());
        }
    }

    public function changeToimagesHTML($content) {
        $content = json_decode($content, true);
        $html = '';
        foreach ($content as $item) {
            $item = CommonHelper::ossUrl($item);
            $html.= '<img src="'. $item. '">';
        }
        return $html;
    }

    /**
     * Build a form here.
     */
    public function form()
    {
        // 设置隐藏表单，传递用户id
        $this->select('category_id', admin_trans_label('category_name'))
            ->options(BaseProductCategory::selectOptions())
            ->required();
        $this->hidden('album_ids')->attribute('id', 'album_ids');
    }

    /**
     * The data of the form.
     *
     * @return array
     */
    public function default()
    {
        return [];
    }
}
