<?php
namespace Admin\Controller;
use Common\Controller\AdminbaseController;
require('./Expand/Qiniu/autoload.php');
use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
class EducloudController extends AdminbaseController {
    public function index(){
        $info=$this->get_site_info();
        $postdata=$info;
        $postdata['start_date']=date('Y-m-d', strtotime('-6 days'));
        $postdata['end_date']=date('Y-m-d', time());
        $videourl=$info['server']."/api/educloud/getVideoCountInfo";
        $videorestemp= $this->post_curl($videourl,$postdata);
        $videoresult=json_decode($videorestemp,true);
        if($videoresult['code']==0){
            if($videoresult['data']['charge_type']==0){
                $videoresult['data']['total_flow_limit']=$videoresult['data']['month_flow_limit'];
            }
            $video['code']=0;
            $video['remain_flow']=$this->format_file_size($videoresult['data']['total_flow_limit']-$videoresult['data']['used_flow']);
            $video['remain_storage']=$this->format_file_size($videoresult['data']['total_storage']-$videoresult['data']['used_storage']);
            $video['total_storage']=$this->format_file_size($videoresult['data']['total_storage']);
            $video['used_storage']=$this->format_file_size($videoresult['data']['used_storage']);
            $video['total_flow_limit']=$this->format_file_size($videoresult['data']['total_flow_limit']);
            $video['used_flow']=$this->format_file_size($videoresult['data']['used_flow']);
            $video['remain_storage_BG']=round(($videoresult['data']['total_storage']-$videoresult['data']['used_storage'])/1024/1024/1024,2);
            $video['remain_flow_GB']=round(($videoresult['data']['total_flow_limit']-$videoresult['data']['used_flow'])/1024/1024/1024,2);
            $video['used_storage_GB']=round($videoresult['data']['used_storage']/1024/1024/1024,2);
            $video['used_flow_GB']=round($videoresult['data']['used_flow']/1024/1024/1024,2);
            $video['remain']=floor((strtotime($videoresult['data']['expire_time'])-strtotime(date('Y-m-d h:i:s', time())))/86400);
            $this->assign("videoinfo",$video);
            $this->assign("remain_flow",$video['remain_flow']);
            $this->assign("remain_flow_GB",$video['remain_flow_GB']);
            $this->assign("used_flow", $video['used_flow']);
            $this->assign("used_flow_GB", $video['used_flow_GB']);
            $this->assign("remain_storage",$video['remain_storage']);
            $this->assign("remain_storage_BG",$video['remain_storage_BG']);
            $this->assign("used_storage",$video['remain_storage']);
            $this->assign("used_storage_GB",$video['used_storage_GB']);
            $getUsedFlowurl=$info['server']."/api/educloud/getUsedFlow";
            $UsedFlowTime=array();
            $UsedFlowNum=array();
            for ($x=0,$i=6; $x<=6; $x++) {
                $UsedFlowTime[]=$postdata['UsedFlow_start_date']=date('Y-m-d', strtotime('-'.$i.' days'));
                $postdata['UsedFlow_end_date']=date('Y-m-d', strtotime('-'.$i.' days'));
                $UsedFlow=json_decode($this-> post_curl($getUsedFlowurl,$postdata),true);
                $UsedFlowNum[]=round($UsedFlow['data']['flow']/1024/1024/1024,2);
                $i=$i-1;
            }
            $UsedFlowTime= json_encode($UsedFlowTime);
            $UsedFlowNum = json_encode($UsedFlowNum);
            $this->assign('UsedFlowTime', $UsedFlowTime);
            $this->assign('UsedFlowNum', $UsedFlowNum);

        }else{
            $this->assign("videoinfo",$videoresult);
        }
        $liveurl=$info['server']."/api/educloud/getLiveCountInfo";
        $liverestemp= $this->post_curl($liveurl,$postdata);
        $liveresult=json_decode($liverestemp,true);
        if($liveresult['code']==0){
            $liveresult['data']['remain']=floor((strtotime($liveresult['data']['expire_time'])-strtotime(date('Y-m-d h:i:s', time())))/86400);
            $this->assign("liveoinfo",$liveresult['data']);
            $DayPeakUserurl=$info['server']."/api/educloud/getDayPeakUser";
            $DayPeakUser=json_decode($this-> post_curl($DayPeakUserurl,$postdata),true);
            $TodyPeakUser=$DayPeakUser['data']['peak_user'][date('Y-m-d', time())];
            $time=array();
            $num=array();
            foreach($DayPeakUser['data']['peak_user'] as $key=>$v)
            {
                $time[]=$key;$num[]=$v;
            }
            $str_num= json_encode($num);
            $str_time = json_encode($time);

            $this->assign("liveinfo",$liveresult);
            $this->assign('str_num', $str_num);
            $this->assign('str_time', $str_time);
            $this->assign('TodyPeakUser', $TodyPeakUser);
        }else{
            $this->assign("liveinfo",$liveresult);
        }
        $this->display();
    }
    /**
     * 注册教育云账户
     */
    public function add(){
        if (IS_POST) {
            $postdata=I('post.');
            if($postdata['BJ_Partner_ID']==''){
                $this->error("请正确填写Partner_ID！");
            }
            if($postdata['BJ_Partner_Key']==''){
                $this->error("请正确填写Partner_Key！");
            }
            if($postdata['BJ_Secret_Key']==''){
                $this->error("请正确填写Secret_Key！");
            }
            if($postdata['BJ_private_domain']==''){
                $this->error("请正确填写私有域名！");
            }
            $data['domain']=$this->get_domain();
            $info=$this->get_site_info();
            $data['authorcode']=$info['author_code'];
            $url= $info['server']."/api/educloud/checkautho";
            $restemp= $this->post_curl($url,$data);
            $res=json_decode($restemp,true);
            if($res['status']){
                sp_set_dynamic_config($postdata);
                $this->success('绑定成功',U('admin/educloud/index'));
            }else{
                $this->error($res['msg']);
            }
        }else{
           $BJ['BJ_Partner_ID']=C('BJ_Partner_ID');
           $BJ['BJ_Partner_Key']=C('BJ_Partner_Key');
           $BJ['BJ_Secret_Key']=C('BJ_Secret_Key');
           $BJ['BJ_private_domain']=C('BJ_private_domain');
           $this->assign("BJ",$BJ);
           $this->display();
        }
    }

