<?php

namespace app\api\controller;

use app\common\controller\Api;
use function fast\e;
use think\Cache;
use think\Db;
use think\Session;
use think\Config;

use app\api\controller\Common;
use app\common\controller\Backend;
use EasyWeChat\Message\Image;
use Exception;
use fast\Auth;
use fast\Random;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use Endroid\QrCode\QrCode;
use think\exception\PDOException;

/**
 * 我的资料
 */
class User extends Api
{
    protected $noNeedLogin = ['video_list'];
    protected $noNeedRight = ['*'];

    /**
     * @ApiTitle    (我的资料)
     * @ApiSummary  (我的资料)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/index)
     *
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     *
     * @ApiReturn({
    "code": 1,
    "msg": "成功",
    "time": "1571492001",
    "data": {
    "id"://ID
    "username"://用户名
    "nickname"://姓名
    "sex"://性别1男0女
    "card"://身份证号
    "work_address"://工作地点
    "phone"://手机号
    "image"://头像
    }
    })
     */
    public function index()
    {
        $qiniu = get_addon_config('qiniu')['cdnurl'];
        $user_id = $this->auth->id;
        $data = Db::name('user')->where('id',$user_id)->find();
        if(empty($data['nickname'])){
            $data['nickname'] = '';
        }
        if(empty($data['image'])){
            $data['image'] = '';
            $data['yuan_image'] = '';
        }else{
            $data['yuan_image'] = $data['image'];
            $data['image'] = $qiniu.$data['image'];
        }
        if(empty($data['card'])){
            $data['card'] = '';
        }
        if(empty($data['phone'])){
            $data['phone'] = '';
        }
        if(empty($data['work_address'])){
            $data['work_address'] = '';
        }
        $this->success('success',$data);
    }

    /**
     * @ApiTitle    (修改我的资料)
     * @ApiSummary  (修改我的资料)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/edit_info)
     *
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="nickname", type="string", required=true, description="姓名")
     * @ApiParams   (name="sex", type="int", required=true, description="性别1男0女")
     * @ApiParams   (name="card", type="string", required=true, description="身份证号")
     * @ApiParams   (name="work_address", type="string", required=true, description="工作单位")
     * @ApiParams   (name="phone", type="string", required=true, description="手机号")
     * @ApiParams   (name="code", type="string", required=true, description="验证码")
     * @ApiParams   (name="image", type="string", required=true, description="照片")
     *
     * @ApiReturn({
    "code": 1,
    "msg": "成功",
    "time": "1571492001",
    "data": {
    }
    })
     */
    public function edit_info()
    {
        $user_id = $this->auth->id;
        $nickname = $this->request->param('nickname');
        $sex = $this->request->param('sex');
        $card = $this->request->param('card');
        $work_address = $this->request->param('work_address');
        $phone = $this->request->param('phone');
        $code = $this->request->param('code');
        $image = $this->request->param('image');
        if(!empty($phone)){
            if(empty($code)){
                $this->error('验证码不能为空');
            }
            $yuan_code = Cache::get($phone);
            if($code != $yuan_code){
                $this->error('验证码错误');
            }
        }
        $data = Db::name('user')->where('id',$user_id)->find();
        $params = [];
        if($sex){
            $params['sex'] = $sex;
        }
        if($phone){
            $params['phone'] = $phone;
        }
        if(empty($data['image']) && $image){
            $params['image'] = $image;
        }
        if($params){
            Db::name('user')
                ->where('id',$user_id)
                ->update($params);
        }
        $this->success('success');
    }

