<?php
/**主播控制器
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaoq <570035208@qq.com>
 */

namespace Admin\Controller;
class LiveAnchorController extends BaseController{

	public function index(){//主播列表
        $name = "LiveAnchor";
        $map=array();
        $map['is_delete']=0;
        $keyword = I('keyword');
        if(!empty($keyword)){
            $whereor['id']=array('like','%'.$keyword.'%');
            $whereor['roomnumber']=array('like','%'.$keyword.'%');
            $whereor['_logic'] = 'or';
            $map['_complex'] = $whereor;
            $seotitle=$keyword.'_';
        }
        $list = $this->lists($name, $map);
        foreach($list as $key=>$val){
            $m_map['id']=$val['user_id'];
            $member_info=M("Member")->where($m_map)->field('nickname,username,mobile')->find();
            $list[$key]['user_name']=$this->getnickname($member_info);
        }
        $this->assign('list', $list);
        $this->display();
	}
	public function live_shenh(){
		$id = I('get.id');
		if(!$id) $this->error("参数错误");
        $map = array();$map['id'] = $id;
        $data = M('LiveAnchor')->where($map)->field(true)->find();
        $this->assign($data);
        $this->display();
	}
	public function change_shenh(){
		$post = I('param.');
		$id = $post['id'];
		$status = $post['status'];
		// echo "<pre>";print_r($post);exit;
		if(!$id){
			$this->error("参数错误");exit;
		}
		$map = array();$map['id'] = $id;$map['status'] = 0;
		$data = array();$data['status'] = $status;
		if($status == 1) $data['is_auth'] = 1;
		$ret = M('LiveAnchor')->where($map)->save($data);
		if($ret){
			$this->success("审核成功",U(CONTROLLER_NAME.'/index'));exit;
		}else{
			$this->error("审核失败");exit;
		}
	}
    public function getnickname($user){
        if($user['nickname']){
            return $user['nickname'];
        }elseif($user['username']){
            return $user['username'];
        }elseif($user['mobile']){
            return $user['mobile'];
        }
    }
    public function edit(){
        $id=I('id');
        $checked_id=I('checked');
        $map=array();
        $map['id']=$id;
        $info=M("LiveAnchor")->where($map)->find();
        $uids = array();

        $username = idtoname($info['user_id'], 'Member', 'username');
        if(empty($username)) $username = idtoname($info['user_id'], 'Member', 'mobile');
        $uids[$info['user_id']] = $username;

		$this->get_shops_list();
        $this->getcate();
        $this->assign('uids', $uids);
        $this->assign('checked_id', $checked_id);
        $this->assign('id', $id);

        $this->assign($info);
        if($checked_id>0){
            $this->display('check_edit');
        }else{
            $this->display();
        }

    }
    public function getcate(){
        $map['is_delete']=0;
        $list=M("LiveCategory")->where($map)->field('id,name')->select();
        foreach ($list as $v) {
            $category['']='请选择分类';
            $category[$v['id']] = $v['name'];
        }
        $this->assign('category', $category);
    }
    public function update(){
        $postdata = I('post.');
        $id=I('id');
        $model=M("LiveAnchor");
        $this->check_post($postdata, $id);
        $data = $model->create($postdata);
        if (false === $data) {
            $this->error($model->getError());
        }else{
            unset($data['id']);
        }
		$data['updatetime'] = NOW_TIME;
        $map = array();$map['id'] = $id;
        $result = $model->where($map)->save($data);
        if (false !== $result) {
            // $room_config=idtoname('room_number','LiveSet','value');
            $room_config=getconfig('ROOM_NUMBER');
            
            if(empty($postdata['roomnumber'])){
                $data = array();$data['roomnumber']=$room_config.$id;
                $map = array();$map['id']=$id;
                M("LiveAnchor")->where($map)->save($data);
            }
            if($postdata['checked_id']){
                $this->success(L('DO_OK'),U(CONTROLLER_NAME . '/reviewed'));
            }else{
                $this->success(L('DO_OK'), '', '', 'edit');
            }
        } else {
            $this->error(L('DO_ERROR'));
        }
    }
	public function get_shops_list(){
		$map = array();$map['status'] = 1;
		$shops_list_arr = M('Shops')->where($map)->field('id,name')->select();
		if($shops_list_arr){
			$shops_list = array(''=>'请选择');
			foreach($shops_list_arr as $k=>$v){
				$shops_list[$v['id']]=$v['name'];
			}
			// echo "<pre>";print_r($shops_list);exit;
			$this->assign('shop_list',$shops_list);
		}
	}
    public function insert(){
        $postdata = I('post.');
        $model=M("LiveAnchor");
        $this->check_post($postdata);
        // $postdata['status']=1;
		$postdata['addtime'] = $postdata['updatetime'] = NOW_TIME;
        $data = $model->create($postdata);
        $result=$model->add();
        if (false === $data) {
            $this->error($model->getError());
        }
        $jumpUrl = I('forward') ? I('forward') : U(CONTROLLER_NAME . '/index');
        $msg = array_merge(array('success' => L('EDIT_OK'), 'error' => L('EDIT_ERROR'), 'url' => $jumpUrl, 'ajax' => IS_AJAX), (array)$msg);
        if ($result) {
            // $c_map['name']='room_number';
            // $room_config=M("LiveSet")->where($c_map)->getField('value');

            $room_config=getconfig('ROOM_NUMBER');
            if (empty($postdata['roomnumber'])) {
                $r_data['roomnumber'] = $room_config . $result;
                $map['id'] = $result;
                M("LiveAnchor")->where($map)->save($r_data);
            }
            $this->success($msg['success'], $msg['url'], $msg['ajax']);
        }else {
                $this->error($msg['error'], $msg['url'], $msg['ajax']);
            }
    }
    /**
     * 检查提交的数据是否合法
     * @param array $postdata
     * @param $id 店铺id
     */
    public function check_post($postdata = array(), $id = 0)
    {
        if (empty($postdata)) $this->error("非法数据");
        if (empty($postdata['front_card'])) $this->error("身份证正面不得为空");
        if (empty($postdata['negative_card'])) $this->error("身份证反面不得为空");
        if (empty($postdata['handheld_card'])) $this->error("手持身份证照片不得为空");
        if ($postdata['user_id'] == '' && $postdata['checked_id']<=0) $this->error("会员不得为空");
        if ($this->check_uid($postdata['user_id'], $id) == true) $this->error("该会员已绑定主播");
        if ($this->check_is_uid($postdata['user_id'],$id) <= 0 && $postdata['checked_id']<=0) $this->error("该会员不存在");
        if ($this->check_roomnumber($postdata['roomnumber'],$id) == true ) $this->error("该房间号已存在");
    }
    /**
     * 判断会员是否存在
     */
    public function check_is_uid($uid)
    {
        $mod = M('Member');
        $map['uid'] = $uid;
        $uid = $mod->where($map)->count();
        return $uid;
    }

