<?php

namespace App\Services;

use App\Constants\HttpEnumCode;
use App\Model\OrderInquiry;
use App\Model\OrderPrescription;
use App\Model\OrderPrescriptionProduct;
use App\Model\User;
use App\Model\UserDoctor;
use App\Model\UserPharmacist;
use App\Model\UserPharmacistInfo;
use Hyperf\DbConnection\Db;

/**
 * 药师
 */
class UserPharmacistService extends BaseService
{
    /**
     * 获取药师审核处方列表
     * @return array
     */
    public function getPrescriptionList(): array
    {
        $user_info = $this->request->getAttribute("userInfo") ?? [];

        $pharmacist_audit_status = $this->request->input('pharmacist_audit_status');
        $platform_audit_status = $this->request->input('platform_audit_status');
        $page = $this->request->input('page', 1);
        $per_page = $this->request->input('per_page', 10);

        $OrderPrescriptionService = new OrderPrescriptionService();
        $prescription = $OrderPrescriptionService->getPharmacistWaitAuditPage($user_info['client_user_id'], $pharmacist_audit_status, $platform_audit_status, $page, $per_page);
        if (!empty($prescription['data'])) {
            foreach ($prescription['data'] as &$item) {
                $item['prescription_img'] = addAliyunOssWebsite($item['prescription_img']);
            }
        }
        return success($prescription);
    }

    /**
     * 设置上下线
     * @return array
     */
    public function putOnOff(): array
    {
        $user_info = $this->request->getAttribute("userInfo") ?? [];

        $is_online = $this->request->input('is_online');

        // 获取药师数据
        $params = array();
        $params['user_id'] = $user_info['user_id'];
        $user_pharmacist = UserPharmacist::getOne($params);
        if (empty($user_pharmacist)) {
            return fail();
        }

        $data = array();
        $data['is_online'] = $is_online;

        $params = array();
        $params['pharmacist_id'] = $user_pharmacist['pharmacist_id'];
        UserPharmacist::editUserPharmacist($params, $data);

        return success();
    }

    /**
     * 获取处方详情
     * @return array
     */
    public function getPrescriptionInfo(): array
    {
        $user_info = $this->request->getAttribute("userInfo") ?? [];

        $order_prescription_id = $this->request->route('order_prescription_id');

        // 获取药师数据
        $params = array();
        $params['user_id'] = $user_info['user_id'];
        $user_pharmacist = UserPharmacist::getOne($params);
        if (empty($user_pharmacist)) {
            return fail();
        }

        // 获取处方数据
        $fields = [
            "order_prescription_id",
            "order_inquiry_id",
            "prescription_status",
            "pharmacist_audit_status",
            "platform_audit_status",
            "prescription_img",
        ];

        $params = array();
        $params['order_prescription_id'] = $order_prescription_id;
        $params['pharmacist_id'] = $user_info['client_user_id'];
        $order_prescription = OrderPrescription::getOne($params, $fields);
        if (empty($order_prescription)) {
            return fail();
        }

        $order_prescription['prescription_img'] = addAliyunOssWebsite($order_prescription['prescription_img']);

        return success($order_prescription->toArray());
    }

