<?php

namespace App\Services;

use App\Constants\HttpEnumCode;
use App\Exception\BusinessException;
use App\Model\DoctorInquiryConfig;
use App\Model\DoctorInquiryPriceRecord;
use App\Model\SystemInquiryConfig;
use App\Model\UserDoctor;
use Hyperf\DbConnection\Db;

/**
 * 医生问诊
 */
class DoctorInquiryService extends BaseService
{
    /**
     * 获取医生问诊配置
     * @return array
     */
    public function getInquiryConfig(): array
    {
        $user_info = $this->request->getAttribute("userInfo") ?? [];

        $inquiry_type = $this->request->input('inquiry_type');// 接诊类型（1:专家问诊 2:快速问诊 3:公益问诊）
        $inquiry_mode = $this->request->input('inquiry_mode');// 接诊方式（1:图文 2:视频 3:语音 4:电话 5:会员）

        $result = array();
        $result['info'] = array(); // 配置信息
        $result['config'] = array(); // 系统配置

        // 获取医生信息
        $params = array();
        $params['doctor_id'] = $user_info['client_user_id'];
        $doctor = UserDoctor::getOne($params);
        if (empty($doctor)) {
            return fail(HttpEnumCode::HTTP_ERROR, "未知医生");
        }

        if ($doctor['idcard_status'] != 1) {
            return fail(HttpEnumCode::HTTP_ERROR, "请先进行实名认证");
        }

        if ($doctor['iden_auth_status'] != 1) {
            return fail(HttpEnumCode::HTTP_ERROR, "请先进行身份认证");
        }

        if ($doctor['is_bind_bank'] != 1) {
            return fail(HttpEnumCode::HTTP_ERROR, "请先进行绑定结算银行卡");
        }

        // 接诊开关
        $result['info']['is_open'] = 0;
        if ($inquiry_type == 1) {
            // 专家
            $result['info']['is_open'] = $doctor['is_img_expert_reception'];
        } elseif ($inquiry_type == 2) {
            // 快速
            $result['info']['is_open'] = $doctor['is_img_quick_reception'];
        } elseif ($inquiry_type == 3) {
            // 公益
            $result['info']['is_open'] = $doctor['is_img_welfare_reception'];
        }

        // 接诊价格
        $result['info']['inquiry_price'] = 0;

        // 接诊人数
        $result['info']['work_num_day'] = 30;

        // 系统问诊配置表
        $params = array();
        $params['inquiry_type'] = $inquiry_type;
        $params['inquiry_mode'] = $inquiry_mode;
        $system_inquiry_config = SystemInquiryConfig::getOne($params);
        if (empty($system_inquiry_config)) {
            return fail(HttpEnumCode::SERVER_ERROR);
        }

        // 医生接诊配置表
        $params = array();
        $params['doctor_id'] = $user_info['client_user_id'];
        $params['inquiry_type'] = $inquiry_type;
        $params['inquiry_mode'] = $inquiry_mode;
        $doctor_inquiry_config = DoctorInquiryConfig::getOne($params);
        if (empty($doctor_inquiry_config)) {
            // 接诊价格
            $result['info']['inquiry_price'] = $system_inquiry_config['inquiry_price'] ?: 0;
            if ($inquiry_type == 3) {
                // 公益问诊，存在价格档次,默认第一档
                $inquiry_price = explode(',', $system_inquiry_config['inquiry_price']);

                $result['info']['inquiry_price'] = $inquiry_price[0];
            }
        } else {
            // 接诊价格
            $result['info']['inquiry_price'] = $doctor_inquiry_config['inquiry_price'] ?: 0;
            if ($inquiry_type == 2) {
                // 快速-系统配置
                $result['info']['inquiry_price'] = $system_inquiry_config['inquiry_price'];
            }

            $result['info']['work_num_day'] = $doctor_inquiry_config['work_num_day'] ?: 0;
        }

        // 每日最大接诊数量
        $result['config']['max_work_num_day'] = $system_inquiry_config['max_work_num_day'];

        // 最低接诊价格（专家问诊）
        $result['config']['min_inquiry_price'] = $system_inquiry_config['min_inquiry_price'] ?: 0;

        // 最高接诊价格（专家问诊）
        $result['config']['max_inquiry_price'] = $system_inquiry_config['max_inquiry_price'] ?: 0;

        // 默认价格
        $result['config']['default_inquiry_price'] = $system_inquiry_config['max_inquiry_price'] ?: 0;

        // 沟通次数（0为不限制次数）
        $result['config']['times_number'] = $system_inquiry_config['times_number'];

        // 沟通时长（分钟，0为不限制时长）
        $result['config']['duration'] = $system_inquiry_config['duration'];

        // 系统价格（公益问诊）
        $result['config']['system_inquiry_price'] = [];
        if ($inquiry_type == 3) {
            $result['config']['system_inquiry_price'] = explode(',', $system_inquiry_config['inquiry_price']);
        }

        return success($result);
    }