    /**验证会员是否重复
     * @param $uid
     * @return true是重复false是不重复
     */
    public function check_uid($uid, $id)
    {
        $map['user_id'] = $uid;
        $map['is_delete'] = 0;
        $shop_id = M('LiveAnchor')->where($map)->getField('id');
        if (empty($shop_id) || (!empty($shop_id) && $shop_id == $id)) return false;
        return true;
    }
    /**
     * 判断房间号是否唯一
     */
    public function check_roomnumber($roomnumber,$id){
        $map['roomnumber']=$roomnumber;
        $map['is_delete'] = 0;
        $room_count=M("LiveAnchor")->where($map)->getField('id');
        if($room_count && $id!=$room_count){
            return true;
        }else{
            return false;
        }
    }
   

    

    public function history(){
        $id=I('id');
        if(empty($id)){
            $this->error('参数错误');
        }
        $a_map=$map=array();
        $a_map['id']=$id;
        $anchor=M("LiveAnchor")->where($a_map)->getField('roomnumber');
        $name="LiveHistory";
        $map['roomnumber']=$anchor;
        $map['end_time']=array('gt',0);
        $order['id']='desc';
        $list = $this->lists($name, $map,$order);
        foreach($list as $key=>$val){
            $time=format_decimal(($val['end_time']-$val['begin_time'])%86400/3600);
            if($time<0){$time=0;}
            $list[$key]['hours']=$time;
            $list[$key]['begin_time']=time_format($val['begin_time']);
            $list[$key]['end_time']=time_format($val['end_time']);
            $list[$key]['liveonlinecount']=$val['liveonlinecount'];
        }
        $this->assign('list',$list);
        $this->display();
    }

    /**
     * 推荐商品
     */
    public function history_goods(){
        $id=I('id');
        if(empty($id)){
            $this->error('参数错误');
        }
        $list=D("LiveAnchor")->get_live_goodslist($id);
        $this->assign($list);
        $this->display();
    }

