<?php

declare(strict_types=1);

namespace App\Amqp\Consumer;

use App\Model\OrderInquiry;
use App\Model\OrderInquiryCoupon;
use App\Model\UserCoupon;
use App\Model\UserDoctor;
use App\Services\ImService;
use App\Services\InquiryService;
use App\Utils\Log;
use Hyperf\Amqp\Message\ConsumerDelayedMessageTrait;
use Hyperf\Amqp\Message\ProducerDelayedMessageTrait;
use Hyperf\Amqp\Message\Type;
use Hyperf\Amqp\Result;
use Hyperf\Amqp\Annotation\Consumer;
use Hyperf\Amqp\Message\ConsumerMessage;
use Hyperf\DbConnection\Db;
use PhpAmqpLib\Message\AMQPMessage;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

/**
 * 取消未接诊问诊订单
 */
#[Consumer(nums: 1)]
class CancelUnInquiryOrdersDelayDirectConsumer extends ConsumerMessage
{
    use ProducerDelayedMessageTrait;
    use ConsumerDelayedMessageTrait;

    protected string $exchange = 'amqp.delay.direct';

    protected ?string $queue = 'cancel.uninquiry.orders.delay.queue';

    protected string $type = Type::DIRECT; //Type::FANOUT;

    protected string|array $routingKey = 'CancelUnInquiryOrders';