    /**
     * 医生问诊开关
     * @return array
     */
    public function putInquiryOpen(): array
    {
        $user_info = $this->request->getAttribute("userInfo") ?? [];

        $inquiry_type = $this->request->input('inquiry_type');// 接诊类型（1:专家问诊 2:快速问诊 3:公益问诊）
        $inquiry_mode = $this->request->input('inquiry_mode');// 接诊方式（1:图文 2:视频 3:语音 4:电话 5:会员）
        $is_open = $this->request->input('is_open');// 是否开启（1:开启 0:关闭）

        // 获取医生信息
        $params = array();
        $params['doctor_id'] = $user_info['client_user_id'];
        $doctor = UserDoctor::getOne($params);
        if (empty($doctor)) {
            return fail(HttpEnumCode::HTTP_ERROR, "未知医生");
        }

        if ($doctor['idcard_status'] != 1) {
            return fail(HttpEnumCode::HTTP_ERROR, "请先进行实名认证");
        }

        if ($doctor['iden_auth_status'] != 1) {
            return fail(HttpEnumCode::HTTP_ERROR, "请先进行身份认证");
        }

        if ($doctor['is_bind_bank'] != 1) {
            return fail(HttpEnumCode::HTTP_ERROR, "请先进行绑定结算银行卡");
        }

        // 医生接诊配置表
        $params = array();
        $params['doctor_id'] = $user_info['client_user_id'];
        $params['inquiry_type'] = $inquiry_type;
        $params['inquiry_mode'] = $inquiry_mode;
        $doctor_inquiry_config = DoctorInquiryConfig::getOne($params);
        if (empty($doctor_inquiry_config)) {
            if ($inquiry_type != 2) {
                // 快速问诊可能会存在未创建的情况
                return fail(HttpEnumCode::HTTP_ERROR, "请先完善问诊配置");
            }
        }

        Db::beginTransaction();
        try {
            $params = array();
            $params['doctor_id'] = $user_info['client_user_id'];

            $data = array();
            if ($inquiry_type == 1) {
                // 专家
                $data['is_img_expert_reception'] = $is_open;
                $data['is_online'] = $is_open;
            } elseif ($inquiry_type == 2) {
                // 快速
                $data['is_img_quick_reception'] = $is_open;
            } elseif ($inquiry_type == 3) {
                // 公益
                $data['is_img_welfare_reception'] = $is_open;
            }

            UserDoctor::editUserDoctor($params, $data);

            if ($inquiry_type == 2 && $is_open == 1) {
                $params = array();
                $params['doctor_id'] = $user_info['client_user_id'];
                $params['inquiry_type'] = $inquiry_type;
                $params['inquiry_mode'] = $inquiry_mode;
                $doctor_inquiry_config = DoctorInquiryConfig::getOne($params);
                if (empty($doctor_inquiry_config)) {
                    // 系统问诊配置表
                    $params = array();
                    $params['inquiry_type'] = $inquiry_type;
                    $params['inquiry_mode'] = $inquiry_mode;
                    $system_inquiry_config = SystemInquiryConfig::getOne($params);
                    if (empty($system_inquiry_config)) {
                        Db::rollBack();
                        return fail(HttpEnumCode::SERVER_ERROR);
                    }

                    // 快速问诊,需创建
                    $data = array();
                    $data['doctor_id'] = $user_info['client_user_id'];
                    $data['system_inquiry_config_id'] = $system_inquiry_config['system_inquiry_config_id'];
                    $data['inquiry_type'] = $inquiry_type;
                    $data['inquiry_mode'] = $inquiry_mode;
                    $data['work_num_day'] = $system_inquiry_config['max_work_num_day'] ?: 0;
                    $data['inquiry_price'] = $system_inquiry_config['inquiry_price'];

                    $doctor_inquiry_config = DoctorInquiryConfig::addInquiryConfig($data);
                    if (empty($doctor_inquiry_config)) {
                        Db::rollBack();
                        return fail(HttpEnumCode::SERVER_ERROR);
                    }
                }
            }

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

        return success();
    }

    /**
     * 修改医生问诊配置
     * @return array
     */
    public function putInquiryConfig(): array
    {
        $user_info = $this->request->getAttribute("userInfo") ?? [];

        $inquiry_type = $this->request->input('inquiry_type');// 接诊类型（1:专家问诊 2:快速问诊 3:公益问诊）
        $inquiry_mode = $this->request->input('inquiry_mode');// 接诊方式（1:图文 2:视频 3:语音 4:电话 5:会员）
        $inquiry_price = $this->request->input('inquiry_price');// 接诊价格
        $work_num_day = $this->request->input('work_num_day');// 每日接诊数量

        if ($inquiry_type == 2) {
            // 快速问诊无需配置
            return fail();
        }

        // 获取医生信息
        $params = array();
        $params['doctor_id'] = $user_info['client_user_id'];
        $doctor = UserDoctor::getOne($params);
        if (empty($doctor)) {
            return fail(HttpEnumCode::HTTP_ERROR, "未知医生");
        }

        if ($doctor['idcard_status'] != 1) {
            return fail(HttpEnumCode::HTTP_ERROR, "请先进行实名认证");
        }

        if ($doctor['iden_auth_status'] != 1) {
            return fail(HttpEnumCode::HTTP_ERROR, "请先进行身份认证");
        }

        if ($doctor['is_bind_bank'] != 1) {
            return fail(HttpEnumCode::HTTP_ERROR, "请先进行绑定结算银行卡");
        }

        // 系统问诊配置表
        $params = array();
        $params['inquiry_type'] = $inquiry_type;
        $params['inquiry_mode'] = $inquiry_mode;
        $system_inquiry_config = SystemInquiryConfig::getOne($params);
        if (empty($system_inquiry_config)) {
            return fail(HttpEnumCode::SERVER_ERROR);
        }

        // 验证-每日接诊数量
        if ($work_num_day > $system_inquiry_config['max_work_num_day']) {
            return fail(HttpEnumCode::HTTP_ERROR, "超出每日最大接诊数量");
        }

        // 验证-问诊价格
        // 义诊时不判断，义诊为选择价格，价格后台可调节
        if ($inquiry_type == 3) {
            if (!empty($system_inquiry_config['min_inquiry_price']) && !empty($system_inquiry_config['max_inquiry_price'])) {
                if ($inquiry_price > $system_inquiry_config['max_inquiry_price'] || $inquiry_price < $system_inquiry_config['min_inquiry_price']) {
                    return fail(HttpEnumCode::HTTP_ERROR, "问诊价格填写错误");
                }
            }
        }

        // 开启事务锁
        Db::beginTransaction();
        try {
            // 医生接诊配置表
            $params = array();
            $params['doctor_id'] = $user_info['client_user_id'];
            $params['inquiry_type'] = $inquiry_type;
            $params['inquiry_mode'] = $inquiry_mode;
            $doctor_inquiry_config = DoctorInquiryConfig::getOne($params);
            if (empty($doctor_inquiry_config)) {
                // 创建
                $data = array();
                $data['doctor_id'] = $user_info['client_user_id'];
                $data['system_inquiry_config_id'] = $system_inquiry_config['system_inquiry_config_id'];
                $data['inquiry_type'] = $inquiry_type;
                $data['inquiry_mode'] = $inquiry_mode;
                $data['work_num_day'] = $work_num_day;
                $data['inquiry_price'] = $inquiry_price;

                $doctor_inquiry_config = DoctorInquiryConfig::addInquiryConfig($data);
                if (empty($doctor_inquiry_config)) {
                    Db::rollBack();
                    return fail(HttpEnumCode::SERVER_ERROR);
                }

                // 记录修改记录
                $data = array();
                $data['doctor_id'] = $user_info['client_user_id'];
                $data['inquiry_config_id'] = $doctor_inquiry_config['inquiry_config_id'];
                $data['old_price'] = 0;
                $data['new_price'] = $inquiry_price;
                $doctor_inquiry_price_record = DoctorInquiryPriceRecord::addRecord($data);
                if (empty($doctor_inquiry_price_record)) {
                    Db::rollBack();
                    return fail(HttpEnumCode::SERVER_ERROR);
                }
            } else {
                // 在线问诊限制在线问诊验证修改次数
                if ($inquiry_type == 1 && $doctor_inquiry_config['inquiry_price'] != $inquiry_price) {
                    // 获取月份内总调整次数
                    $params = array();
                    $params[] = ['doctor_id', '=', $user_info['client_user_id']];
                    $params[] = ['inquiry_config_id', '=', $doctor_inquiry_config['inquiry_config_id']];
                    $params[] = ['created_at', '>', date('Y-m-01', time())];
                    $modify_month_count = DoctorInquiryPriceRecord::getCount($params);
                    if ($modify_month_count >= 5) {
                        // 每自然月仅限调整5次
                        Db::rollBack();
                        return fail(HttpEnumCode::HTTP_ERROR, "问诊价格每自然月仅限调整5次");
                    }

                    $params = array();
                    $params[] = ['doctor_id', '=', $user_info['client_user_id']];
                    $params[] = ['inquiry_config_id', '=', $doctor_inquiry_config['inquiry_config_id']];
                    $params[] = ['created_at', '>', date('Y-m-d', time())];
                    $modify_month_count = DoctorInquiryPriceRecord::getCount($params);
                    if ($modify_month_count >= 1) {
                        // 问诊价格每日仅限调整1次
                        Db::rollBack();
                        return fail(HttpEnumCode::HTTP_ERROR, "问诊价格每日仅限调整1次");
                    }
                }

                // 修改
                if ($doctor_inquiry_config['work_num_day'] != $work_num_day || $doctor_inquiry_config['inquiry_price'] != $inquiry_price) {
                    $params = array();
                    $params['inquiry_config_id'] = $doctor_inquiry_config['inquiry_config_id'];

                    $data = array();
                    $data['work_num_day'] = $work_num_day;
                    $data['inquiry_price'] = $inquiry_price;

                    DoctorInquiryConfig::editInquiryConfig($params, $data);

                    // 记录修改记录
                    $data = array();
                    $data['doctor_id'] = $user_info['client_user_id'];
                    $data['inquiry_config_id'] = $doctor_inquiry_config['inquiry_config_id'];
                    $data['old_price'] = $doctor_inquiry_config['inquiry_price'];
                    $data['new_price'] = $inquiry_price;
                    $doctor_inquiry_price_record = DoctorInquiryPriceRecord::addRecord($data);
                    if (empty($doctor_inquiry_price_record)) {
                        Db::rollBack();
                        return fail(HttpEnumCode::SERVER_ERROR);
                    }
                }
            }

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

        return success();
    }

    /**
     * 获取医生问诊价格
     * @param string|int $inquiry_type 订单类型（1:专家问诊 2:快速问诊 3:公益问诊 4:问诊购药）
     * @param string|int $inquiry_mode 订单问诊方式（1:图文 2:视频 3:语音 4:电话 5:会员）
     * @param string|int $doctor_id 医生id
     */
    public function getDoctorInquiryPrice(string|int $inquiry_type, string|int $inquiry_mode, string|int $doctor_id):float
    {
        // 接诊类型（1:专家问诊 2:快速问诊 3:公益问诊）
        if ($inquiry_type == 1 || $inquiry_type == 3) {
            // 专家-公益
            $params = array();
            $params['doctor_id'] = $doctor_id;
            $params['inquiry_type'] = $inquiry_type;
            $params['inquiry_mode'] = $inquiry_mode;
            $doctor_inquiry_config = DoctorInquiryConfig::getOne($params);
            if (empty($doctor_inquiry_config)) {
                throw new BusinessException("当前医生未开通对应服务，请重新选择", HttpEnumCode::HTTP_ERROR);
            }

            $inquiry_price = $doctor_inquiry_config['inquiry_price'] ?: 0;
        } elseif ($inquiry_type == 2 || $inquiry_type == 4) {
            // 快速-购药
            $params = array();
            $params['inquiry_type'] = $inquiry_type;
            $params['inquiry_mode'] = $inquiry_mode;
            $system_inquiry_config = SystemInquiryConfig::getOne($params);
            if (empty($system_inquiry_config)) {
                throw new BusinessException();
            }

            $inquiry_price = $system_inquiry_config['inquiry_price'] ?: 0;
        } else {
            throw new BusinessException();
        }

        return $inquiry_price;
    }
}