<?php
namespace app\mobile\controller;

use think\Validate;
use think\Db;
use app\common\controller\Api;
use app\mobile\model\CourseBanner;
use app\mobile\model\CourseCatalog;
use app\mobile\model\CourseAppraise;
use app\mobile\model\CourseSpec;
use app\mobile\model\CourseOrder;
use app\mobile\model\Company;
use app\mobile\model\CompanyUser;
use addons\epay\library\Service;

/**
 * 课程接口
 * @ApiWeigh (93)
 */
class Course extends Api
{
	protected $noNeedLogin = ['banner','index','info','catalog','appraiseList'];
    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="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()
    { 
        $order = $this->request->param('order',0);
        $page = $this->request->param('page', 1, 'intval');
        $page_num = $this->request->param('page_num', 10, 'intval');
        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
            ")
            ->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" //视频
            }
        }
    })
     */
    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;
        $this->success('成功',$info->visible([
            'id',
            'title',
            'cover',
            'current_price',
            'original_price',
            'content'
        ])->append([
            'video'
        ]));
    }

    /**
     * @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": {
            "is_buy": 0, //是否已购买:0=否,1=是
            "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;
    	}
        // 是否已购买
        $order = CourseOrder::where('user_id',$this->auth->id)
            ->where('course_id',$course_id)
            ->where('pay_status','1')
            ->field('id')
            ->find();
        $is_buy = !empty($order) ? 1 : 0;
        $this->success('成功',compact('is_buy','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']);
                $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=支付宝")
     *
     * @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'])) {
            $this->error("请选择支付方式");
        }
        // 创建订单
        $model = new CourseOrder;
        $model->add($this->auth->getUser(), $order, $param['pay_type']);
        // 零元直接支付成功
        if($model['pay_price'] <= 0){
            (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);
    }
}