Course.php 26.9 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
<?php
namespace app\mobile\controller;

use Exception;
use think\exception\PDOException;
use think\Db;
use app\common\controller\Api;
use app\mobile\model\CourseBanner;
use app\mobile\model\CourseCatalog;
use app\mobile\model\CourseCategory;
use app\mobile\model\CourseAppraise;
use app\mobile\model\CourseSpec;
use app\mobile\model\CourseOrder;
use app\mobile\model\CourseCollect;
use app\mobile\model\Company;
use app\mobile\model\CompanyUser;
use addons\epay\library\Service;

/**
 * 课程接口
 * @ApiWeigh (93)
 */
class Course extends Api
{
	protected $noNeedLogin = ['banner','category','index','info','catalog','appraiseList','spec_intro','scorePrice','service'];
    protected $noNeedRight = ['*'];
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('app\mobile\model\Course');
    }

    /**
     * @ApiTitle    (课程-轮播图)
     * @ApiSummary  (课程-轮播图)
     * @ApiMethod   (POST)
     *
     * @ApiReturn({
		"code": 1,
		"msg": "成功",
		"time": "1599907184",
		"data": [{
			"id": 1, // 轮播图ID
			"image": "https://img02.mockplus.cn/idoc/sketch/2020-08-06/006324c3-e5d3-4206-be48-52a7c7468e74.7C1FC40C-CED5-4B08-9506-3E48A2732B2C.png" // 图片地址
		}]
	})
     */
    public function banner()
    {
        $list = CourseBanner::order('createtime desc')->field('id,image')->select();
        $this->success('成功',$list);
    }

    /**
     * @ApiTitle    (课程-分类)
     * @ApiSummary  (课程-分类)
     * @ApiMethod   (POST)
     * @ApiParams   (name="page", type="inter", required=false, description="当前页(默认1)")
     * @ApiParams   (name="page_num", type="inter", required=false, description="每页显示数据个数(默认10)")
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1599907522",
        "data": {
        "total": 1, //数据总条数
        "list": [{
            "id": 1, //分类ID
            "title": "测试课程", //分类标题
            "cover": "", //分类图片
            "study_num_rate": 3, //多少人选择(%)
            "description": "" //描述
        }]
    }
    })
     */
    public function category()
    {
        $page = $this->request->param('page', 1, 'intval');
        $page_num = $this->request->param('page_num', 10, 'intval');
        $data = CourseCategory::field("id,title,cover,study_num_rate,description")
            ->paginate($page_num,false,['page'=>$page])
            ->toArray();
        $this->success('成功',['total'=>$data['total'],'list'=>$data['data']]);
    }

    /**
     * @ApiTitle    (课程-首页)
     * @ApiSummary  (课程-首页)
     * @ApiMethod   (POST)
     * @ApiParams   (name="course_category_id", type="inter", required=true, description="课程分类ID")
     * @ApiParams   (name="order", type="inter", required=false, description="排序方式:0=综合排序,1=按学习人数,2=价格从低到高,3=价格从高到低")
     * @ApiParams   (name="page", type="inter", required=false, description="当前页(默认1)")
     * @ApiParams   (name="page_num", type="inter", required=false, description="每页显示数据个数(默认10)")
     * @ApiReturn({
		"code": 1,
		"msg": "成功",
		"time": "1599907522",
		"data": {
			"total": 1, //数据总条数
			"list": [{
				"id": 1, //课程ID
				"title": "测试课程", //课程标题
				"cover": "", //课程封面图
				"current_price": "50.00", //课程现价
				"original_price": "100.00", //课程原价
				"study_num_rate": 3 //多少人选择(%)
			}]
		}
	})
     */
    public function index()
    {
        $course_category_id = $this->request->param('course_category_id',0);
        $order = $this->request->param('order',0);
        $page = $this->request->param('page', 1, 'intval');
        $page_num = $this->request->param('page_num', 10, 'intval');
        $where = [];
        if($course_category_id){
            $where['course_category_id'] = $course_category_id;
        }
        switch ($order) {
            case 0:
                $order = ['is_top' => 'desc','top_time' => 'desc', 'createtime' => 'desc'];
                break;
            case 1:
                $order = ['study_num_rate' => 'desc'];
                break;
            case 2:
                $order = ['current_price' => 'asc'];
                break;
            case 3:
                $order = ['current_price' => 'desc'];
                break;
            default:
                $order = ['createtime' => 'desc'];
                break;
        }
        $data = $this->model
            ->field("
            	id,
            	title,
            	cover,
            	current_price,
            	original_price,
            	study_num_rate
            ")
            ->where($where)
            ->order($order)
            ->paginate($page_num,false,['page'=>$page])
            ->toArray();
        $this->success('成功',['total'=>$data['total'],'list'=>$data['data']]);
    }

    /**
     * @ApiTitle    (课程详情)
     * @ApiSummary  (课程详情)
     * @ApiMethod   (POST)
     * 
     * @ApiParams (name="course_id", type="int", required=true, description="课程ID")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1600919979",
        "data": {
            "id": 1, //课程ID
            "title": "测试课程", //课程标题
            "cover": "", //封面图
            "current_price": "50.00", //现价
            "original_price": "100.00", //原价
            "content": "123", //详情介绍
            "video": { //一节课视频地址
                "cover": "http://www.enterprise.top/assets/img/bg-middle.jpg", //视频封面
                "video": "https://vd2.bdstatic.com/mda-jkptk0q9euab5v41/sc/mda-jkptk0q9euab5v41.mp4?auth_key=1599909914-0-0-1b5b778ac7883d30cf78883ff8884b7e&bcevod_channel=searchbox_feed&pd=1&pt=3" //视频
            },
            "is_buy": 0, //是否已购买:0=否,1=是
            "is_collect": 0, //是否已收藏:0=否,1=是
        }
    })
     */
    public function info()
    {
    	$course_id = $this->request->param('course_id');
    	empty($course_id) && $this->error('缺少必要参数');
    	$info = $this->model->get($course_id);
        empty($info) && $this->error('课程信息不存在');
    	// 课程视频
    		// 第一节目录
	    	$catalog_parent = CourseCatalog::where('course_id',$course_id)
	    		->where('pid',0)
	    		->order('weigh asc')
	    		->find();
	    	// 第一节目录下的第一课程
	    	$catalog_child = CourseCatalog::where('course_id',$course_id)
	    		->where('pid',$catalog_parent['id'])
	    		->order('weigh asc')
	    		->find();
	    	$video = [];
	    	if(!empty($catalog_parent) && !empty($catalog_child)){
	    		$video = $catalog_child['video'];
	    	}
    	$info['video'] = $video;
        // 是否已购买
            // 我加入的企业购买是否购买了此课程
            $company_course_list = CourseOrder::alias('a')
                ->join('mobile_company_user b','b.company_id = a.company_id')
                ->join('user c','c.id = b.user_id')
                ->where('a.course_id',$course_id)
                ->where('b.user_id',$this->auth->id)
                ->where('b.status','1')
                ->where('c.group_id',1)
                ->field('a.id,a.company_id,a.people_num,a.is_top')
                ->select();
            // 查询我是否可以享受企业课程(按企业审核时间排队,没在队伍里就无法享受企业课程)
            $order_id_arr = [];
            foreach ($company_course_list as $v) {
                if($v['is_top'] == '1'){
                    $order_id_arr[] = $v['id'];
                    continue;
                }
                $user_id_arr = CompanyUser::where('company_id',$v['company_id'])
                    ->where('status','1')
                    ->order('updatetime asc')
                    ->limit($v['people_num'])
                    ->column('user_id');
                if(in_array($this->auth->id,$user_id_arr)){
                    $order_id_arr[] = $v['id'];
                }
            }
            $order = CourseOrder::where(function($query)use($order_id_arr){
                    $query->where('user_id', $this->auth->id)->whereor('id', 'in', $order_id_arr);
                })
                ->where('course_id',$course_id)
                ->where('pay_status','1')
                ->field('id')
                ->find();
        $info['is_buy'] = !empty($order) ? 1 : 0;
        // 是否已收藏
        $collect = CourseCollect::where('user_id',$this->auth->id)->where('course_id',$course_id)->field('id')->find();
        $info['is_collect'] = !empty($collect) ? 1 : 0;
        $this->success('成功',$info->visible([
            'id',
            'title',
            'cover',
            'current_price',
            'original_price',
            'content'
        ])->append([
            'video',
            'is_buy',
            'is_collect'
        ]));
    }

    /**
     * @ApiTitle    (课程详情-收藏)
     * @ApiSummary  (课程详情-收藏)
     * @ApiMethod   (POST)
     *
     * @ApiHeaders (name=token, type=string, required=true, description="请求的Token")
     *
     * @ApiParams (name="course_id", type="int", required=true, description="课程ID")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1599032660",
        "data": null
    })
     */
    public function collect()
    {
        $course_id = $this->request->param('course_id');
        empty($course_id) && $this->error('缺少必要参数');
        $info = CourseCollect::get(['course_id'=>$course_id,'user_id'=>$this->auth->id]);
        if(!empty($info)){
            $info->delete();
            $this->success('取消收藏成功');
        }
        CourseCollect::create([
            'course_id' => $course_id,
            'user_id' => $this->auth->id,
        ]);
        $this->success('收藏成功');
    }

    /**
     * @ApiTitle    (课程详情-目录)
     * @ApiSummary  (课程详情-目录)
     * @ApiMethod   (POST)
     *
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams (name="course_id", type="int", required=true, description="课程ID")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1600927297",
        "data": {
            "list": [{
                "id": 1, //一级目录ID
                "name": "第一章", //一级目录名称
                "childlist": [{ //二级目录列表
                    "id": 2, //二级目录ID
                    "name": "第一章-第一节", //二级目录名称
                    "video": { //视频信息
                        "cover": "http://www.enterprise.top/assets/img/bg-middle.jpg", //封面
                        "video": "https://vd2.bdstatic.com/mda-jkptk0q9euab5v41/sc/mda-jkptk0q9euab5v41.mp4?auth_key=1599909914-0-0-1b5b778ac7883d30cf78883ff8884b7e&bcevod_channel=searchbox_feed&pd=1&pt=3" //视频
                    }
                }]
            }]
        }
    })
     */
    public function catalog()
    {
        $course_id = $this->request->param('course_id');
    	empty($course_id) && $this->error('缺少必要参数');
        $info = $this->model->get($course_id);
        empty($info) && $this->error('课程信息不存在');
    	$list = CourseCatalog::where('course_id',$course_id)
    		->where('pid',0)
    		->field('id,name')
    		->order('weigh asc')
    		->select();
    	foreach ($list as &$v) {
    		$childlist = CourseCatalog::where('pid',$v['id'])
    			->where('course_id',$course_id)
    			->order('weigh asc')
    			->select();
    		foreach ($childlist as $val) {
    			$val->visible(['id','name','video']);
    		}
    		$v['childlist'] = $childlist;
    	}
        $this->success('成功',compact('list'));
    }

    /**
     * @ApiTitle    (课程详情-目录-播放)
     * @ApiSummary  (课程详情-目录-播放)
     * @ApiMethod   (POST)
     *
     * @ApiParams (name="course_catalog_id", type="int", required=true, description="目录ID")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1600927297",
        "data": null
    })
     */
    public function play()
    {
        $course_catalog_id = $this->request->param('course_catalog_id');
        empty($course_catalog_id) && $this->error('缺少必要参数');
        $info = CourseCatalog::get($course_catalog_id);
        empty($info) && $this->error('目录信息不存在');
        // 播放次数加1
        $info->play_num_real = $info->play_num_real + 1;
        $info->save();
        $this->success('成功');
    }

    /**
     * @ApiTitle    (课程详情-老师)
     * @ApiSummary  (课程详情-老师)
     * @ApiMethod   (POST)
     *
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams (name="course_id", type="int", required=true, description="课程ID")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1600927509",
        "data": {
            "teacher_avatar": "/uploads/20200814/a8df375d64ec5f828a38ded72f42333e.jpg", //老师头像
            "teacher_name": "杰克", //老师名称
            "teacher_desc": "汤姆包与杰克鼠" //老师介绍
        }
    })
     */
    public function teacher()
    {
        $course_id = $this->request->param('course_id');
        empty($course_id) && $this->error('缺少必要参数');
        $info = $this->model->get($course_id);
        empty($info) && $this->error('课程信息不存在');
        $this->success('成功',$info->visible([
            'teacher_avatar',
            'teacher_name',
            'teacher_desc'
        ]));
    }

    /**
     * @ApiTitle    (课程详情-评价)
     * @ApiSummary  (课程详情-评价)
     * @ApiMethod   (POST)
     *
     * @ApiParams (name="course_id", type="int", required=true, description="课程ID")
     * @ApiParams   (name="page", type="inter", required=false, description="当前页(默认1)")
     * @ApiParams   (name="page_num", type="inter", required=false, description="每页显示数据个数(默认10)")
     *
     * @ApiReturn({
		"code": 1,
		"msg": "成功",
		"time": "1599908791",
		"data": {
			"total": 1, //数据总条数
			"list": [{
				"id": 1, //评价ID
				"star": 5, //评价星数
				"content": "keyi ", //评价内容
				"createtime": "1970.01.01 08:00", //评价时间
				"user": { //用户信息
					"nickname": "", //真实姓名
					"image": "http://qizhibang.brotop.cn/uploads/20200814/FkGifOc2vGqdgoZ68cDFAv5HWKqh.jpg" //头像
				}
			}]
		}
	})
     */
    public function appraiseList()
    {
        $course_id = $this->request->param('course_id');
        $page = $this->request->param('page', 1, 'intval');
        $page_num = $this->request->param('page_num', 10, 'intval');
    	empty($course_id) && $this->error('缺少必要参数');
    	$data = CourseAppraise::with(['user'])
            ->where('course_id',$course_id)
            ->order('createtime desc')
            ->paginate($page_num,false,['page'=>$page])
            ->each(function($v){
                $v->visible(['id','star','content','createtime','user']);
                $v->createtime = date('Y.m.d H:i',$v['createtime']);
                if($v->getRelation('user')){
                    $v->getRelation('user')->visible(['user_id','image','nickname']);
                }
            })->toArray();
        $this->success('成功',['total'=>$data['total'],'list'=>$data['data']]);
    }

    /**
     * @ApiTitle    (选择规格)
     * @ApiSummary  (选择规格)
     * @ApiMethod   (POST)
     *
     * @ApiParams (name="course_id", type="int", required=true, description="课程ID")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1599739316",
        "data": [{
            "id": 1, //规格ID
            "course_id": 1, //课程ID
            "name": "基础版", //套餐名称
            "current_price": "500.00", //当前价格
            "original_price": "1000.00", //原价
            "people_num": 20, //限制人数
            "is_top": "0", //是否顶配:0=否,1=是
            "createtime": null,
            "updatetime": null,
            "is_pay": 1 //是否可以购买:0=否,1=是
        }]
    })
     */
    public function spec()
    {
        $company = Company::get(['user_id'=>$this->auth->id]);
        $course_id = $this->request->param('course_id');
        empty($course_id) && $this->error('缺少必要参数');
        $info = $this->model->get($course_id);
        empty($info) && $this->error('课程信息不存在');
        $list = CourseSpec::where('course_id',$course_id)->select();
        foreach ($list as &$v) {
            // 是否可购买
            $order = CourseOrder::where('company_id',$company['id'])
                ->where('course_id',$course_id)
                ->where('pay_status','1')
                ->order(['is_top'=>'desc','people_num'=>'desc'])
                ->find();
            $people_num = CompanyUser::where('company_id',$company['id'])
                ->where('status','1')
                ->count();
            if(!empty($order)){
                // 已购买顶配套餐,直接跳出本次循环
                if($order['is_top'] == '1'){
                    $v['is_pay'] = 0;
                    continue;
                }
                if($order['people_num'] > $people_num){
                    $people_num = $order['people_num'];
                }
                $v['current_price'] = $v['current_price']-$order['course_price'];
            }
            if($v['is_top'] == '1'){
                $v['is_pay'] = 1;
            }else{
                $v['is_pay'] = $v['people_num'] <= $people_num ? 0 : 1;
            }
        }
        $this->success('成功',$list);
    }

    /**
     * @ApiTitle    (套餐说明)
     * @ApiSummary  (套餐说明)
     * @ApiMethod   (POST)
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1599017563",
        "data": "套餐说明" //套餐说明内容
    })
     */
    public function spec_intro()
    {
        $content = Db::name('mobile_config')->where('id',1)->value('course_spec_intro');
        $this->success('成功', $content);
    }

    /**
     * @ApiTitle    (每积分可抵扣多少元)
     * @ApiSummary  (每积分可抵扣多少元)
     * @ApiMethod   (POST)
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1599046220",
        "data": 0.01 //每积分可抵扣多少元
    })
     */
    public function scorePrice()
    {
        $content = Db::name('mobile_config')->where('id',1)->value('score_price');
        $this->success('成功', $content);
    }

    /**
     * @ApiTitle    (联系客服)
     * @ApiSummary  (联系客服)
     * @ApiMethod   (POST)
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1606961557",
        "data": {
            "service_qrcode": "http://qizhibang.brotop.cn/uploads/20200811/b9bbd60dcacbcb649579155f63b62558.png", //客服二维码
            "service_phone": "0311-28907" //客服电话
        }
    })
     */
    public function service()
    {
        $config = Db::name('mobile_config')->where('id',1)->field('service_qrcode,service_phone')->find();
        $config['service_qrcode'] = !empty($config['service_qrcode']) ? cdnurl($config['service_qrcode'],true) : '';
        $this->success('成功', $config);
    }

    /**
     * @ApiTitle    (购买预览)
     * @ApiSummary  (购买预览)
     * @ApiMethod   (POST)
     *
     * @ApiHeaders (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams (name="course_id", type="int", required=true, description="课程ID")
     * @ApiParams (name="spec_id", type="int", required=true, description="课程规格ID")
     * @ApiParams (name="score_switch", type="int", description="积分开关:0=关,1=开")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1599046220",
        "data": {
            "id": 1, //试卷ID
            "title": "测试试卷", //试卷标题
            "year": 2015, //年费(单位:年)
            "time": 100, //答题时间(单位:分)
            "pass_score": 80, //合格分数
            "description": "这个还行", //试卷描述
            "do_num": 10, //回答人数
            "full_score": 100 //试卷分数(单位:分)
        }
    })
     */
    public function payView()
    {
        $param = $this->request->param();
        if(!$order = $this->model->payView($this->auth->getUser(),$param)){
            $this->error($this->model->getError(),null,$this->model->getCode());
        }
        $this->success(__('成功'),$order);
    }

    /**
     * @ApiTitle    (购买)
     * @ApiSummary  (购买)
     * @ApiMethod   (POST)
     *
     * @ApiHeaders (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams (name="course_id", type="int", required=true, description="课程ID")
     * @ApiParams (name="spec_id", type="int", required=true, description="课程规格ID")
     * @ApiParams (name="score_switch", type="int", description="积分开关:0=关,1=开")
     * @ApiParams (name="pay_type", type="string", required=true, description="支付方式:wechat=微信,alipay=支付宝,money=余额")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1599046220",
        "data": {
            "id": 1, //试卷ID
            "title": "测试试卷", //试卷标题
            "year": 2015, //年费(单位:年)
            "time": 100, //答题时间(单位:分)
            "pass_score": 80, //合格分数
            "description": "这个还行", //试卷描述
            "do_num": 10, //回答人数
            "full_score": 100 //试卷分数(单位:分)
        }
    })
     */
    public function pay()
    {
        $param = $this->request->param();
        if(!$order = $this->model->payView($this->auth->getUser(),$param)){
            $this->error($this->model->getError(),null,$this->model->getCode());
        }
        if (!$param['pay_type'] || !in_array($param['pay_type'], ['alipay', 'wechat', 'money'])) {
            $this->error("请选择支付方式");
        }
        $user = $this->auth->getUser();
        if($param['pay_type'] == 'money' && $user['money'] < $order['pay_price']){
            $this->error('余额不足');
        }
        // 创建订单
        $model = new CourseOrder;
        $model->add($user, $order, $param['pay_type']);
        // 零元直接支付成功
        if($model['pay_price'] <= 0 || $param['pay_type'] == 'money'){
            (new Notify)->notifyCourseZero($model['order_sn'],$model['pay_price'],$param['pay_type']);
            $this->success('成功',[]);
        }
        //回调链接
        $notifyurl = $this->request->root(true) . '/mobile/notify/notifyCourse/paytype/' . $param['pay_type'];
        // $model['pay_price'] = 0.01; //测试金额
        $payment = Service::submitOrder($model['pay_price'], $model['order_sn'], $param['pay_type'], '课程', $notifyurl, null, 'app');
        $this->success('成功',$payment);
    }

    /**
     * @ApiTitle    (兑换)
     * @ApiSummary  (兑换)
     * @ApiMethod   (POST)
     *
     * @ApiHeaders (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams (name="course_id", type="int", required=true, description="课程ID")
     * @ApiParams (name="code", type="string", description="兑换码")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1599046220",
        "data": null
    })
     */
    public function exchange()
    {
        $param = $this->request->param();
        empty($param['course_id']) && $this->error('缺少必要参数');
        empty($param['code']) && $this->error('请输入兑换码');
        $course = $this->model->get($param['course_id']);
        empty($course) && $this->error('课程信息不存在');
        $course_code = Db::name('mobile_course_code')
            ->where('code',$param['code'])
            ->where('course_id',$param['course_id'])
            ->find();
        empty($course_code) && $this->error('您输入的兑换码不存在');
        if($course_code['expire_time'] < time() || $course_code['status'] != '0'){
            $this->error('您输入的兑换码已失效');
        }
        // 是否已购买
            // 我加入的企业购买是否购买了此课程
            $company_course_list = CourseOrder::alias('a')
                ->join('mobile_company_user b','b.company_id = a.company_id')
                ->join('user c','c.id = b.user_id')
                ->where('a.course_id',$param['course_id'])
                ->where('b.user_id',$this->auth->id)
                ->where('b.status','1')
                ->where('c.group_id',1)
                ->field('a.id,a.company_id,a.people_num,a.is_top')
                ->select();
            // 查询我是否可以享受企业课程(按企业审核时间排队,没在队伍里就无法享受企业课程)
            $order_id_arr = [];
            foreach ($company_course_list as $v) {
                if($v['is_top'] == '1'){
                    $order_id_arr[] = $v['id'];
                    continue;
                }
                $user_id_arr = CompanyUser::where('company_id',$v['company_id'])
                    ->where('status','1')
                    ->order('updatetime asc')
                    ->limit($v['people_num'])
                    ->column('user_id');
                if(in_array($this->auth->id,$user_id_arr)){
                    $order_id_arr[] = $v['id'];
                }
            }
            $order = CourseOrder::where(function($query)use($order_id_arr){
                $query->where('user_id', $this->auth->id)->whereor('id', 'in', $order_id_arr);
            })
                ->where('course_id',$param['course_id'])
                ->where('pay_status','1')
                ->field('id')
                ->find();
        !empty($order) && $this->error('已购买该课程,无需兑换');
        Db::startTrans();
        try {
            // 创建订单
            $model = new CourseOrder;
            $model->save([
                'user_id' => $this->auth->id,
                'course_id' => $param['course_id'],
                'course_code_id' => $course_code['id'],
                'order_sn' => get_order_sn(),
                'pay_price' => 0,
                'pay_type' => 'code',
                'course_price' => $course['current_price'],
            ]);
            (new Notify)->notifyCourseZero($model['order_sn'],$model['pay_price'],$model['pay_type']);
            Db::name('mobile_course_code')->where('id',$course_code['id'])->update(['status'=>'1']); //兑换码状态变为:已兑换
            Db::commit();
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('成功');
    }
}