    /**
     * @ApiTitle    (培训课程列表)
     * @ApiSummary  (培训课程列表)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/video_list)
     *
     * @ApiParams   (name="id", type="int", required=true, description="学习系统id")
     * @ApiParams   (name="type", type="int", required=true, description="类型1或者空是全部2必修3选修")
     * @ApiParams   (name="page", type="inter", required=false, description="当前页(默认1)")
     * @ApiParams   (name="pageNum", type="inter", required=false, description="每页显示数据个数(默认10)")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1571492001",
        "data": {
        "total_num"://总时长
         "info":[
            "id"://ID
            "study_id"://学习系统id
            "is_major"://1主修2选修
            "tag"://标签
            "name"://课程名称
            "video_file"://视频地址
            "video_image"://视频首帧图
            "duration"://总时长/秒
            "class_hour"://学时
            "content"://内容详情
            "teacher"://讲师
              ]

    }
    })
     */
    public function video_list()
    {
        $page = $this->request->param('page', 1, 'intval');
        $pageNum = $this->request->param('pageNum', 10, 'intval');
        $id = $this->request->param('id');
        if(empty($id)){
            $this->error('缺少必要参数');
        }

        $type = $this->request->param('type');
        if($type == 1 || empty($type)){
            true;
        }elseif ($type == 2){
            $where['is_major'] = 1;
        }elseif ($type == 3){
            $where['is_major'] = 2;
        }
        $where['study_id'] = $id;
        $qiniu = get_addon_config('qiniu')['cdnurl'];
        $data['total_num'] = Db::name('classes')
            ->where($where)
            ->count();
        $data['info'] = Db::name('classes')
            ->field('createtime,updatetime',true)
            ->where($where)
            ->page($page,$pageNum)
            ->order('id desc')
            ->select();
        foreach ($data['info'] as &$v){
            $v['video_file'] = $qiniu.$v['video_file'];
//            $video_info = json_decode(file_get_contents($v['video_file'] . '?avinfo'), true);
            $v['video_image'] = $qiniu.$v['video_image'];
        }
        $this->success('success',$data);
    }

    /**
     * @ApiTitle    (培训课程详情)
     * @ApiSummary  (培训课程详情)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/video_detail)
     *
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="int", required=true, description="培训课程id")
     *
     * @ApiReturn({
    "code": 1,
    "msg": "成功",
    "time": "1571492001",
    "data": {
    "id"://ID
    "study_id"://学习系统id
    "is_major"://1主修2选修
    "tag"://标签
    "name"://课程名称
    "video_file"://视频地址
    "video_image"://视频首帧图
    "duration"://总时长/秒
    "min"://总时长/分
    "class_hour"://学时
    "content"://内容详情
    "teacher"://讲师
    "expirationtime"://截止日期
    "is_join"://是否已经加入学习计划1未加入2已加入
    "bofangtime"://播放时长/秒
    }
    })
     */
    public function video_detail()
    {
        $user_id = $this->auth->id;
        $id = $this->request->param('id');
        if(empty($id)){
            $this->error('缺少必要参数');
        }

        $user_info = Db::name('user')->where('id',$user_id)->find();
        if(empty($user_info['image']) || empty($user_info['phone'])){
            $this->error('请先完善个人信息');
        }

        $qiniu = get_addon_config('qiniu')['cdnurl'];
        $data = Db::name('classes')
            ->alias('a')
            ->join('study b','a.study_id = b.id')
            ->where('a.id',$id)
            ->field('a.*,b.expirationtime')
            ->find();

        //查看播放秒数
        $class_detail = Db::name('class_detail')
            ->where('user_id',$user_id)
            ->where('class_id',$id)
            ->find();
        if(empty($class_detail)){
            $res['user_id'] = $user_id;
            $res['class_id'] = $id;
            $res['duration'] = 0;
            $res['createtime'] = time();
            Db::name('class_detail')->insert($res);
            $data['bofangtime'] = 0;
            $data['is_end'] = 2;
        }else{
            $data['bofangtime'] = $class_detail['duration'];
            $data['is_end'] = $class_detail['is_end'];
        }


        $info = Db::name('study_class')
            ->where('third_id',$user_id)
            ->where('study_id',$data['study_id'])
            ->where('class_id',$id)
            ->find();
        if(empty($info)){
            $data['is_join'] = 1;
        }else{
            $data['is_join'] = 2;
        }
        //视频地址以及首帧图
        $data['video_file'] = $qiniu.$data['video_file'];
//        $video_info = json_decode(file_get_contents($data['video_file'] . '?avinfo'), true);
        $data['video_image'] = $qiniu.$data['video_image'];
        $data['expirationtime'] = date('Y-m-d H:i:s',$data['expirationtime']);
        $data['min'] = ceil($data['duration']/60);
        $this->success('success',$data);
    }

