<?php

declare(strict_types=1);

namespace App\Command;

use App\Model\Product;
use App\Model\ProductPlatform;
use App\Utils\Log;
use Extend\Prescription\Prescription;
use Hyperf\Command\Command as HyperfCommand;
use Hyperf\Command\Annotation\Command;
use Hyperf\DbConnection\Db;
use Psr\Container\ContainerInterface;
use Symfony\Component\Console\Input\InputArgument;

/**
 * 更新处方平台商品
 */
#[Command]
class getProductCommand extends HyperfCommand
{
    public function __construct(protected ContainerInterface $container)
    {
        parent::__construct('getProduct:command');
    }

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

    // 主逻辑处理
    public function handle()
    {
        $this->line("商品更新开始");

        try {
            $prescription = new Prescription();

            $page = 1;
            $page_size = 10;
            $result = $prescription->getProd(1, 10);
            if (!empty($result['rows'])){
                foreach ($result['rows'] as $item) {
                    // 执行入库
                    $this->handleData($item);
                }

                $count = ceil($result['count'] / $page * $page_size);

                if ($result['count'] > $page * $page_size) {
                    for ($i = 2; $i < $count; $i++) {
                        $result = $prescription->getProd($i, $page_size);
                        foreach ($result['rows'] as $item) {
                            // 执行入库
                            $this->handleData($item);
                        }
                    }
                }
            }
        } catch (\Exception $e) {
            $this->line("商品更新失败：" . $e->getMessage());
        }

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

    /**
     * 参数设置
     * @return array[]
     */
    protected function getArguments(): array
    {
        return [
//            ['sign', InputArgument::REQUIRED, '签名数据']
        ];
    }

    /**
     * 入库
     * @param array $item
     * @return bool
     */
    protected function handleData(array $item): bool
    {
        try {
            Db::beginTransaction();

            if (empty($item['drugCode'])) {
                Db::rollBack();
                $this->line("商品更新失败，缺少平台药品编码" . json_encode($item, JSON_UNESCAPED_UNICODE));
                return false;
            }

            if (empty($item['drugPrice'])) {
                Db::rollBack();
                $this->line("商品更新失败，缺少药品价格" . json_encode($item, JSON_UNESCAPED_UNICODE));
                return false;
            }

            // 查询是否存在
            $params = array();
            $params['product_platform_code'] = $item['drugCode'];
            $product_platform = ProductPlatform::getOne($params);
            if (!empty($product_platform)) {
                // 已存在，更新
                $product_platform_data = array();
                $product_data = array();

                // 商品名称
                if (isset($item['tradeName'])) {
                    if ($product_platform['product_name'] != $item['tradeName']) {
                        $product_platform_data['product_name'] = $item['tradeName'];
                        $product_data['product_name'] = $item['tradeName'];
                    }
                }

                // 商品价格
                if ($product_platform['product_price'] != $item['drugPrice']) {
                    $product_platform_data['product_price'] = $item['drugPrice'];
                    $product_data['product_price'] = $item['drugPrice'];
                }

                // 药品类型
                if (isset($item['drugClassCode'])) {
                    if ($item['drugClassCode'] == 1) {
                        $product_type = 1;
                    } elseif ($item['drugClassCode'] == 2) {
                        $product_type = 2;
                    } else {
                        $product_type = 0;
                    }

                    if ($product_platform['product_type'] != $product_type) {
                        $product_platform_data['product_type'] = $product_type;
                        $product_data['product_type'] = $product_type;
                    }
                }

                // 商品规格
                if (isset($item['specifications'])) {
                    if ($product_platform['product_spec'] != $item['specifications']) {
                        $product_platform_data['product_spec'] = $item['specifications'];
                        $product_data['product_spec'] = $item['specifications'];
                    }
                }

                // 批准文号
                if (isset($item['approvalNumber'])) {
                    if ($product_platform['license_number'] != $item['approvalNumber']) {
                        $product_platform_data['license_number'] = $item['approvalNumber'];
                        $product_data['license_number'] = $item['approvalNumber'];
                    }
                }

                // 生产厂家
                if (isset($item['manufacturer'])) {
                    if ($product_platform['manufacturer'] != $item['manufacturer']) {
                        $product_platform_data['manufacturer'] = $item['manufacturer'];
                        $product_data['manufacturer'] = $item['manufacturer'];
                    }
                }

                // 零售包装单位
                if (isset($item['packingUnit'])) {
                    if ($product_platform['retail_unit'] != $item['packingUnit']) {
                        $product_platform_data['retail_unit'] = $item['packingUnit'];
                        $product_data['packaging_unit'] = $item['packingUnit']; // 平台返回零售包装单位为：盒，此结果适用于商品表的基本包装单位
                    }
                }

                // 第三方药店商品编码
                if (isset($item['thirdDrugCode'])) {
                    if ($product_platform['product_pharmacy_code'] != $item['thirdDrugCode']) {
                        $product_platform_data['product_pharmacy_code'] = $item['thirdDrugCode'];
                        $product_data['product_pharmacy_code'] = $item['thirdDrugCode'];
                    }
                }

                // 基本包装数量
                if (isset($item['basicPackingCount'])) {
                    if ($product_platform['packaging_count'] != $item['basicPackingCount']) {
                        $product_platform_data['packaging_count'] = $item['basicPackingCount'];
                    }
                }

                // 基本包装单位
                if (isset($item['basicPackingUnit'])) {
                    if ($product_platform['packaging_unit'] != $item['basicPackingUnit']) {
                        $product_platform_data['packaging_unit'] = $item['basicPackingUnit'];
                    }
                }

                // 单次剂量单位
                if (isset($item['defaultSingleDosageUnit'])) {
                    if ($product_platform['single_unit'] != $item['defaultSingleDosageUnit']) {
                        $product_platform_data['single_unit'] = $item['defaultSingleDosageUnit'];
                    }
                }

                if (!empty($product_platform_data)) {
                    // 更新商品表-处方平台
                    $params = array();
                    $params['product_platform_id'] = $product_platform['product_platform_id'];
                    ProductPlatform::edit($params, $product_platform_data);

                    if (!empty($product_data)) {
                        // 获取商品表数据
                        $params = array();
                        $params['product_platform_id'] = $product_platform['product_platform_id'];
                        $product = Product::getOne($params);
                        if (!empty($product)) {
                            // 更新商品表
                            $params = array();
                            $params['product_platform_id'] = $product_platform['product_platform_id'];
                            Product::edit($params, $product_data);
                        }
                    }
                }
            } else {
                // 不存在，创建
                $data = array();
                // 商品名称
                if (isset($item['tradeName'])) {
                    $data['product_name'] = $item['tradeName'];
                }

                // 商品价格
                $data['product_price'] = $item['drugPrice'];

                // 药品类型
                if (isset($item['drugClassCode'])) {
                    if ($item['drugClassCode'] == 1) {
                        $data['product_type'] = 1;
                    } elseif ($item['drugClassCode'] == 2) {
                        $data['product_type'] = 2;
                    } else {
                        $data['product_type'] = 0;
                    }
                }

                // 处方平台商品编码
                $data['product_platform_code'] = $item['drugCode'];

                // 第三方药店商品编码
                if (isset($item['thirdDrugCode'])) {
                    $data['product_pharmacy_code'] = $item['thirdDrugCode'];
                }

                // 商品规格
                if (isset($item['specifications'])) {
                    $data['product_spec'] = $item['specifications'];
                }

                // 批准文号
                if (isset($item['approvalNumber'])) {
                    $data['license_number'] = $item['approvalNumber'];
                }

                // 生产厂家
                if (isset($item['manufacturer'])) {
                    $data['manufacturer'] = $item['manufacturer'];
                }

                // 单次剂量单位
                if (isset($item['defaultSingleDosageUnit'])) {
                    $data['single_unit'] = $item['defaultSingleDosageUnit'];
                }

                // 基本包装单位
                if (isset($item['basicPackingUnit'])) {
                    $data['packaging_unit'] = $item['basicPackingUnit'];
                }

                // 基本包装数量
                if (isset($item['basicPackingCount'])) {
                    $data['packaging_count'] = $item['basicPackingCount'];
                }

                // 零售包装单位
                if (isset($item['packingUnit'])) {
                    $data['retail_unit'] = $item['packingUnit'];
                }

                $product_platform = ProductPlatform::addProductPlatform($data);
                if (empty($product_platform)) {
                    Db::rollBack();
                    $this->line("商品更新失败：" . json_encode($data, JSON_UNESCAPED_UNICODE));
                }
            }

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

        return true;
    }
}
