User.php 32.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853
<?php

namespace app\api\controller;

use addons\third\model\Third;
use app\api\model\Appointment;
use app\api\model\AppointmentAppraise;
use app\api\model\AppointmentLog;
use app\api\model\Doctor;
use app\api\model\DoctorLevel;
use app\api\model\DoctorReceiveNum;
use app\api\model\Gift;
use app\api\model\GiftOrder;
use app\api\model\UserCollectDoctor;
use app\common\controller\Api;
use app\common\controller\Tim;
use app\common\controller\Wechat;
use think\Db;
use think\Exception;
use think\exception\PDOException;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'getWxMiniProgramSessionKey', 'wxMiniProgramLogin', 'giftList', 'aboutUs'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * @ApiWeigh (99)
     * @ApiTitle    (个人中心)
     * @ApiSummary  (个人中心)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name="token", type="string", required=true, description="token")
     * @ApiReturn   ({
        "code": 1,
        "msg": "成功",
        "time": "1624523616",
        "data": {
            "user": { //用户信息
                "id": 1, //用户ID
                "nickname": "这是昵称啊", //昵称
                "avatar": "http://yanji-spider.oss-cn-hangzhou.aliyuncs.com/uploads/20210526/3451459c2469a191a84de24d2e6852b5.png", //头像地址
                "identity": "1", //身份:1=普通用户,2=医生
                "url": "/u/1"
            }
        }
    })
     */
    public function index()
    {
        $user = $this->auth->getUser()->visible(['id','nickname','avatar','identity']);
        $user['avatar'] = cdnurl($user['avatar'],true);
        $this->success('成功', compact('user'));
    }

    /**
     * @ApiWeigh (97)
     * @ApiTitle    (修改会员个人信息)
     * @ApiSummary  (修改会员个人信息)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name="token", type="string", required=true, description="token")
     * @ApiParams  (name="avatar", type="string", required=true, description="头像地址")
     * @ApiParams  (name="nickname", type="string", required=true, description="昵称")
     * @ApiReturn   ({
        "code": 1,
        "msg": "",
        "time": "1620711606",
        "data": null
    })
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $nickname = $this->request->param('nickname');
        $avatar = $this->request->param('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if(!$nickname && !$avatar){
            $this->error('请修改昵称或头像');
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        if($avatar){
            $user->avatar = $avatar;
        }
        $user->save();
        $this->success('成功');
    }

    /**
     * @ApiWeigh    (95)
     * @ApiTitle    (获取微信小程序session_key)
     * @ApiSummary  (获取微信小程序session_key)
     * @ApiMethod   (POST)
     * @ApiParams (name=code, type=string, required=true, description="加密code")
     * @ApiReturn({
        "code": 1,
        "msg": "用户信息",
        "time": "1607588102",
        "data": {
            "openid": 123456, //openid
            "session_key": 123456, //session_key
        }
    })
     */
    public function getWxMiniProgramSessionKey()
    {
        $post = $this->request->post();
        empty($post['code']) && $this->error('缺少必需参数');
        $decryptSession = Wechat::miniProgram()->auth->session($post['code']);
        $this->success('获取session_key', $decryptSession);
    }

    /**
     * @ApiWeigh    (91)
     * @ApiTitle    (微信小程序登录)
     * @ApiSummary  (微信小程序登录)
     * @ApiMethod   (POST)
     * @ApiParams (name=session_key, type=string, required=true, description="session_key")
     * @ApiParams (name=iv, type=string, required=true, description="iv")
     * @ApiParams (name=encryptedData, type=string, required=true, description="encryptedData")
     * @ApiParams (name=openid, type=string, required=true, description="openid")
     * @ApiParams (name=unionid, type=string, required=false, description="unionid")
     * @ApiReturn({
        "code": 1,
        "msg": "Logged in successful",
        "time": "1622016289",
        "data": {
            "userinfo": {
                "id": 85, //用户ID
                "nickname": "我无所谓", //昵称
                "mobile": "15133120361", //手机号
                "avatar": "https://thirdwx.qlogo.cn/mmopen/vi_32/dPXsS9sic6XQQckbwdHibS2tfv44SbSpu8tR5BnenKfeILpeXo9p7g7Pk9vgVicyBaGWPwIv8MgAaqNy6xExSBsrA/132", //头像
                "gender": 1,
                "token": "8ef2b809-68db-4788-b2b1-d1df9746d13c", //登录token
                "user_id": 85,
                "createtime": 1622016290,
                "expiretime": 1624608290,
                "expires_in": 2592000
            }
        }
    })
     */
    public function wxMiniProgramLogin()
    {
        $post = $this->request->post();
        $decryptUserInfo = Wechat::miniProgram()->encryptor->decryptData($post['session_key'], $post['iv'], $post['encryptedData']);
        //组装decryptData
        $decryptData = array_change_key_case($decryptUserInfo, CASE_LOWER);
        $decryptData['avatar'] = isset($decryptData['avatarurl']) ? $decryptData['avatarurl'] : '';
        $decryptData['access_token'] = '';
        $decryptData['refresh_token'] = '';
        $decryptData['expires_in'] = 7200;

        // 2021年4月13之后的获取不到openid和unionid
        $decryptData['openid'] = empty($decryptData['openid']) ? $post['openid'] : $decryptData['openid'];
        $decryptData['unionid'] = empty($decryptData['unionid']) ? (!empty($post['unionid']) ? $post['unionid'] : '') : $decryptData['unionid'];

        if (empty($decryptData['openid'])) {
            $this->error(__('code错误'), $decryptData);
        }

        $loginret = \addons\third\library\Service::connect('wechat', $decryptData);
        if ($loginret) {
            $this->auth->setAllowFields(['id', 'nickname', 'avatar', 'identity']);
            $data = [
                'userinfo'  => $this->auth->getUserinfo()
            ];
            $this->success(__('Logged in successful'), $data);
        }
        $this->error($this->auth->getError());
    }

    /**
     * @ApiWeigh    (90)
     * @ApiTitle    (用户授权获取手机号)
     * @ApiSummary  (用户授权获取手机号)
     * @ApiMethod   (POST)
     * @ApiParams   (name="sessionKey", type="string", required=true, description="小程序sessionKey")
     * @ApiParams   (name="iv", type="string", required=true, description="小程序iv")
     * @ApiParams   (name="encryptedData", type="string", required=true, description="小程序encryptedData")
     * @ApiParams   (name="openid", type="string", required=true, description="openid")
     * @ApiReturn   ({
        'code':'1',
        'msg':'返回成功',
        "data": {
            "phoneNumber": "13580006666", //用户绑定的手机号(国外手机号会有区号)
            "purePhoneNumber": "13580006666", //没有区号的手机号
            "countryCode": "86", //区号
            "watermark": {
                "appid": "APPID",
                "timestamp": TIMESTAMP
            }
        }
    })
     */
    public function getPhoneNumber()
    {
        $param = $this->request->param();
        $validate = new \think\Validate([
            'sessionKey' => 'require',
            'iv' => 'require',
            'encryptedData' => 'require',
            'openid' => 'require'
        ]);
        $validate->message([
            'sessionKey.require' => 'sessionKey参数错误!',
            'iv.require' => 'iv参数错误!',
            'encryptedData.require' => 'encryptData参数错误!',
            'openid.require' => 'openid参数错误!'
        ]);
        if (!$validate->check($param)) {
            $this->error($validate->getError());
        }
        // 获取小程序配置
        $app = Wechat::miniProgram();
        $data = $app->encryptor->decryptData($param['sessionKey'], $param['iv'], $param['encryptedData']);
        // 新用户绑定手机号
        $third = Third::where('openid',$param['openid'])->field('user_id')->find();
        $user = \app\common\model\User::get($third['user_id']);
        if(!empty($data['phoneNumber']) && $third && $user){
            $user->save(['mobile'=>$data['phoneNumber']]);
        }
        $this->success('授权成功',$data);
    }

    /**
     * @ApiWeigh    (89)
     * @ApiTitle    (预约列表)
     * @ApiSummary  (预约列表)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name="token", type="string", required=true, description="token")
     * @ApiParams   (name=status, type=integer, required=true, description="状态:1=未开始,2=诊断中,3=已完成,4=待评价")
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1625561885",
        "data": {
            "total": 1, //数据总数
            "per_page": 10,
            "current_page": 1,
            "last_page": 1,
            "data": [{ //列表
                "id": 1, //预约ID
                "date": "2021-07-06", //预约日期
                "type": "1", //服务类型:1=文字沟通,1=音频沟通
                "status": "1", //状态:1=未开始,2=诊断中,3=已完成
                "diagnose_time": { //诊断时间
                    "hours": 0, //时
                    "minutes": 0, //分
                    "seconds": 39 //秒
                },
                "doctor": { //医生信息
                    "id": 1, //ID
                    "nickname": "小何", //姓名
                    "avatar": "http://www.consultation.top/assets/img/qrcode.png", //头像
                    "level": 2 //等级
                },
                "dept_list": [{ //专科列表
                    "id": 1, //ID
                    "name": "骨科与神经外科" //名称
                }]
            }]
        }
    })
     */
    public function appointmentList(){
        $status = $this->request->post('status');
        empty($status) && $this->error('缺少必需参数');
        $where['user_id'] = $this->auth->id;
        if($status != 4){
            $where['status'] = $status;
        }else{
            $where['status'] = '3';
            $where['is_appraise'] = '0';
        }
        $list = Appointment::with(['doctor'])
            ->where($where)
            ->paginate(10)
            ->each(function ($v){
                $v->visible(['id','date','type','status','diagnose_time','doctor'])->append(['dept_list']);
                if($v->getRelation('doctor')){
                    $v->getRelation('doctor')->visible(['id','nickname','avatar'])->append(['level']);
                }else{
                    $v['doctor'] = (Object)[];
                }
            });
        $this->success('成功',$list);
    }

    /**
     * @ApiWeigh    (89)
     * @ApiTitle    (预约详情)
     * @ApiSummary  (预约详情)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name="token", type="string", required=true, description="token")
     * @ApiParams   (name=appointment_id, type=integer, required=true, description="预约ID")
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1625563325",
        "data": {
            "id": 1, //预约ID
            "date": "2021-07-06", //服务时间
            "type": "1", //服务类型:1=文字沟通,1=音频沟通
            "status": "1", //状态:1=未开始,2=诊断中,3=已完成
            "diagnose_time": { //诊断时间
                "hours": 0, //时
                "minutes": 0, //分
                "seconds": 39 //秒
            },
            "doctor": { //医生信息
                "id": 1, //ID
                "nickname": "小何", //姓名
                "avatar": "http://www.consultation.top/assets/img/qrcode.png", //头像
                "level": 2 //等级
            },
            "appraise": {
                "id": 1, //ID
                "star": 3, //评分
                "content": "这就是街舞", //评论内容
                "images": [ //图片
                    "http://www.consultation.top/uploads/20210623/32a69f0cb6c609b1d55f56f17583c473.png"
                ],
                "video": "", //视频地址
                "video_cover": "", //视频封面
                "reply": "", //回复内容
                "createtime": "2021-07/06-17:37", //评论时间
                "star_level_text": "中" //评分文字
            },
            "dept_list": [{ //专科列表
                "id": 1, //ID
                "name": "骨科与神经外科" //名称
            }]
        }
    })
     */
    public function appointmentInfo(){
        $appointment_id = $this->request->post('appointment_id');
        empty($appointment_id) && $this->error('缺少必需参数');
        $appointment = Appointment::with(['doctor','appraise'])->where('id',$appointment_id)->find();
        empty($appointment) && $this->error('预约不存在');
        $appointment->visible(['id','date','type','status','diagnose_time','doctor','appraise'])->append(['dept_list']);
        // 医生信息
        if($appointment->getRelation('doctor')){
            $appointment->getRelation('doctor')->visible(['id','nickname','avatar'])->append(['level']);
        }else{
            $appointment['doctor'] = (Object)[];
        }
        // 评价信息
        if($appointment->getRelation('appraise')){
            $appointment->getRelation('appraise')->visible(['id','star','content','video','video_cover','images','reply','createtime']);
        }else{
            $appointment['appraise'] = (Object)[];
        }
        $this->success('成功',$appointment);
    }

    /**
     * @ApiWeigh    (87)
     * @ApiTitle    (预约-在线咨询)
     * @ApiSummary  (预约-在线咨询)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name=appointment_id, type=integer, required=true, description="预约ID")
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1604282876",
        "data": null
    })
     */
    public function appointmentDiagnose(){
        $appointment_id = $this->request->post('appointment_id');
        empty($appointment_id) && $this->error('缺少必需参数');
        $appointment = Appointment::get(['user_id'=>$this->auth->id,'id'=>$appointment_id]);
        empty($appointment) && $this->error('预约不存在');
        !in_array($appointment['status'],['1,2']) && $this->error('订单不合法');
        if($appointment['status'] == '1'){
            $tim = new Tim();
            // 导入用户
            if(!$res = $tim->importUser($appointment['user'])){
                $this->error($tim->getError());
            }
            // 导入医生
            if(!$res = $tim->importUser($appointment['doctor'])){
                $this->error($tim->getError());
            }
            // 发送消息
            if(!$res = $tim->sendMsg('doctor_'.$appointment['doctor_id'],'user_'.$appointment['user_id'],'服务开始,请问有什么可以帮助您的?')){
                $this->error($tim->getError());
            }
            $appointment->save(['status'=>'2','diagnose_time'=>time()]);
        }
        $this->success('成功');
    }

    /**
     * @ApiWeigh    (85)
     * @ApiTitle    (预约-确认完成)
     * @ApiSummary  (预约-确认完成)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name="token", type="string", required=true, description="token")
     * @ApiParams   (name=appointment_id, type=string, required=true, description="预约ID")
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1622016289",
        "data": null
    })
     */
    public function appointmentConfirm(){
        $appointment_id = $this->request->post('appointment_id');
        empty($appointment_id) && $this->error('缺少必需参数');
        $appointment = Appointment::get(['user_id'=>$this->auth->id,'id'=>$appointment_id]);
        $this->confirm($appointment);
        $this->success('成功');
    }

    /**
     * @ApiInternal
     * 确认完成
     */
    public function confirm(){
        empty($appointment) && $this->error('预约不存在');
        $appointment['status'] == '1' && $this->error('预约未开始');
        $appointment['status'] == '3' && $this->error('已确认完成,请勿重复操作');
        $doctor = Doctor::get($appointment['doctor_id']);
        empty($doctor) && $this->error('医生不存在');
        Db::startTrans();
        try{
            // 统计月接单量
            $receive_num_where = [
                'doctor_id' => $appointment['doctor_id'],
                'month' => date('Y-m'),
            ];
            $receive_num = DoctorReceiveNum::where($receive_num_where)->find();
            if(empty($receive_num)){
                DoctorReceiveNum::create($receive_num_where);
            }else{
                $receive_num->setInc('receive_num');
            }
            $month_receive_num = DoctorReceiveNum::where($receive_num_where)->value('receive_num');
            $doctor->isUpdate(true)->save(['month_receive_num' => $month_receive_num]);
            // 统计总接单量
            $doctor->setInc('total_receive_num');
            // 添加会诊记录
            AppointmentLog::create([
                'appointment_id' => $appointment['id'],
                'user_id' => $appointment['user_id'],
                'avatar' => $appointment['user']['avatar'],
                'nickname' => $appointment['user']['nickname'],
                'doctor_id' => $appointment['doctor_id'],
                'dept_ids' => $appointment['dept_ids'],
                'date' => $appointment['date']
            ]);
            // 计算医生收益
            $level = DoctorLevel::where('id',$doctor['level_id'])->find();
            $doctor_income = $level ? round($appointment['pay_fee'] * ($level['income_ratio'] / 100),2) : 0;
            if($doctor_income > 0){
                Doctor::money($doctor_income,$appointment['doctor_id'],$appointment['user']['nickname'],$appointment['id']);
            }
            // 计算平台收益
            $platform_income = round($appointment['pay_fee'] - $doctor_income,2);
            // 更新预约信息
            $appointment->doctor_income = $doctor_income;
            $appointment->platform_income = $platform_income;
            $appointment->status = '3';
            $appointment->save();
            Db::commit();
        }catch (PDOException $e){
            Db::rollback();
            $this->error($e->getMessage());
        }catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        return true;
    }

    /**
     * @ApiWeigh    (83)
     * @ApiTitle    (预约-评价)
     * @ApiSummary  (预约-评价)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name="token", type="string", required=true, description="token")
     * @ApiParams (name=appointment_id, type=string, required=true, description="预约ID")
     * @ApiParams (name=is_solve, type=string, required=true, description="问题是否解决:0=否,1=是")
     * @ApiParams (name=star, type=string, required=true, description="满意度")
     * @ApiParams (name=content, type=string, required=true, description="服务评价")
     * @ApiParams (name=video, type=string, required=true, description="评价视频")
     * @ApiParams (name=images, type=string, required=true, description="评价图片")
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1622016289",
        "data": null
    })
     */
    public function appointmentAppraise(){
        $post = $this->request->post();
        !isset($post['is_solve']) && $this->error('请确定问题是否解决');
        !in_array($post['is_solve'],['0','1']) && $this->error('问题是否解决参数不合法');
        empty($post['star']) && $this->error('请选择满意度');
        !in_array($post['star'],[1,2,3,4,5]) && $this->error('满意度参数不合法');
        empty($post['content']) && $this->error('请输入服务评价');
        $appointment = Appointment::get($post['appointment_id']);
        empty($appointment) && $this->error('预约不存在');
        $appointment['status'] != '3' && $this->error('预约未完成,无法评价');
        $appointment['is_appraise'] == '1' && $this->error('已评价,请勿重复操作');
        $doctor = Doctor::get($appointment['doctor_id']);
        empty($doctor) && $this->error('医生信息不存在');
        // 视频封面
        if(!empty($post['video'])){
            // 获取七牛云视频信息
            $video = cdnurl($post['video'],true);
            $video_info = json_decode(file_get_contents($video.'?avinfo'),true);
            if(empty($video_info['streams'][0]['width'])) {
                $width = $video_info['streams'][1]['width'];
                $height = $video_info['streams'][1]['height'];
            } else {
                $width = $video_info['streams'][0]['width'];
                $height = $video_info['streams'][0]['height'];
            }
            $post['video_cover'] = $video.'?vframe/jpg/offset/1/w/'.$width.'/h/'.$height;
        }
        Db::startTrans();
        try{
            // 评价
            (new AppointmentAppraise)->allowField(true)->save(array_merge([
                'user_id' => $this->auth->id,
                'doctor_id' => $appointment['doctor_id'],
                'star_level' => $post['star'] > 3 ? 'good' : ($post['star'] == 3 ? 'middle' : 'bad')
            ],$post));
            // 更新订单状态
            $appointment->save(['is_appraise'=>'1']);
            // 统计医生平均星级
            $star = AppointmentAppraise::where('doctor_id',$appointment['doctor_id'])->avg('star');
            $doctor->setInc('star',round($star,2));
            Db::commit();
        }catch (PDOException $e){
            Db::rollback();
            $this->error($e->getMessage());
        }catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('成功');
    }

    /**
     * @ApiWeigh    (81)
     * @ApiTitle    (礼物)
     * @ApiSummary  (礼物)
     * @ApiMethod   (POST)
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1625226644",
        "data": [{ //礼物数据
            "id": 1, //ID
            "name": "12,13", //礼物名称
            "image": "http://www.consultation.top/assets/img/avatar.png", //礼物图片
            "price": 0, //价格
        }]
    })
     */
    public function giftList(){
        $list = Gift::field('id,name,image,price')->select();
        $this->success('成功',$list);
    }

    /**
     * @ApiWeigh    (79)
     * @ApiTitle    (礼物-购买)
     * @ApiSummary  (礼物-购买)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="is_custom", type="string", required=true, description="是否自定义:0=否,1=是")
     * @ApiParams   (name="gift_id", type="inter", required=false, description="礼物ID")
     * @ApiParams   (name="money", type="float", required=false, description="自定义金额")
     * @ApiReturn({
        "code": 1, //返回码:0=错误普通提示,1=成功,2=普通弹窗提示,3=跳转弹窗提示
        "msg": "成功",
        "time": "1604282876",
        "data": {
            "payment": [], //支付数据
            "order_id": 15, //订单ID
        }
    })
     */
    public function payGift(){
        $is_custom = $this->request->post('is_custom');
        $gift_id = $this->request->post('gift_id');
        $money = $this->request->post('money');
        !isset($is_custom) && $this->error('缺少必需参数');
        switch ($is_custom){
            case '0':
                empty($gift_id) && $this->error('请选择礼物');
                $gift = Gift::get($gift_id);
                empty($gift) && $this->error('礼物不存在');
                $pay_fee = $gift['price'];
                break;
            case '1':
                empty($money) && $this->error('请填写自定义金额');
                $pay_fee = $money;
                break;
            default:
                $this->error('参数不合法');
        }
        $order = GiftOrder::create([
            'user_id' => $this->auth->id,
            'order_sn' => get_order_sn(),
            'gift_id' => $is_custom == '0' ? $gift_id : 0,
            'pay_fee' => $pay_fee,
        ]);
        $payment = [];
        if($pay_fee <= 0){
            (new Notify())->notifyGiftZero([
                'out_trade_no' => $order['order_sn'],
                'transaction_id' => ''
            ]);
        }else{
             // 发起微信支付
             $Wechat = new Wechat;
             $openid = Db::name('third')->where('user_id',$this->auth->id)->value('openid');
             $notify_url = $this->request->root(true) . '/api/notify/notifyGift';
             if(!$payment = $Wechat->wxPay($this->model['order_sn'], $openid, $pay_fee, $notify_url)){
                 $this->error($Wechat->getError());
             }
//            (new Notify())->notifyGiftZero([
//                'out_trade_no' => $order['order_sn'],
//                'transaction_id' => ''
//            ]);
        }
        $this->success('成功',[
            'payment' => $payment,
            'order_id' => $order['id']
        ]);
    }

    /**
     * @ApiWeigh    (77)
     * @ApiTitle    (医生入驻)
     * @ApiSummary  (医生入驻)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name="token", type="string", required=true, description="token")
     * @ApiParams (name=nickname, type=string, required=true, description="姓名")
     * @ApiParams (name=mobile, type=string, required=true, description="联系电话")
     * @ApiParams (name=city, type=string, required=true, description="所在城市")
     * @ApiParams (name=idcard_front, type=string, required=true, description="身份证正面")
     * @ApiParams (name=idcard_back, type=string, required=true, description="身份证反面")
     * @ApiParams (name=certificates, type=string, required=true, description="从医资格证")
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1622016289",
        "data": null
    })
     */
    public function applyDoctor(){
        $post = $this->request->post();
        empty($post['nickname']) && $this->error('请填写姓名');
        empty($post['mobile']) && $this->error('请填写联系电话');
        empty($post['city']) && $this->error('请选择所在城市');
        empty($post['idcard_front']) && $this->error('请上传身份证正面');
        empty($post['idcard_back']) && $this->error('请上传身份证反面');
        empty($post['certificates']) && $this->error('请上传从医资格证');
        $doctor = Doctor::where('user_id',$this->auth->id)->find();
        $doctor['status'] == '1' && $this->error('已通过审核');
        if(!$doctor){
            $doctor = new Doctor();
        }
        $doctor->allowField(true)->save(array_merge([
            'user_id' => $this->auth->id
        ],$post));
        $this->success('成功');
    }

    /**
     * @ApiWeigh    (75)
     * @ApiTitle    (医生入驻-详情)
     * @ApiSummary  (医生入驻-详情)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name="token", type="string", required=true, description="token")
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1625797950",
        "data": {
            "nickname": "张清北", //姓名
            "mobile": "15133120361", //联系电话
            "city": "江苏省,无锡市", //所在城市
            "idcard_front": "http://www.consultation.top/assets/img/qrcode.png", //身份证正面
            "idcard_back": "http://www.consultation.top/assets/img/qrcode.png", //身份证反面
            "certificates": [ //从医资格证
                "http://www.consultation.top/assets/img/avatar.png",
                "http://www.consultation.top/assets/img/qrcode.png"
            ],
            "status": "0", //审核状态:0=待审核,1=已通过,2=已拒绝
            "reject_reason": "驳回吧" //拒绝原因
        }
    })
     */
    public function applyDoctorInfo(){
        $doctor = Doctor::where('user_id',$this->auth->id)->find();
        $doctor['status'] == '1' && $this->error('已通过审核');
        $doctor->visible(['nickname','mobile','city','idcard_front','idcard_back','certificates','status','reject_reason']);
        $this->success('成功',$doctor);
    }

    /**
     * @ApiWeigh    (73)
     * @ApiTitle    (我的收藏)
     * @ApiSummary  (我的收藏)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name="token", type="string", required=true, description="token")
     * @ApiParams (name=page, type=integer, required=false, description="分页")
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1625560239",
        "data": {
            "total": 1, //数据总数
            "per_page": 10,
            "current_page": 1,
            "last_page": 1,
            "data": [{ //医生列表
                "id": 1, //ID
                "avatar": "http://www.consultation.top/assets/img/qrcode.png", //头像
                "nickname": "小何", //姓名
                "star": "0.00", //评分
                "good_field": "爬树", //擅长
                "level": 2, //等级
                "dept_list": [{ //专科
                    "id": 1, //ID
                    "name": "骨科与神经外科" //名称
                }]
            }]
        }
    })
     */
    public function collectList(){
        $where = [
            'a.status' => '1',
            'c.user_id' => $this->auth->id
        ];
        $data = Doctor::alias('a')
            ->join('user b','b.id = a.user_id')
            ->join('user_collect_doctor c','c.doctor_id = a.id')
            ->where($where)
            ->field('a.*')
            ->order('c.createtime')
            ->paginate(10)
            ->each(function ($v){
                $v->visible(['id','avatar','nickname','star','good_field','level'])->append(['level','dept_list']);
            });
        $this->success('成功',$data);
    }

    /**
     * @ApiWeigh    (71)
     * @ApiTitle    (医生入驻说明)
     * @ApiSummary  (医生入驻说明)
     * @ApiMethod   (POST)
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1622016289",
        "data": {
            "content": "医生入驻说明"
        }
    })
     */
    public function applyDoctorDescription(){
        $content = config('site.apply_doctor_description');
        $this->success('成功',compact('content'));
    }

    /**
     * @ApiWeigh    (69)
     * @ApiTitle    (关于我们)
     * @ApiSummary  (关于我们)
     * @ApiMethod   (POST)
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1622016289",
        "data": {
            "content": "关于我们"
        }
    })
     */
    public function aboutUs(){
        $content = config('site.about_us');
        $this->success('成功',compact('content'));
    }

    /**
     * @ApiWeigh    (67)
     * @ApiTitle    (获取腾讯即时通讯签名)
     * @ApiSummary  (获取腾讯即时通讯签名)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1604282876",
        "data": {
            "usersig": 123, //即时通讯签名
        }
    })
     */
    public function getTimSig(){
        $usersig = (new Tim)->getSig('user_'.$this->auth->id);
        $this->success('成功',compact('usersig'));
    }

    /**
     * @ApiWeigh    (1)
     * @ApiTitle    (测试登录)
     * @ApiSummary  (测试登录)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->request('account');
        $password = $this->request->request('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $this->auth->setAllowFields(['id', 'nickname', 'avatar', 'identity']);
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }
}