    /**
     * @ApiTitle    (记录播放时间)
     * @ApiSummary  (记录播放时间)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/bofang)
     *
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="int", required=true, description="培训课程id")
     * @ApiParams   (name="duration", type="int", required=true, description="播放时间")
     *
     * @ApiReturn({
    "code": 1,
    "msg": "成功",
    "time": "1571492001",
    "data": {
    }
    })
     */
    public function bofang()
    {
        $user_id = $this->auth->id;
        $id = $this->request->param('id');
        $duration = $this->request->param('duration');
        if(empty($id) || empty($duration)){
            $this->error('缺少必要参数');
        }

        $class = Db::name('classes')
            ->where('id',$id)
            ->field('id,duration,study_id')
            ->find();



        if($duration >= $class['duration']){
            $is_end = 1;

            $study_class = Db::name('study_class')
                ->where('third_id',$user_id)
                ->where('study_id',$class['study_id'])
                ->where('class_id',$id)
                ->find();
            if(!empty($study_class)){
                Db::name('study_class')
                    ->where('third_id',$user_id)
                    ->where('study_id',$class['study_id'])
                    ->where('class_id',$id)
                    ->update(['status'=>2,'playtime'=>$duration]);
            }
        }else{
            $is_end = 2;
            $study_class = Db::name('study_class')
                ->where('third_id',$user_id)
                ->where('study_id',$class['study_id'])
                ->where('class_id',$id)
                ->find();
            if(!empty($study_class)){
                Db::name('study_class')
                    ->where('third_id',$user_id)
                    ->where('study_id',$class['study_id'])
                    ->where('class_id',$id)
                    ->update(['playtime'=>$duration]);
            }
        }

        $data = Db::name('class_detail')
            ->where('user_id',$user_id)
            ->where('class_id',$id)
            ->update(['duration'=>$duration,'is_end'=>$is_end]);
        if(empty($data)){
            $this->error('失败');
        }else{
            $this->success('成功');
        }
    }

    /**
     * @ApiTitle    (加入学习计划)
     * @ApiSummary  (加入学习计划)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/join)
     *
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="int", required=true, description="培训课程id")
     *
     * @ApiReturn({
    "code": 1,
    "msg": "成功",
    "time": "1571492001",
    "data": {
    }
    })
     */
    public function join()
    {
        $info['third_id'] = $this->auth->id;
        $info['class_id'] = $this->request->param('id');
        if(empty($info['class_id'])){
            $this->error('缺少必要参数');
        }
        $data = Db::name('classes')
            ->where('id',$info['class_id'])
            ->field('study_id,duration')
            ->find();
        $info['study_id'] = $data['study_id'];


        //查询用户是否已经播放完毕该视频
        $video = Db::name('class_detail')
            ->where('user_id',$info['third_id'])
            ->where('class_id',$info['class_id'])
            ->find();
        if(empty($video)){
            $info['playtime'] = 0;
        }else{
            if($video['is_end'] == 2){
                $info['playtime'] = $video['duration'];
            }else{
                $info['playtime'] = $data['duration'];
                $info['status'] = 2;
            }
        }

        $info['createtime'] = time();
        $is_have = Db::name('study_class')
            ->where('third_id',$info['third_id'])
            ->where('study_id',$info['study_id'])
            ->where('class_id',$info['class_id'])
            ->find();
        if(empty($is_have)){
            $arr = Db::name('study_class')->insertGetId($info);
            if(empty($arr)){
                $this->error('添加失败');
            }else{
                $this->success('添加成功');
            }
        }else{
            $this->error('您已经添加过了');
        }
    }

    /**
     * @ApiTitle    (移除学习计划)
     * @ApiSummary  (移除学习计划)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/del_join)
     *
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="int", required=true, description="培训课程id")
     *
     * @ApiReturn({
    "code": 1,
    "msg": "成功",
    "time": "1571492001",
    "data": {
    }
    })
     */
    public function del_join()
    {
        $user_id = $this->auth->id;
        $id = $this->request->param('id');
        if(empty($id)){
            $this->error('缺少必要参数');
        }
        $data = Db::name('classes')
            ->where('id',$id)
            ->value('study_id');

        $arr = Db::name('study_class')
            ->where('third_id',$user_id)
            ->where('study_id',$data)
            ->where('class_id',$id)
            ->delete();
        if(empty($arr)){
            $this->error('移除失败');
        }else{
            $this->success('移除成功');
        }

    }
    
