<?php
declare (strict_types = 1);

namespace app\openapi\controller\v1;

use app\openapi\model\ProductModel;

class Product
{
    /**
     * 产品列表
     */
    public function list()
    {
        
        $params = request()->get([
            'category_id',
            'language' => 'zh-cn',
            'page/d'   => 1,
            'size/d'   => 50
        ]);

        if ($params['size'] > 200) {
            // 每页不超过200条
            $params['size'] = 200;
        }

        $list = ProductModel::with([
                'category' => fn($query) => $query->field(['id', 'name']),
            ])
            ->field([
                'id',
                'category_id',
                'spu',
                'name',
                'short_name',
                'cover_image',
                'deleted_at'
            ])
            ->where(function($query) use($params) {
                $model = $query->getModel();
                if (!empty($params['category_id'])) {
                    $model->scopeCategoryId($query, $params['category_id']);
                }
            })
            ->language($params['language']??'zh-cn')
            ->order(['sort' => 'asc', 'id' => 'desc'])
            ->hidden(['category_id'])
            ->paginate([
                'list_rows' => $params['size'],
                'page'      => $params['page']
            ])
            ->each(function($item) {
                if (!empty($item['cover_image']) && !str_starts_with($item['cover_image'], 'http')) {
                    $item['cover_image'] = image_domain_concat($item['cover_image']);
                }

                return $item;
            });

        return success('success', $list);
    }

    /**
     * 产品详情
     */
    public function detail()
    {
        $id = request()->param('id');

        $product = ProductModel::with([
                // 关联分类
                'category' => fn($query) => $query->field(['id', 'name']),
                // 关联属性
                'params'   => fn($query) => $query->field(['product_id', 'name', 'value'])
                                                ->hidden(['product_id']),
                // 关联sku
                'skus' => fn($query) => $query->withoutField(['sort', 'created_at', 'updated_at'])
                                                ->with([
                                                    'sku_attr' => fn($query) => $query->with('attr')->hidden(['sku_id', 'attr_id'])
                                                ])
                                                ->hidden(['id', 'product_id']),
                // 关联购买链接
                'links' => fn($query) => $query->field(['product_id', 'platform_id', 'link'])
                                                ->with([
                                                    'platforms' => fn($query) => $query->field(['id', 'platform'])
                                                ])
                                                ->hidden(['product_id', 'platform_id']),
                // 关联相关产品
                'related' => fn($query) => $query->field(['product_id', 'related_product_id'])
                                                ->with([
                                                    'product' => fn($query) => $query->field(['id', 'name', 'spu', 'cover_image'])->withBind([
                                                        'id',
                                                        'name',
                                                        'spu',
                                                        'cover_image'
                                                    ])
                                                ])
                                                ->hidden(['product_id', 'related_product_id'])
            ])
            ->withoutField([
                'language_id',
                'desc',
                'stock_qty',
                'seo_title',
                'seo_keywords',
                'seo_desc',
                'created_at',
                'updated_at',
                'deleted_at'
            ])
            ->bypk($id)
            ->hidden(['category_id'])
            ->find();

        // 处理封面图
        if (!empty($product['cover_image']) && !str_starts_with($product['cover_image'], 'http')) {
            $product['cover_image'] = image_domain_concat($product['cover_image']);
        }

        // 处理视频图片
        if (!empty($product['video_img']) && !str_starts_with($product['video_img'], 'http')) {
            $product['video_img'] = image_domain_concat($product['video_img']);
        }

        // 处理视频
        if (!empty($product['video_url']) && !str_starts_with($product['video_url'], 'http')) {
            $product['video_url'] = video_domain_concat($product['video_url']);
        }

        // 处理详情内容中图片
        if (!empty($product['detail'])) {
            $product['detail'] = html_image_replace($product['detail']);
        }

        // 处理sku中图片
        if (!empty($product['skus'])) {
            $skus = $product['skus']->toArray();
            foreach ($skus as $key => $sku) {
                // sku二级列表图
                if (!empty($sku['main_image']) && !str_starts_with($sku['main_image'], 'http')) {
                    $skus[$key]['main_image'] = image_domain_concat($sku['main_image']);
                }
                // sku相册图
                if (!empty($sku['photo_album'])) {
                    $photo_album = json_decode($sku['photo_album'], true);
                    foreach ($photo_album as $idx => $photo) {
                        if (!empty($photo) && !str_starts_with($photo, 'http')) {
                            $photo_album[$idx] = image_domain_concat($photo);
                        }
                    }
                    $skus[$key]['photo_album'] = $photo_album;
                }
                // sku属性图片
                foreach ($sku['sku_attr'] as $idx => $attr) {
                    if (!empty($attr['attr_value']) && !str_starts_with($attr['attr_value'], 'http')) {
                        $skus[$key]['sku_attr'][$idx]['attr_value'] = image_domain_concat($attr['attr_value']);
                    }
                }
            }
            $product['skus'] = $skus;
        }

        // 处理相关产品中图片
        if (!empty($product['related'])) {
            $related = $product['related']->toArray();
            foreach ($related as $key => $item) {
                if (!empty($item['cover_image']) && !str_starts_with($item['cover_image'], 'http')) {
                    $related[$key]['cover_image'] = image_domain_concat($item['cover_image']);
                }
            }
            $product['related'] = $related;
        }

        return success('success', $product);
    }
}