    //1207播放回看
    public function history_live(){
        $id=I('id');
        if(empty($id)) $this->error('参数错误');
        $url = U('Home/LiveAnchor/player',array('id'=>$id,'type'=>'look_back'));
        Header("Location:$url"); 
    }
    //end

    /**
     * 礼物
     */
    public function history_gift(){
        $id=I('id');
        if(empty($id)){
            $this->error('参数错误');
        }
        $map=array();
        $map['history_id']=$id;
        $list = $this->lists("LiveGiftLink",$map);
        foreach($list as $key=>$val){
            $u_map['id']=$val['user_id'];
            $member_author=M("Member")->where($u_map)->field('nickname,username,mobile,header_img')->find();
            $list[$key]['name']=$this->getnickname($member_author);
        }
        $this->assign('list',$list);
        $this->display();
    }
    /**
     * 删除，回收站
     * @param $is_delete 0恢复,1删除
     */
    public function recycling()
    {
        $id = I('id');
        $map=$where=array();
        $where['is_delete'] = 1;
        $map['id'] = $id;
        $info=M("LiveAnchor")->where($map)->save($where);
        if($info){
            $this->success(L('HAVE_PUT_IN_RECYCLE'));
        }else{
            $this->error(L('DELETE_FAILED'));
        }
    }

    /**
     * 测试直播
     */
    public function start_live(){
        $room=I('room');
        $map=array();
        $map['roomnumber']=$room;
        $data['status']=1;
        $data['is_play_default']=1;
        M("LiveAnchor")->where($map)->save($data);
        $score=M("LiveAnchor")->where($map)->getField('default_video_source');
        if(empty($score)){
            $this->error("默认播放视频源为空，不能测试播放");
        }
        $result = D('Live/Chat')->runHistory('start','',$room,1);

        if($result['status']==1){
            $this->success("测试直播播放成功，请到前台页面查看",U("LiveAnchor/index"));
        }
    }

    /**
     * 主播收益
     */
    public function live_divided(){
        $room=I('room');
        if(empty($room)){
            $this->error("参数错误");
        }
        $map=array();
        $map['roomnumber']=$room;
        $anchor_uid=M("LiveAnchor")->where($map)->getField('user_id');
        $map=array();
        $map['status']=1;
        $map['anchor_id']=$anchor_uid;
        $map['divided_status']=array("in",'1,2');
        $list=$this->lists("LiveDivided",$map);
        foreach($list as $key=>$val){
            $list[$key]['goods_name']=idtoname($val['goods_id'],"Goods",'goods_name');
            $list[$key]['goods_attr']=D("Common/GoodsAttr")->goods_to_attrname($val['goods_attr']);
            $list[$key]['divided_time']=time_format($val['divided_time']);
        }
        $this->assign('list',$list);
        $this->assign('roomnumber',$room);
        $this->display();
    }

    /**
     * 主播收益详情页
     */
    public function divided_content(){
        $id=I('id');
        $order_status=array('0'=>'未付款','1'=>'已付款,已确认','2'=>'退款','3'=>'已收货');
        $divided_info_status=array('0'=>'未分佣','1'=>'待分佣','2'=>'已分佣');
        $map=array();
        $map['id']=$id;
        $info=M("LiveDivided")->where($map)->find();
        $info['goods_attr']=D("Common/GoodsAttr")->goods_to_attrname($info['goods_attr']);
        $this->assign($info);
        $this->assign('order_info_status',$order_status);
        $this->assign('divided_info_status',$divided_info_status);
        $this->display();
    }

    /**
     * 添加直播会员搜索
     */
    public function searchuser()
    {
        $like = I('get.like');
        if ($like) {
            $whereor['mobile'] = $like;
            $map['_complex'] = $whereor;
            $list = M('Member')->where($map)->field('id,username,status,mobile')->select();
            $result = "<option>请选择该会员</option>";
            foreach ($list as $k => $v) {
                if ($v['status'] == 1) {
                    if($v['username']) $result .= "<option value='" . $v['id'] . "'>" . $v['username'] . "</option>";
                    else $result .= "<option value='" . $v['id'] . "'>" . $v['mobile'] . "</option>";
                    
                }
            }
        }
        echo $result;
        exit;
    }

