<?php

declare(strict_types=1);

namespace App\Command;

use App\Model\Product;
use App\Model\ProductPlatformAmount;
use Extend\Prescription\Prescription;
use Hyperf\Command\Command as HyperfCommand;
use Hyperf\Command\Annotation\Command;
use Hyperf\DbConnection\Db;
use Psr\Container\ContainerInterface;

/**
 * 更新商品库存
 */
#[Command]
class getProductStockCommand extends HyperfCommand
{
    public function __construct(protected ContainerInterface $container)
    {
        parent::__construct('getProductStock:command');
    }

    public function configure()
    {
        parent::configure();
        $this->setDescription('获取处方平台商品库存数据');
    }

    public function handle()
    {
        $this->line("商品库存更新开始");

        try {
            // 获取商品
            $params = array();
            $product = Product::getPage($params,['*'],1,10);
            if (empty($product['data'])){
                $this->line("商品库存更新成功，无可更新库存商品");
                return;
            }

            $prescription = new Prescription();

            foreach ($product['data'] as $item){
                if (!empty($item['product_pharmacy_code'])){
                    $result = $prescription->getProdStock($item['product_pharmacy_code']);
                    $this->handleData($item['product_platform_id'],$item['product_platform_code'],$result[0]);
                }
            }

            if ($product['last_page'] > 1){
                for ($i = 2; $i <= $product['last_page']; $i++) {
                    // 获取商品
                    $params = array();
                    $product = Product::getPage($params,['*'],1,10);
                    if (empty($product['data'])){
                        $this->line("商品库存更新成功，无可更新库存商品");
                        return;
                    }

                    $prescription = new Prescription();

                    foreach ($product['data'] as $item){
                        if (!empty($item['product_pharmacy_code'])){
                            $result = $prescription->getProdStock($item['product_pharmacy_code']);
                            $this->handleData($item['product_platform_id'],$item['product_platform_code'],$result[0]);
                        }
                    }
                }
            }
        } catch (\Exception $e) {
            $this->line("商品库存更新失败：" . $e->getMessage());
        }

        $this->line("商品库存更新成功");
    }

    /**
     * 入库
     * @param string $product_platform_id
     * @param string $product_platform_code
     * @param array $resultData
     * @return bool
     */
    public function handleData(string $product_platform_id,string $product_platform_code,array $resultData): bool
    {
        if (empty($resultData['quantity'])){
            $resultData['quantity'] = 0;
        }
        try {
            Db::beginTransaction();

            $params = array();
            $params['product_platform_id'] = $product_platform_id;
            $params['product_platform_code'] = $product_platform_code;
            $product_platform_amount = ProductPlatformAmount::getSharedLockOne($params);
            if (empty($product_platform_amount)){
                // 无库存数据，新增
                $data = array();
                $data['product_platform_id'] = $product_platform_id;
                $data['product_platform_code'] = $product_platform_code;
                $data['stock'] = $resultData['quantity'];
                $product_platform_amount = ProductPlatformAmount::addProductPlatformAmount($data);
                if (empty($product_platform_amount)){
                    Db::rollBack();
                    $this->line("商品库存更新失败，无法新增库存数据" . json_encode($data, JSON_UNESCAPED_UNICODE));
                }
            }else{
                // 存在库存数据，修改
                $data = array();
                $data['stock'] = $resultData['quantity'];

                $params = array();
                $params['amount_id'] = $product_platform_amount['amount_id'];
                ProductPlatformAmount::edit($params,$data);
            }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollBack();
            $this->line("商品库存更新失败：" . $e->getMessage());
            return false;
        }

        return true;
    }
}