    /**
     * @param $data
     * @param AMQPMessage $message
     * @return string
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function consumeMessage($data, AMQPMessage $message): string
    {
        Log::getInstance()->error("开始执行 取消未接诊问诊订单 队列：" . json_encode($data, JSON_UNESCAPED_UNICODE));

        Db::beginTransaction();

        try {
            // 获取问诊订单数据
            $params = array();
            $params['order_inquiry_id'] = $data['order_inquiry_id'];
            $order_inquiry = OrderInquiry::getOne($params);
            if (empty($order_inquiry)){
                Db::rollBack();
                Log::getInstance()->error("取消未接诊问诊订单失败：未找到对应问诊订单" );
                return Result::ACK;
            }

            // 检测订单状态
            if ($order_inquiry['inquiry_status'] == 7) {
                // 问诊订单状态（1:待支付 2:待分配 3:待接诊 4:已接诊 5:已完成 6:已结束 7:已取消）
                Db::rollBack();
                Log::getInstance()->error("取消未接诊问诊订单失败：订单已取消" );
                return Result::ACK;
            }

            if ($order_inquiry['inquiry_status'] == 4) {
                // 问诊订单状态（1:待支付 2:待分配 3:待接诊 4:已接诊 5:已完成 6:已结束 7:已取消）
                Db::rollBack();
                Log::getInstance()->error("取消未接诊问诊订单失败：订单已接诊" );
                return Result::ACK;
            }

            if ($order_inquiry['inquiry_status'] != 3) {
                // 问诊订单状态（1:待支付 2:待分配 3:待接诊 4:已接诊 5:已完成 6:已结束 7:已取消）
                Db::rollBack();
                Log::getInstance()->error("取消未接诊问诊订单失败：订单状态非待接诊" );
                return Result::DROP;
            }

            if (!in_array($order_inquiry['inquiry_refund_status'], [0, 4, 5])) {
                // 问诊订单退款状态（0:无退款 1:申请退款 2:退款中 3:退款成功 4:拒绝退款 5:退款关闭）
                Db::rollBack();
                Log::getInstance()->error("取消未接诊问诊订单失败：订单正在退款中" );
                return Result::DROP;
            }

            // 取消问诊订单
            $save_data = array();
            $save_data['inquiry_status'] = 7;
            $save_data['cancel_time'] = date("Y-m-d H:i:s", time());
            $save_data['cancel_reason'] = 1; // 取消订单原因（1:医生未接诊 2:主动取消 3:无可分配医生 4:客服取消 5:支付超时）
            $save_data['cancel_remarks'] = "医生未接诊"; // 取消订单备注
            $save_data['updated_at'] = date("Y-m-d H:i:s", time());

            $params = array();
            $params['order_inquiry_id'] = $order_inquiry['order_inquiry_id'];
            OrderInquiry::edit($params, $save_data);

            // 恢复优惠卷
            if (!empty($order_inquiry['coupon_amount_total']) && $order_inquiry['coupon_amount_total'] > 0) {
                // 获取用户优惠卷信息
                $params = array();
                $params['order_inquiry_id'] = $order_inquiry['order_inquiry_id'];
                $order_inquiry_coupon = OrderInquiryCoupon::getOne($params);
                if (!empty($order_inquiry_coupon)) {
                    // 恢复优惠卷
                    $save_data = array();
                    $save_data['user_coupon_status'] = 0;
                    $save_data['coupon_use_date'] = date('Y-m-d H:i:s', time());

                    $params = array();
                    $params['user_coupon_id'] = $order_inquiry_coupon['user_coupon_id'];
                    UserCoupon::edit($params, $save_data);
                }
            }

            // 订单退款
            if ($order_inquiry['inquiry_pay_status'] == 2) {
                // 检测问诊订单执行退款次数
                $InquiryService = new InquiryService();
                $res = $InquiryService->checkInquiryRefundCount($order_inquiry['order_inquiry_id']);
                if (!$res){
                    Db::rollBack();
                    Log::getInstance()->error("取消未接诊问诊订单失败：超出最大退款次数");
                    return Result::ACK;
                }

                $InquiryService->inquiryRefund($order_inquiry['order_inquiry_id'], "医生未接诊");
                Db::commit();
                return Result::ACK;
            }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollBack();
            Log::getInstance()->error("取消未接诊问诊订单失败：" . $e->getMessage());
            return Result::REQUEUE;
        }

        Log::getInstance()->info("取消未接诊问诊订单成功");
        Log::getInstance()->info("取消未接诊问诊订单成功,发送IM消息");

        try {
            $ImService = new ImService();

            // 获取订单医生数据
            $params = array();
            $params['doctor_id'] = $order_inquiry['doctor_id'];
            $user_doctor = UserDoctor::getOne($params);
            if (empty($user_doctor)) {
                Log::getInstance()->info("取消未接诊问诊订单成功,发送IM消息失败：医生数据错误");
            }

            // 发送消息
            // 自定义消息
            $cloud_custom_data = array();
            $cloud_custom_data['order_inquiry_id'] = $order_inquiry['order_inquiry_id'];
            $cloud_custom_data['is_system'] = 1;
            $cloud_custom_data['inquiry_type'] = $order_inquiry['inquiry_type'];
            $cloud_custom_data['message_rounds'] = 0;
            $cloud_custom_data['patient_family_data']['patient_name'] = $order_inquiry['patient_name'];
            $cloud_custom_data['patient_family_data']['patient_sex'] = $order_inquiry['patient_sex'];
            $cloud_custom_data['patient_family_data']['patient_age'] = $order_inquiry['patient_age'];

            // 消息内容
            $message_content_data = array();
            $message_content_data['message_type'] = 1;
            $message_content_data['content'] = "--医生未接诊--";
            $message_content_data['desc'] = "医生因工作繁忙，未能接诊和您沟通希望见谅。平台在24小时内进行退款，钱会退回至原账户中。";

            $message_content = [
                'Data' => json_encode($message_content_data,JSON_UNESCAPED_UNICODE),
            ];

            $ImService->sendMessage($user_doctor['user_id'], $order_inquiry['user_id'], $message_content, "TIMCustomElem", $cloud_custom_data);

            Log::getInstance()->info("取消未接诊问诊订单成功,发送IM消息成功");
        } catch (\Exception $e) {
            // 验证失败
            Log::getInstance()->error("取消未接诊问诊订单成功,发送IM消息失败:" . $e->getMessage());
        }

        return Result::ACK;
    }
}
