<?php

declare(strict_types=1);

namespace App\Amqp\Consumer;

use App\Model\OrderPrescription;
use App\Model\UserPharmacist;
use App\Utils\Log;
use Hyperf\Amqp\Result;
use Hyperf\Amqp\Annotation\Consumer;
use Hyperf\Amqp\Message\ConsumerMessage;
use Hyperf\DbConnection\Db;
use PhpAmqpLib\Message\AMQPMessage;

/**
 * 分配药师
 */
#[Consumer(exchange: 'amqp.direct', routingKey: 'AssignPharmacist', queue: 'assign.pharmacist.queue', nums: 1)]
class AssignPharmacistConsumer extends ConsumerMessage
{
    public function consumeMessage($data, AMQPMessage $message): string
    {
        Log::getInstance()->error("开始执行 分配药师 队列：" . json_encode($data, JSON_UNESCAPED_UNICODE));

        Db::beginTransaction();

        try {
            // 获取订单-处方表数据
            $params = array();
            $params['order_prescription_id'] = $data['order_prescription_id'];
            $order_prescription = OrderPrescription::getOne($params);
            if (empty($order_prescription)){
                Db::rollBack();
                Log::getInstance()->error("分配药师队列执行失败：未查询到对应处方订单数据");
                return Result::DROP;// 销毁
            }

            // 检测处方状态（1:待审核 3:待使用 4:已失效 5:已使用）
            if ($order_prescription['prescription_status'] != 1){
                Db::rollBack();
                Log::getInstance()->error("分配药师队列执行失败：处方状态错误，当前为" .$order_prescription['prescription_status']);
                return Result::ACK;// 销毁
            }

            // 检测药师审核状态
            if ($order_prescription['pharmacist_audit_status'] == 1){
                Db::rollBack();
                Log::getInstance()->error("分配药师队列执行失败：药师审核状态为已通过");
                return Result::ACK;// 销毁
            }

            // 分配药师
            $params = array();
            $params['pharmacist_id'] = 3;
            $user_pharmacist = UserPharmacist::getOne($params);
            if (empty($user_pharmacist)){
                Db::rollBack();
                Log::getInstance()->error("分配药师队列执行失败：药师数据错误");
                return Result::DROP;// 销毁
            }

            // 分配药师
            $save_data = array();
            $save_data['pharmacist_id'] = $user_pharmacist['pharmacist_id'];

            $params = array();
            $params['order_prescription_id'] = $data['order_prescription_id'];
            OrderPrescription::edit($params,$save_data);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollBack();
            Log::getInstance()->error("分配药师队列执行失败原因：" . $e->getMessage());
            return Result::DROP; // 重回队列
        }

        Log::getInstance()->info("分配药师队列执行成功");

        return Result::ACK;
    }
}
