<?php
declare (strict_types=1);

namespace app\service;

use app\exception\BusinessException;
use app\model\Product;
use app\service\util\BlueBrothersClientUtil;
use BlueBrothers\Openapi\OpenapiException;

/**
 * @author canny
 * @date 2024/2/23 16:51
 **/
class ProductService extends BaseService
{
    public function __construct()
    {
        $this->model = app()->make(Product::class);
    }

    public function updateProductSaleNum($productId, $saleNum)
    {
        $product = $this->detailById($productId);
        $this->updateOne([['id', '=', $productId]], ['sale_num' => $product['sale_num'] + $saleNum]);
    }

    /**
     * @throws OpenapiException
     * @throws BusinessException
     */
    public function sync()
    {
        $list = BlueBrothersClientUtil::getClient()->RechargeProduct();
        if (empty($list['products'])) {
            throw new BusinessException('未查询到关联商品.');
        }
//        $productMapService = app()->make(ProductMapService::class);
        foreach ($list['products'] as $product) {
            $supplierProduct = Product::getBySupplierProductId($product['product_id']);
            if ($supplierProduct->isEmpty()) {
                Product::create([
                    'name' => $product['item_name'],
                    'face_amount' => $product['original_price'],
                    'price' => $product['channel_price'],
                    'supplier_product_id' => $product['product_id']
                ]);
            } else {
                Product::update([
                    'name' => $product['item_name'],
                    'face_amount' => $product['original_price'],
                    'price' => $product['channel_price']],
                    ['supplier_product_id' => $product['product_id']]);
            }
        }
    }
}