    /**
     * @ApiTitle    (我的考试)
     * @ApiSummary  (我的考试)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/myexam)
     *
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="int", required=true, description="学习系统id")
     *
     * @ApiReturn({
    "code": 1,
    "msg": "成功",
    "time": "1571492001",
    "data": {
          "exam":[
            "id"://id,
            "examname"://考试名称
            "class_hour"://所需课时
            "finish_hour"://完成课时
            "image"://图片
            "proportion"://比例
            "expirationtime"://截止日期
             "is_xian"://是否显示1显示2不显示
          ],
        "info": [
            {
            "name": //课程名称,
            "class_hour": //课时,
            "is_major": //1主修2选修,
            "duration": //时长,
            "status": //状态1学习中2已完成,
            "playtime": //已播放的秒数,
            "proportion": //比例
            },
        ]
    }
    })
     */
    public function myexam()
    {
        $qiniu = get_addon_config('qiniu')['cdnurl'];
        $user_id = $this->auth->id;
        $id = $this->request->param('id');
        if(empty($id)){
            $this->error('缺少必要参数');
        }
        $data['exam'] = Db::name('study')
            ->where('id',$id)
            ->find();

        $data['exam']['image'] = $qiniu.$data['exam']['image'];

        $finish_hour = Db::name('study_class')
            ->alias('a')
            ->join('classes b','a.class_id = b.id')
            ->where('a.third_id',$user_id)
            ->where('a.study_id',$id)
            ->where('a.status',2)
            ->field('sum(b.class_hour) as finish_hour')
            ->find();

        if(empty($finish_hour['finish_hour'])){
            $data['exam']['finish_hour'] = 0;
        }else{
            $data['exam']['finish_hour'] = $finish_hour['finish_hour'];
        }

        //查询出所有该科目的必修课
        $class_ids = Db::name('classes')->where('study_id',$id)->where('is_major',1)->column('id');
        $is_end = Db::name('study_class')
            ->where('third_id',$user_id)
            ->where('study_id',$id)
            ->whereIn('class_id',$class_ids)
            ->where('status',1)
            ->find();

        //查看用户该科目是否已经考过3次了
        $exam_times = Db::name('third_exam')
            ->where('user_id',$user_id)
            ->where('study_id',$id)
            ->whereTime('createtime','month')
            ->count();

        //该用户绑定该科目的有效期
        $third_study = Db::name('third_study')->where('third_id',$user_id)->where('study_id',$id)->find();

        if($third_study['periodtime'] < time() || $data['exam']['expirationtime']<time() || $data['exam']['finish_hour'] < $data['exam']['class_hour'] || !empty($is_end) || $exam_times >= 3){
            $data['exam']['is_xian'] = 2;
            $third_exam = Db::name('third_exam')
                ->where('user_id',$user_id)
                ->where('study_id',$id)
                ->order('exam_num desc')
                ->find();
        }else{
            $study = Db::name('study')->where('id',$id)->find();
            $where_exam = [
                'user_id' => $user_id,
                'study_id' => $id,
                'score' => ['egt',$study['pass_mark']]
            ];
            $third_exam = Db::name('third_exam')
                ->where($where_exam)
                ->whereTime('createtime','year')
                ->find();
            $data['exam']['is_xian'] = $third_exam  ? 2 : 1;
        }
        $data['exam']['expirationtime'] = date('Y-m-d H:i:s',$data['exam']['expirationtime']);

        unset($data['exam']['updatetime']);
        unset($data['exam']['createtime']);
        $a = round($data['exam']['finish_hour']/$data['exam']['class_hour']*100,0);
        if($a > 100){
            $a = 100;
        }
        $data['exam']['proportion'] = $a.'%';

        $data['info'] = Db::name('study_class')
            ->alias('a')
            ->join('classes b','a.class_id = b.id')
            ->where('a.third_id',$user_id)
            ->where('a.study_id',$id)
            ->field('b.id,a.id as study_class_id,b.name,b.class_hour,b.is_major,b.duration,a.status,a.playtime')
            ->select();
        foreach ($data['info'] as &$v){
            if($v['status'] == 1){
                $v['proportion'] = round($v['playtime']/$v['duration']*100,0).'%';
            }else{
                $v['proportion'] = '100%';
            }
            $v['duration'] = ceil($v['duration']/60);
        }
        $data['third'] = $third_exam;
        $this->success('success',$data);
    }


