<?php

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

class ImportProduct extends Form
{
    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
        // dump($input);

        // return $this->response()->error('Your error message.');


        // 获取输入的 product_ids 和 category_id
        $productIds = explode(',', $input['product_ids']);
        $categoryId = $input['category_id'];

        // 检查 product_ids 是否为空

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


        try {
            foreach ($productIds as $productId) {
                // 从 BaseProduct 获取产品数据
                $baseProduct = BaseProduct::findById($productId);

                if (!$baseProduct) {
                    throw new \Exception("Product with ID $productId not found in BaseProduct.");
                }
// 获取 base_product_image 表中与当前 base_product 相关的图片记录
                $baseProductImages = BaseProductImage::where('product_id', $baseProduct->id)->get();

                // 创建新的 DistProduct 记录
                $distProduct = DistProduct::create([
                    'category_id' => $categoryId,
                    'title' => $baseProduct->title,
                    'keywords' => $baseProduct->keyword, // 注意这里是 'keywords' 而不是 'keyword'
                    'description' => $baseProduct->description,
                    'sku' => $baseProduct->sku, // 假设 $baseProduct 也有 sku 字段
                    'issuance_date' => $baseProduct->issuance_date, // 假设 $baseProduct 也有 issuance_date 字段
                    'order' => $baseProduct->order, // 假设 $baseProduct 也有 order 字段
                    'enabled' => $baseProduct->enabled, // 假设 $baseProduct 也有 enabled 字段
                    'content' => $baseProduct->content, // 假设 $baseProduct 也有 content 字段
                    'parameters' => $baseProduct->parameters, // 假设 $baseProduct 也有 parameters 字段
                    'is_pinned' => 0, // 假设 $baseProduct 也有 is_pinned 字段
                    'dist_id' => getDistributorId(),
                    'created_at' => now(), // 自动填充创建时间
                    'updated_at' => now(), // 自动填充更新时间
                ]);

                // 遍历 base_product_image 表中的记录，并插入到 dist_product_image 表中
                foreach ($baseProductImages as $baseImage) {
                    DistProductImage::create([
                        'image_url' => $baseImage->image_url,
                        'product_id' => $distProduct->id, // 使用新创建的 DistProduct 的 ID
                        'order' => $baseImage->order,
                        'created_at' => now(), // 自动填充创建时间
                        'updated_at' => now(), // 自动填充更新时间
                    ]);
                }

            }

            return $this
                ->response()
                ->success('导入成功')
                ->refresh();
        } catch (\Exception $e) {

            return $this
                ->response()
                ->error('导入失败: ' . $e->getMessage());
        }
//
//        return $this
//				->response()
//				->success('导入成功')
//				->refresh();
    }

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

    /**
     * The data of the form.
     *
     * @return array
     */
    public function default()
    {
        return [
//            'name'  => 'John Doe',
//            'email' => 'John.Doe@gmail.com',
        ];
    }
}
