<?php

namespace App\Services;

use App\Model\InquiryCaseProduct;
use App\Model\OrderInquiry;
use App\Model\OrderInquiryCase;

/**
 * 病例
 */
class PatientCaseService extends BaseService
{
    /**
     * 获取患者最后一份问诊病例
     * @return array
     */
    public function getLastCase(): array
    {
        $family_id = $this->request->route('family_id');

        $user_info = $this->request->getAttribute("userInfo") ?? [];

        // 查询该家庭成员是否存在问诊记录
        $order_inquiry_params = array();
        $order_inquiry_params['patient_id'] = $user_info['client_user_id'];
        $order_inquiry_params['family_id'] = $family_id;
        $order_inquiry_params['inquiry_status'] = 6;// 问诊订单状态（1:待支付 2:待分配 3:待接诊 4:已接诊 5:已完成 6:已结束 7:已取消）
        $order_inquiry_params['inquiry_refund_status'] = 0;

        // 查询该家庭成员最后一次已完成的问诊病例
        $params = array();
        $params['patient_id'] = $user_info['client_user_id'];
        $params['family_id'] = $family_id;
        $params['status'] = 1;
        $order_inquiry_case = OrderInquiryCase::getEndOrderInquiryCaseOne($params,$order_inquiry_params);

        if (empty($order_inquiry_case)){
            return success('');
        }

        $order_inquiry_case = $order_inquiry_case->toArray();

        if (!empty($order_inquiry_case['order_inquiry'])){
            if ($order_inquiry_case['order_inquiry']['inquiry_type'] == 4){
                // 问诊购药存在用药意向
                $CaseService = new CaseService();
                $inquiry_case_product = $CaseService->getCaseProductlist($order_inquiry_case['inquiry_case_id']);
            }
            unset($order_inquiry_case['order_inquiry']);
        }

        // 复诊凭证
        if (!empty($order_inquiry_case['diagnose_images'])){
            $diagnose_images = explode(',',$order_inquiry_case['diagnose_images']);
            foreach ($diagnose_images as &$item){
                $item = addAliyunOssWebsite($item);
            }

            $order_inquiry_case['diagnose_images'] = $diagnose_images;
        }

        $order_inquiry_case['product'] = $inquiry_case_product ?? [];

        return success($order_inquiry_case);
    }
}