    /**
     * @ApiTitle    (查看证书)
     * @ApiSummary  (查看证书)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/certificate)
     *
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="int", required=true, description="考试记录id")
     *
     * @ApiReturn({
    "code": 1,
    "msg": "成功",
    "time": "1571492001",
    "data": {
        "qrcodeurl": //证书图片,
        "score": //分数
    }
    })
     */
    public function certificate(){
        $qiniu = get_addon_config('qiniu')['cdnurl'];
        $user_id = $this->auth->id;
        $id = $this->request->param('id');
        if(empty($id)){
            $this->error('缺少必要参数');
        }

        //查询该课程的详细信息
        $data = Db::name('third_exam')
            ->alias('a')
            ->join('study b','a.study_id = b.id')
            ->join('user c','a.user_id = c.id')
            ->where('a.id',$id)
            ->field('a.id,a.score,a.user_id,a.study_id,a.createtime,b.yinimage,b.workname,c.studynum,b.class_hour,c.image,c.card,c.nickname')
            ->find();
        $year = date('Y',$data['createtime']);
        $data['createtime'] = date('Y年m月d日',$data['createtime']);


        if(empty($data['image'])){
            $this->error('请先上传用户头像');
        }


        //将用户的头像保存到本地
        $dir_user = ROOT_PATH . 'public' . DS . 'uploads/user';
        if (!file_exists($dir_user)){
            mkdir($dir_user,0777,true);
        }
        $qiniu_url = $qiniu.$data['image'];
        $image_name = $user_id.'.png';
        $furl = $dir_user . DS .$image_name;
        $a = file_get_contents($qiniu_url);
        file_put_contents($furl,$a);
        
        //将考试的印章图片保存到本地
        $dir_qrcode = ROOT_PATH . 'public' . DS . 'uploads/qrcode';
        if (!file_exists($dir_qrcode)){
            mkdir($dir_qrcode,0777,true);
        }
        $yinimage = $qiniu.$data['yinimage'];
        $imagename = $data['study_id'].'.png';
        $yinfurl = $dir_qrcode . DS .$imagename;
        $b = file_get_contents($yinimage);
        file_put_contents($yinfurl,$b);


        //用户头像
        $user_image = \think\Image::open(ROOT_PATH."public/uploads/user/$image_name");
        $user_image->thumb(184,220,\think\Image::THUMB_CENTER)->save(ROOT_PATH."public/uploads/user/$image_name");

        //印象头像
        $yin_image = \think\Image::open(ROOT_PATH."public/uploads/qrcode/$imagename");
        $yin_image->thumb(248,242,\think\Image::THUMB_CENTER)->save(ROOT_PATH."public/uploads/qrcode/$imagename");


        
        $file_path = "$id.png";
        $image = \think\Image::open(ROOT_PATH."public/assets/img/yuan.png");
        $path_ttf = ROOT_PATH.'public/assets/fonts/PingFang.ttf';
        //证书编号
        $text = 'TJAG'.$year.$data['studynum'].$id;
        //培训单位盖章
        $text1 = '培训单位盖章';

        $image->water(ROOT_PATH."public/uploads/qrcode/$imagename",[1200,602],100);
        $image->water(ROOT_PATH."public/uploads/user/$image_name",[300,430],100);
        $image->text($data['card'],$path_ttf,25,'#000000',[300,778]);
        $image->text($text,$path_ttf,25,'#000000',[300,868]);
        $image->text($data['nickname'],$path_ttf,30,'#000000',[850,364]);
        $image->text($data['nickname'],$path_ttf,30,'#000000',[851,364]);
        $image->text($year,$path_ttf,30,'#000000',[1121,364]);
        $image->text($year,$path_ttf,30,'#000000',[1122,364]);
        $image->text($data['workname'],$path_ttf,30,'#000000',[1325,362]);
        $image->text($data['workname'],$path_ttf,30,'#000000',[1326,362]);
        $image->text($data['class_hour'],$path_ttf,30,'#000000',[1071,442]);
        $image->text($data['class_hour'],$path_ttf,30,'#000000',[1072,442]);
        $image->text($data['createtime'],$path_ttf,30,'#000000',[1121,832]);
        $image->text($data['createtime'],$path_ttf,30,'#000000',[1122,832]);
        $image->text($text1,$path_ttf,30,'#000000',[1187,772]);
        $image->text($text1,$path_ttf,30,'#000000',[1188,772]);
        $image->save(ROOT_PATH . 'public' . DS . 'uploads' . DS . $file_path,'png',100);

        // 将编号存入数据库
        Db::name('third_exam')->where('id',$id)->update(['certificate_sn'=>$text]);

        $answer['qrcodeurl'] = request()->domain().'/uploads/'.$id.'.png';
        $answer['score'] = $data['score'];
        $this->success('success',$answer);

    }



    public function get_video_first_image($video_url,$video_info){
        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'];
        }
        return $video_url.'?vframe/jpg/offset/1/w/'.$width.'/h/'.$height;
    }
}