    //主播分类
    public function cate_index(){
        $name = "LiveCategory";
        $map=array();
        $map['is_delete']=0;
        $list = $this->lists($name, $map);
        $this->assign('list', $list);
        $this->display();
    }
    public function cate_insert(){
        $cmodel = D('LiveCategory');
        if (false === $cmodel->create()) {
            $this->error($cmodel->getError());
        }
        $id = $cmodel->add();
        if ($id !== false) {
            if ($_POST['isajax']) $this->assign('dialog', '1');
            $jumpUrl = $_POST['forward'] ? $_POST['forward'] : U(CONTROLLER_NAME . '/cate_index');
            $this->assign('jumpUrl', $jumpUrl);
            $this->success(L('ADD_OK'));
        } else {
            $this->error(L('ADD_ERROR') . ': ' . $cmodel->getDbError());
        }
    }
    public function cate_edit(){
        $id=I('id');
        // if (!$id) $this->error(L('PARAM_ERR'));
        $map=array();
        $map['id']=$id;
        $info = M('LiveCategory')->field(true)->where($map)->find($id);
        $this->assign('info',$info);
        $this->display();
    }
    public function cate_update(){
        $cmodel = D('LiveCategory');
        $id=I('id');
        $postdata = I('post.');
        $data = $cmodel->create($postdata);
        $jumpUrl = I('forward') ? I('forward') : U(CONTROLLER_NAME . '/cate_index');
        $where['id']=$id;
        $res=$cmodel->where($where)->save($postdata) ;
        $msg=array();
        $msg = array_merge(array('success' => L('EDIT_OK'), 'error' => L('EDIT_ERROR'), 'url' => $jumpUrl, 'ajax' => IS_AJAX), (array)$msg);
        if ($res !== false) {
            $this->success($msg['success'], $msg['url'], $msg['ajax']);
        } else {
            $this->error($msg['error'], $msg['url'], $msg['ajax']);
        }
    }
    /**
     * 删除，回收站
     * @param $is_delete 0恢复,1删除
     */
    public function cate_recycling()
    {
        $name = 'LiveCategory';
        $postdata = I('post.');
        $id = I('get.id');
        if (empty($postdata['id']) && !empty($id)) $postdata['id'][] = $id;
        $is_delete = I('is_delete');
        if (empty($postdata['id'])) {
            if ($is_delete == 1) $this->error(L('PLEASE_SELECT_DELETE_GOODS'));
            else $this->error('请选择要恢复的分类！');
        }
        $where['is_delete'] = $is_delete;
        foreach ($postdata['id'] as $key => $value) {
            $map['id'] = $value;
            $g_info = M($name)->where($map)->save($where);
        }
        if ($is_delete == 1) {
            if (isset($g_info)) {
                $this->success(L('HAVE_PUT_IN_RECYCLE'));
            } else {
                $this->error(L('DELETE_FAILED'));
            }
        } else {
            if (isset($g_info)) {
                $this->success(L('RECOVER_SUCCESS'));
            } else {
                $this->error(L('RECOVER_FAILED'));
            }
        }
    }
    //end
    //1129推流
    public function publish(){
        $postdata=I('param.');
        $id=$postdata['id'];
        if(empty($id)) $this->error('参数错误');

        //1.获取房间id
        $room_id = trim(idtoname($id,'LiveAnchor','roomnumber','id',false));
        //2.推流地址
        $live= new \Common\Vendor\QiniuLive;
        $streamKey=$room_id;
        $push_url = $live->RTMPPublishURL($streamKey);
        if(!$push_url) $this->error('推流地址获取错误');
        $this->assign('push_url',$push_url);
        $this->display();
    }

    //拉流
    public function player(){
        $postdata=I('param.');
        $id=$postdata['id'];
        if(empty($id)) $this->error('参数错误');

        //1.获取房间id
        $room_id = trim(idtoname($id,'LiveAnchor','roomnumber','id',false));
        $url = U('Home/LiveAnchor/player',array('room_id'=>$room_id));
        Header("Location:$url"); 
    }

    //禁播主播
    public function live_disabled(){
        $postdata=I('param.');
        $room_id=$postdata['room'];
        if(empty($room_id)) $this->error('参数错误');
        $live= new \Common\Vendor\QiniuLive;
        $streamKey=$room_id;

        $dtype = $postdata['dtype'];
        if($dtype==1){
            $is_disabled = $live->liveDisabled($streamKey); //禁播
            $msg = '禁播';
            $status = 3;
        }
        if($dtype==2) {
            $is_disabled = $live->liveDisabled($streamKey,0); //解除禁播
            $msg = '解除禁播';
            $status = 1;
        }
       
        if($is_disabled['error']==''){
            $this->success($msg.'成功');
            $map=$data=array();
            $map['roomnumber'] = $room_id;
            $data['status'] = $status; // 主播状态
            $is_save = M('LiveAnchor')->where($map)->save($data);
        }else $this->success($msg.'失败');
        
    }
}