<?php


namespace app\lumaapi\controller;

use app\lumaapi\service\EventService;
use app\lumaapi\service\VideoService;
use app\utils\encryption;
use think\cache\driver\Redis;
use think\Db;
use think\Request;
use think\Validate;

class Lumavideo extends Common
{
    /**
     * 前置操作 except不需要登录，only需要登录
     */
    protected $beforeActionList = [
        'need_login' => ['except' => ["previewvideo"
        ]],
    ];
    /*public function mongodb(){
        $bulk=new BulkWrite();
        $bulk->delete([]);
        $manager=new Manager("mongodb://127.0.0.1/");
        $manager->executeBulkWrite("db2.db1",$bulk);
        $client = new Client();
        $db2=$client->db2;//数据库
        $db=$db2->db1;//自定义数据表
        $document = array("title" =>"test","online"=>"true");
        $document1 = array("title" =>"test123","online"=>"false");
        $db->insertOne($document);
        $db->insertOne($document1);
        $cursor= $db->find();
    }*/

    public function videoList(){
        $page=$this->request->param("page",1);
        $skeyword=$this->request->param("skeyword");
        $lumaUid=$this->user_id;
        $redis=new Redis();
        $map['a.mychannel']=3;
        $map['a.hide']=1;
        $sql=" ( a.video != '' OR a.video IS NOT NULL ) ";
        if(!empty($redis->get("luma".$lumaUid))){
            $data=$redis->get("luma".$lumaUid);
            $sql =$sql.' and a.id not in ('.substr($data,1,strlen($data)).')';
        }
        if(!empty($skeyword)){
            $map['a.title|m.nickname'] = ['LIKE','%'.$skeyword.'%'];
        }
        $articleDb=Db::name('article')->alias('a')->join('member m','a.uid=m.id')->field('a.*')
            ->where($map)->where($sql)->limit($this->pageSize)->order("a.des","desc")->order("a.create_time","desc")->page($page)->cache(_cache('db'))->select();
        if(count($articleDb)==0){
            $redis->set('luma'.$lumaUid,null);
            $articleDb=Db::name('article')->alias('a')->join('member m','a.uid=m.id')->field('a.*')
                ->where($map)->limit($this->pageSize)->order("a.des","desc")->order("a.create_time","desc")->page($page)->cache(_cache('db'))->select();
        }
        foreach ($articleDb as $key=>$val){
            $articleDb[$key]['qiniu_video']=$articleDb[$key]['video']=encryption::think_encrypt($val['qiniu_video'],$this->key);
            $articleDb[$key]['user']=Db::name('member')->field('nickname,img')->where(['id'=>$val['uid']])->cache(_cache('db'))->find();
            $redisdata=$redis->get('luma'.$lumaUid);
            $redis->set('luma'.$lumaUid,$redisdata.",".$val['id']);
            Db::name('article')->where(['id'=>$val['id']])->setInc('click');
            $zan=Db::name('article_zan')->where(['uid'=>$this->uid,'aid'=>$val['id']])->fetchSql(false)->find();
            $articleDb[$key]['is_zan']=isset($zan['zan'])==1?true:false;
            $articleDb[$key]['is_cai']=isset($zan['cai'])==1?true:false;
            $guanzhu=Db::name('member_guanzhu')->where(['uid'=>$this->uid,'gz_uid'=>$val['uid']])->fetchSql(false)->find();
            $articleDb[$key]['is_guanzhu']=isset($guanzhu)?true:false;
            EventService::readfavorite($this->uid,$val['uid']);
            $articleDb[$key]['goods']=VideoService::randomGoods();
        }
        $this->success($articleDb);
    }


    //视频分类
    public function typeid(){
        $data=DB::name('typeid')->where(['id'=>['between',[5,34]]])->select();
        $this->success($data);
    }