    /**
     * 审核处方
     * @return array
     */
    public function putPrescriptionVerify(): array
    {
        $user_info = $this->request->getAttribute("userInfo") ?? [];

        $order_prescription_id = $this->request->route('order_prescription_id');
        $pharmacist_audit_status = $this->request->input('pharmacist_audit_status');
        $pharmacist_fail_reason = $this->request->input('pharmacist_fail_reason');

        // 验证器未验证未0的情况
        if ($pharmacist_audit_status == 0){
            return fail(HttpEnumCode::CLIENT_HTTP_ERROR);
        }

        // 获取药师数据
        $params = array();
        $params['user_id'] = $user_info['user_id'];
        $user_pharmacist = UserPharmacist::getOne($params);
        if (empty($user_pharmacist)) {
            return fail();
        }

        // 获取处方数据
        $params = array();
        $params['order_prescription_id'] = $order_prescription_id;
        $params['pharmacist_id'] = $user_info['client_user_id'];
        $order_prescription = OrderPrescription::getOne($params);
        if (empty($order_prescription)) {
            return fail();
        }

        // 验证处方状态
        if ($order_prescription['prescription_status'] != 1){
            // 处方状态（1:待审核 3:待使用 4:已失效 5:已使用）
            return fail(HttpEnumCode::HTTP_ERROR,"处方审核失败");
        }

        // 验证处方审核状态
        if ($order_prescription['pharmacist_audit_status'] != 0){
            // 药师审核状态（0:审核中 1:审核成功 2:审核驳回）
            return fail(HttpEnumCode::HTTP_ERROR,"处方已审核，请勿重复审核");
        }

        // 处方平台审核状态
        if ($order_prescription['platform_audit_status'] != 0){
            // 处方平台审核状态（0:审核中 1:审核成功 2:审核驳回）
            return fail(HttpEnumCode::HTTP_ERROR,"处方已审核，请勿重复审核");
        }

        // 获取处方订单数据
        $params = array();
        $params['order_inquiry_id'] = $order_prescription['order_inquiry_id'];
        $order_inquiry = OrderInquiry::getOne($params);
        if (empty($order_inquiry)){
            return fail(HttpEnumCode::SERVER_ERROR,"问诊订单数据为空");
        }

        // 获取处方商品数据
        $params = array();
        $params['order_prescription_id'] = $order_prescription['order_prescription_id'];
        $order_prescription_product = OrderPrescriptionProduct::getList($params);
        if (!empty($order_prescription_product)){
            $product_name = array_column($order_prescription_product->toArray(),'product_name');
            if (!empty($product_name)){
                $product_name = implode('、',$product_name);
            }
        }

        // 获取医生数据
        $params = array();
        $params['doctor_id'] = $order_inquiry['doctor_id'];
        $user_doctor = UserDoctor::getOne($params);
        if (empty($user_doctor)){
            return fail(HttpEnumCode::SERVER_ERROR,"医生数据错误");
        }

        Db::beginTransaction();

        try {
            // 修改处方审核状态
            $data = array();
            if ($pharmacist_audit_status == 1){
                // 审核成功
                $data['prescription_status'] = 2;
                $data['pharmacist_audit_status'] = 1;
            }else{
                $data['pharmacist_audit_status'] = 2;
                $data['pharmacist_fail_reason'] = $pharmacist_fail_reason;
            }
            $data['pharmacist_verify_time'] = date('Y-m-d H:i:s',time());

            $params = array();
            $params['order_prescription_id'] = $order_prescription_id;

            OrderPrescription::edit($params,$data);

            // 发送消息
            $ImService = new ImService();

            // 发送消息
            $cloud_custom_data = array();
            $cloud_custom_data['order_inquiry_id'] = $order_prescription['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'] = 6;
            $message_content_data['title'] = "处方审核通过";
            $message_content_data['desc'] = "";
            $message_content_data['data']['order_inquiry_id'] = $order_inquiry['order_inquiry_id'];
            $message_content_data['data']['order_prescription_id'] = $order_prescription['order_prescription_id'];
            $message_content_data['data']['product_name'] = $product_name ?? "药品";
            $message_content_data['data']['pharmacist_verify_time'] = date('Y-m-d H:i:s',time());;
            $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);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollBack();
            return fail(HttpEnumCode::HTTP_ERROR, $e->getMessage());
        }

        return success($order_prescription->toArray());
    }

    /**
     * 药师基本资料
     * @return array
     */
    public function getPharmacistInfo(): array
    {
        $user_info = $this->request->getAttribute("userInfo") ?? [];

        // 获取用户数据
        $fields = [
            'age',
            'sex',
            'avatar',
        ];
        $params = array();
        $params['user_id'] = $user_info['user_id'];
        $user = User::getOne($params,$fields);
        if (empty($user)){
            return fail();
        }

        $user['avatar'] = addAliyunOssWebsite($user['avatar']);

        // 获取药师数据
        $fields = [
            'pharmacist_id',
            'user_name',
            'pharmacist_title',
            'department_custom_name',
        ];
        $params = array();
        $params['user_id'] = $user_info['user_id'];
        $user_pharmacist = UserPharmacist::getOne($params,$fields);
        if (empty($user_pharmacist)) {
            return fail();
        }

        // 获取药师详情数据
        $fields = [
            'card_name',
            'card_num',
        ];

        $params = array();
        $params['pharmacist_id'] = $user_pharmacist['pharmacist_id'];
        $user_pharmacist_info = UserPharmacistInfo::getOne($params,$fields);
        if (empty($user_pharmacist_info)){
            return fail();
        }

        $result = array_merge($user->toArray(),$user_pharmacist->toArray(),$user_pharmacist_info->toArray());

        return success($result);
    }
}