    /**
     * 增加教育云点播视频上传目录
     */
    function addCategory($name){
        $info=$this->get_site_info();
        $postdata['domain']=$this->get_domain();
        $postdata['authorcode']=$info['author_code'];
        $postdata['name']=$name;
        $url=$info['server']."/api/educloud/addCategory";
        $restemp= $this->post_curl($url,$postdata);
        $res=json_decode($restemp,true);
        $where['id']=$_SESSION['ADMIN_ID'];
        $data['baijiayuncategory']=$res['data']['id'];
        $users_model=M("Users");
        $users_model->where($where)->save($data);
    }
    /**
     * 获取教育云视频列表
     */
    function getvideolist(){
        $info=$this->get_site_info();
        $UserInfo=$this->loginUserInfo();
        $CategoryList=$this->getCategoryList();
        $postdata['domain']=$this->get_domain();
        $postdata['authorcode']=$info['author_code'];
        $postdata['page_size']='20';
        $url=$info['server']."/api/educloud/getVideo";
        $VideoList=array();
        foreach($CategoryList as $key=>$v){
            $postdata['category_id']=$v['id'];
            $VideoListTemp=json_decode($this-> post_curl($url,$postdata),true);
            if(!empty($VideoListTemp['data']['list'])){
                $VideoList=array_merge($VideoList,$VideoListTemp['data']['list']);
            }
        }
        $this->assign('list',$VideoList);
        $this->display();
    }
    /**
     * 获取所有分类
     */
    function getCategoryList(){
        $info=$this->get_site_info();
        $postdata['domain']=$this->get_domain();
        $postdata['authorcode']=$info['author_code'];
        $url=$info['server']."/api/educloud/getCategoryList";
        $VideoList=json_decode($this-> post_curl($url,$postdata),true);
        return $VideoList['data']['list'];
    }
    /**
     * 删除教育云视频
     */
    function delVideo(){
        $video_id=I('id');
        $info=$this->get_site_info();
        $postdata['domain']=$this->get_domain();
        $postdata['authorcode']=$info['author_code'];
        $postdata['video_id']=$video_id;
        $url=$info['server']."/api/educloud/deleteVideo";
        $res=json_decode($this-> post_curl($url,$postdata),true);
        if($res['code']==0){
            $this->success("视频删除成功！");
        }else{
            $this->error($res['msg']);
        }
    }
    /**
     * 获取直播间列表
     */
    function getliveroomlist(){
        $info=$this->get_site_info();
        $url=$info['server']."/api/educloud/getLiveroomList";
        $LiveroomList=json_decode($this-> post_curl($url,$info),true);
        $this->assign('list',$LiveroomList);
        $this->display();
    }
    /**
     * 删除直播间
     */
    function delLiveroom(){
        $room_id=I('id');
        $info=$this->get_site_info();
        $postdata=$info;
        $postdata['room_id']=$room_id;
        $url=$info['server']."/api/educloud/delLiveroom";
        $res=json_decode($this-> post_curl($url,$postdata),true);
        if($res['code']==0){
            $this->success("房间删除成功！");
        }else{
            $this->error($res['msg']);
        }
    }
    /**
     * 获取回放列表
     */
    function  getplaybacklist(){
        $info=$this->get_site_info();
        $url=$info['server']."/api/educloud/getPlaybackList";
        $PlaybackList=json_decode($this-> post_curl($url,$info),true);
        $this->assign('list',$PlaybackList);
        $this->display();
    }
    /**
     * 删除回放
     */
    function delPlayback(){
        $room_id=I('id');
        $info=$this->get_site_info();
        $postdata=$info;
        $postdata['room_id']=$room_id;
        $url=$info['server']."/api/educloud/delPlayback";
        $res=json_decode($this-> post_curl($url,$postdata),true);
        if($res['code']==0){
            $this->success("回放删除成功！");
        }else{
            $this->error($res['msg']);
        }
    }
    function get_site_info(){
        $info['authorcode']=C('authoCode');
        $info['Partner_ID']=C('BJ_Partner_ID');
        $info['Partner_Key']=C('BJ_Partner_Key');
        $info['Secret_Key']=C('BJ_Secret_Key');
        $info['private_domain']=C('BJ_private_domain');
        $info['server']=C('server');
        $info['domain']=$this->get_domain();
        return $info;
    }
    function get_domain(){
        return sp_get_domain();
    }
    function post_curl($url,$data,$headers = '',$cookie = ''){
        if(!$url) return false;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_UNRESTRICTED_AUTH, 1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible, MSIE 11, Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko');
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        if($headers) curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_COOKIE, $cookie);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }
    /**
     * 字节转换为MB,GB，TB函数
     */
    function format_file_size($size){
        $units = array(' B', ' KB', ' MB', ' GB', ' TB');
        for ($i = 0; $size >= 1024 && $i < 4; $i++){
            $size /= 1024;
        }
        return round($size, 2).$units[$i];
    }
    function loginUserInfo(){
        $users_obj= M("Users");
        $id=$_SESSION['ADMIN_ID'];
        $user=$users_obj->where("id=$id")->find();
        return $user;
    }

    function Ali_account(){
        if (IS_POST) {
            $postdata=I('post.');
            if($postdata['Ali_KeyID']==''){
                $this->error("请正确填写KeyID！");
            }
            if($postdata['Ali_KeySecret']==''){
                $this->error("请正确填写KeySecret！");
            }
            if($postdata['Ali_Bucket']==''){
                $this->error("请正确填写Bucket！");
            }
            if($postdata['Ali_EndPoint']==''){
                $this->error("请正确填写EndPoint！");
            }
            if($postdata['Ali_UserId']==''){
                $this->error("请正确填写UserId！");
            }
            $data['domain']=$this->get_domain();
            $info=$this->get_site_info();
            $data['authorcode']=$info['authorcode'];
            $url= $info['server']."/api/educloud/Addcheckautho";
            $restemp= $this->post_curl($url,$data);
            $res=json_decode($restemp,true);
            if($res['status']){
                sp_set_dynamic_config($postdata);
                $this->success('绑定成功',U('admin/educloud/Ali_account'));
            }else{
                $this->error($res['msg']);
            }
        }else{
            $Ali['Ali_KeyID']=C('Ali_KeyID');
            $Ali['Ali_KeySecret']=C('Ali_KeySecret');
            $Ali['Ali_Bucket']=C('Ali_Bucket');
            $Ali['Ali_EndPoint']=C('Ali_EndPoint');
            $Ali['Ali_UserId']=C('Ali_UserId');
            $this->assign("Ali",$Ali);
            $this->display('aliaccount');
        }
    }
    function Ali_videolist(){
        $postdata=$this->Ali_info();
        $postdata['PageSize']=30;
        $postdata['aliyuncategory']='';
        $url = $postdata['server'] . "/api/educloud/getvideolist";
        $restemp= $this->post_curl($url,$postdata);
        $res=json_decode($restemp,true);
        $this->assign("videoList",$res['VideoList']['Video']);
        $this->display('alivideolist');
    }
    function Ali_videodel(){
        $postdata=$this->Ali_info();
        $postdata['id']=I('get.id');
        $url = $postdata['server'] . "/api/educloud/delvideo";
        $restemp= $this->post_curl($url,$postdata);
        $res=json_decode($restemp,true);
        if($res['RequestId']){
            $this->success('删除成功',U('admin/educloud/Ali_videolist'));
        }else{
            $this->error($res['msg'],U('admin/educloud/Ali_videolist'));
        }

    }
    function Ali_info(){
        $info['KeyID']=C('Ali_KeyID');
        $info['keySecret']=C('Ali_KeySecret');
        $info['Bucket']=C('Ali_Bucket');
        $info['EndPoint']=C('Ali_EndPoint');
        $info['UserId']=C('Ali_UserId');
        $info['server']=C('server');
        $info['domain']=$this->get_domain();
        $info['authorcode']=C('authoCode');
        return $info;
    }
    function qnCountAdd(){
        if (IS_POST) {
            $postdata=I('post.');
            sp_set_dynamic_config($postdata);
            $this->success('绑定成功',U('admin/educloud/qnCountAdd'));
        }else{
            $Qn['QN_AccessKey']=C('QN_AccessKey');
            $Qn['QN_SecretKey']=C('QN_SecretKey');
            $Qn['QN_Bucket']=C('QN_Bucket');
            $Qn['QN_Domain']=C('QN_Domain');
            $this->assign("Qn",$Qn);
            $this->display('qnCountAdd');
        }
    }
    function qnList(){
        $auth=$this->getauth();
        $bucketMgr = new BucketManager($auth);
        $bucket =C('QN_Bucket');
        $this->user_obj = D("Common/Users");
        $user=$this->user_obj->where(array('id'=>sp_get_current_userid()))->find();
        $prefix = $user['mobile'].'audio';
        $limit = '10000';
        list($iterms, $marker, $err) = $bucketMgr->listFiles($bucket, $prefix, $marker, $limit);
        foreach($iterms as $n=> $val){
            list($prefix, $filename) = split ('[/]', $iterms[$n]['key']);
            $iterms[$n]['filename']= $filename;
            $iterms[$n]['putTime']=date("Y-m-d H:i",$iterms[$n]['putTime']);
        }
        $iterms=$this->arr_sort($iterms,'putTime');
        $iterms=array_slice($iterms, 0, 27);
        $this->assign("result",$iterms);
        $this->display('qnList');
    }
    function qnDel(){
        $auth=$this->getauth();
        $bucketMgr = new BucketManager($auth);
        $bucket = C('QN_Bucket');
        $err = $bucketMgr->delete($bucket, $_GET['id']);
        if ($err !== null) {
            $this->success('删除成功',U("admin/educloud/qnList"));
        }else{
            $this->error('删除失败',U("admin/educloud/qnList"));
        }
    }
    function getauth(){
        $accessKey = C('QN_AccessKey');
        $secretKey = C('QN_SecretKey');
        return $auth = new Auth($accessKey, $secretKey);
    }
    function arr_sort($array,$key,$order="desc"){
        $arr_nums=$arr=array();
        foreach($array as $k=>$v){
            $arr_nums[$k]=$v[$key];
        }
        if($order=='asc'){
            asort($arr_nums);
        }else{
            arsort($arr_nums);
        }
        foreach($arr_nums as $k=>$v){
            $arr[$k]=$array[$k];
        }
        return $arr;
    }
}