    // 投稿文章
    // title    标题      必填
    // content  内容      必填
    // typeid   分类      必填
    // writer   作者      选项
    // image    缩略图    选项
    // keywords  关键词   选项
    // description 描述   选项
    // source   来源      选项
    // mychannel   1文章 2图片 3视频
    public function articleAdd(){
        $aritlceId=$this->request->param("id");
        $typeid=$this->request->param("typeid");
        $title=$this->request->param("title");
        $tags=$this->request->param("tags");
        $mychannel=$this->request->param("mychannel")? $this->request->param("mychannel") :3;
        $description=$this->request->param("description");

        //开始验证
        $validate = new Validate([
            'title'         =>      'max:30',
            'description'   =>      'max:250',
            'mychannel'     =>      'require|number|in:1,2,3',
            'typeid'         =>      'require|number',
        ]);
        $validata=[
            'title'         =>      $title,
            'description'   =>      $description,
            'mychannel'     =>      $mychannel,
            'typeid'           =>      $typeid,
        ];
        if (!$validate->check($validata)) {
            $this->error($validate->getError());
        }
        // 检测是否开启投稿
        $data=DB::name('member_config')->where("name='articleAdd' or name='articleHide' or name='articleScore' or name='articleNum' or name='articleCode' or name='articleJingyan' or name='articleMoney'")->fetchSql(false)->select();
        $articleAdd=$data['0']['text'];     //文章投稿
        $articleHide=$data['1']['text'];    //投稿审核
        $articleScore=$data['2']['text'];   //投稿奖励积分
        $articleNum=$data['3']['text'];     //每天投稿限制
        $articleCode=$data['4']['text'];    //投稿文章开启验证码
        $articleJingyan=$data['5']['text'];   //投稿奖励积分
        $articleMoney=$data['6']['text'];   //投稿奖励积分
        unset($data);   // 销毁变量
        // 读取会员配置 - 结束
        // 检测会员投稿分组权限
        if($articleAdd=='-1'){
            $this->error("文章投稿已关闭");
        }
        // 检测投稿文章是否审核
        if($mychannel==1 || $mychannel==2){
            $images=$this->request->param("image");
            if($images){
                $where['images']=$images;
                //提取第一条缩略图
                $img=json_decode(htmlspecialchars_decode($images),true);
                if($img){
                    $where['image']=$img[0];
                }
            }
        }else if($mychannel==3){
            $video=$this->request->param("video");
            //$videourl=$this->request->param("videourl");
            //$videodate=$this->request->param("videodate");
            if(empty($video)){
                $this->error("请上传视频");
            }
            $where['qiniu_video_type']=1;
            $where['video']=$where['qiniu_video']=$video;
            //$where['video']=$videourl;
            if($video){
                $videodate=get(_imgUrl().$video."?avinfo");
                $videodate=json_decode($videodate,true);
                if($videodate){
                    $videodate=videoDate($videodate['streams'][0]['duration']);
                    $where['videodate']=$videodate;
                }
            }
            //file_put_contents("video.txt",var_export($video,true));
        }
        //结束验证
        // 是否开启验证
        if($articleCode==1){
            $yzm=$this->request->param("yzm");
            if($yzm){
                if(!captcha_check($yzm)){
                    $this->error("'验证码错误'");
                }
            }else{
                $this->error("'请输入验证码'");
            }
        }
        $where['image']=$this->request->param("image");
        $where['title']=$title;
        $where['tags']=$tags;
        $where['typeid']=$typeid;
        $where['hide']=1;
        $where['mychannel']=$mychannel;
        $time=time();
        $where['update_time']=$time;
        $where['des']=50;
        $where['flags']=0;
        $where['click']=0;
        $where['create_time']=$time;
        $where['uid']=$this->uid;
        $where['fangshi']='1';
        $where['source']=$this->member['nickname'];
        $where['videoType']='luma108';
        $id=Db::name('article')->insertGetId($where);
        if($where['hide']==1){
            // 检测金额奖励
            if($articleMoney){
                // 检测是否已奖励，防止重复奖励
                $aritlcejiance=Db::name('member_records')->where(['type'=>'money','text'=>'投稿奖励ID：'.$id,'data'=>'+'])->value('id');
                if(!$aritlcejiance){
                    _records($this->member['id'],'投稿奖励ID：'.$id,$articleMoney,'money','+');
                    Db::name('member')->where('id',$this->member['id'])->setInc('money',$articleMoney);
                }
            }
            // 检测积分奖励
            if($articleScore){
                // 检测是否已奖励，防止重复奖励
                $aritlcejiance=Db::name('member_records')->where(['type'=>'score','text'=>'投稿奖励ID：'.$id,'data'=>'+'])->value('id');
                if(!$aritlcejiance){
                    _records($this->member['id'],'投稿奖励ID：'.$id,$articleScore,'score','+');
                    Db::name('member')->where('id',$this->member['id'])->setInc('score',$articleScore);
                }
            }
            // 检测经验值奖励
            if($articleJingyan){
                // 检测是否已奖励，防止重复奖励
                $aritlcejiance=Db::name('member_records')->where(['type'=>'jingyan','text'=>'投稿奖励ID：'.$id,'data'=>'+'])->value('id');
                if(!$aritlcejiance){
                    _records($this->member['id'],'投稿奖励ID：'.$id,$articleJingyan,'jingyan','+');
                    Db::name('member')->where('id',$this->member['id'])->setInc('jingyan',$articleJingyan);
                }
            }
            _records($this->member['id'],'投稿文章ID：'.$id.'自动审核通过');
            $this->success([],"'发布成功'");
        }else{
            _records($this->member['id'],'投稿文章ID：'.$id.'等待审核');
            $this->success([],"'发布成功，等待审核'");
        }
        $this->error("'发布失败'");
    }



    public  function searchList(){
        $type=$this->request->param("type");//0综合，1视频，2用户，3话题
        $skeyword=$this->request->param("skeyword");
        $page=$this->request->param("page",0);
        $list=[];
        if (!empty($skeyword)) {
            if($type==0||$type==1||$type==3) {
                if ($type == 3) {
                    $map['a.tags'] = ['LIKE', '%' . $skeyword . '%'];
                }else if($type==1){
                    $map['a.title'] = ['LIKE', '%' . $skeyword . '%'];
                }else{
                    $map['a.title|a.tags|m.nickname'] = ['LIKE', '%' . $skeyword . '%'];
                }
                $map['a.mychannel'] = 3;
                $map['a.hide'] = 1;
                $sql = " ( a.video != '' OR a.video IS NOT NULL )";
                $list = Db::name('article')->alias('a')->join('member m', 'a.uid=m.id')->field('a.*')
                    ->where($map)->where($sql)->limit($this->pageSize)->order("a.des", "desc")->order("a.create_time", "desc")->page($page)->cache(_cache('db'))->select();
                foreach ($list as $key=>$val){
                    $list[$key]['user']= _user($val['uid']);
                }
            }else if($type==2){
                $map['id|nickname'] = ['LIKE', '%' . $skeyword . '%'];
                $list=Db::name('member')->field('id,nickname,img')->where($map)->cache(_cache('db'))->select();
                foreach ($list as $key=>$val){
                    $status=Db::name('member_guanzhu')->where(['uid'=>$this->uid,'gz_uid'=>$val['id']])->count();
                    $list[$key]['is_guanzhu'] =$status>0?true:false;
                }
            }
        }
        $this->success($list);
    }


}