<?php

namespace Admin\Controller;
use User\Api\UserApi as UserApi;
use Admin\Event\BatchImportExcelEvent;
/**
 * 后台首页控制器
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
class ServerController extends ThinkController {
	const model_name = 'Server';

    public function lists($p=0){
        $page = intval($p);
        $page = $page ? $page : 1; //默认显示第一页数据
        $arraypage = $page; //默认显示第一页数据
        if(isset($_REQUEST['row'])) {$row = $_REQUEST['row'];}else{$row = 10;}

        if(isset($_REQUEST['show_status'])){
            $extend['show_status']=$_REQUEST['show_status'];
            unset($_REQUEST['show_status']);
        }
        if(isset($_REQUEST['server_version'])){
            $extend['server_version']=$_REQUEST['server_version'];
            unset($_REQUEST['server_version']);
        }
        if(isset($_REQUEST['timestart']) && isset($_REQUEST['timeend'])){
            $extend['start_time']  =  array('BETWEEN',array(strtotime($_REQUEST['timestart']),strtotime($_REQUEST['timeend'])+24*60*60-1));
            unset($_REQUEST['timestart']);unset($_REQUEST['timeend']);
        }elseif(isset($_REQUEST['timestart'])){
            $extend['start_time']=array('EGT',strtotime($_REQUEST['timestart']));
        }elseif(isset($_REQUEST['timeend'])){
            $extend['start_time']=array('ELT',strtotime($_REQUEST['timeend']));
        }
        if(isset($_REQUEST['start']) && isset($_REQUEST['end'])){
            $extend['start_time']  =  array('BETWEEN',array(strtotime($_REQUEST['start']),strtotime($_REQUEST['end'])+24*60*60-1));
            unset($_REQUEST['start']);unset($_REQUEST['end']);
        }
        if(isset($_REQUEST['game_name'])){
            if($_REQUEST['game_name']=='全部'){
                unset($_REQUEST['game_name']);
            }else{
                $extend['game_name']=['like', "{$_REQUEST['game_name']}%"];
                unset($_REQUEST['game_name']);
            }
        }
        if(isset($_REQUEST['server_id'])){
            $extend['server_id']=$_REQUEST['server_id'];
            unset($_REQUEST['server_id']);
        }
        if(empty($_GET['type']) || $_GET['type'] == 1) {
            $extend['developers'] = array('EQ',0);
        }else{
            $extend['developers'] = array('NEQ',0);
            $this->assign('show_status',1);
        }

        $this->checkListOrCountAuthRestMap($map,[]);

        $this->m_title = '区服列表';
        $this->assign('commonset',M('Kuaijieicon')->where(['url'=>'Server/lists','status'=>1])->find());
				
       $data =  M("Server","tab_")->field("id,game_name,server_name,server_id,show_status,start_time,server_version,developers")->where($extend)->page($page,$row)->select();
       foreach($data as $k=>&$v){
            $v["start_time"] = set_show_time($v["start_time"]);
            $v["server_version"] = get_systems_name($v["server_version"]);
       }
       $count = M("Server","tab_")->where($extend)->count("id");
       $this->assign('list_data', $data);
        $page = set_pagination($count,$row);
        if($page) {$this->assign('_page', $page);}
        $this->display();
    }

    public function add(){
    	$model = M('Model')->getByName(self::model_name);
			$this->m_title = '区服列表';
				$this->assign('commonset',M('Kuaijieicon')->where(['url'=>'Server/lists','status'=>1])->find());
				
    	parent::add($model["id"]);
    }

    public function edit($id=0){
		$id || $this->error('请选择要编辑的用户!');
		$this->m_title = '区服列表';
				$this->assign('commonset',M('Kuaijieicon')->where(['url'=>'Server/lists','status'=>1])->find());
				
		$model = M('Model')->getByName(self::model_name); /*通过Model名称获取Model完整信息*/
		parent::edit($model['id'],$id);
    }

    public function del($model = null, $ids=null){
        $model = M('Model')->getByName(self::model_name); /*通过Model名称获取Model完整信息*/
        parent::del($model["id"],$ids);
    }

    /**
     * 批量导入游戏区服区服
     */
    public function batch(){
        if(IS_POST){
            switch($_POST['batchType']){
                case 1:
                    $this->batchExcel();
                break;
                case 2:
                    $this->batchImport();
                break;
            }
        }else{
            $this->meta_title = '新增区服管理';
						
						$this->m_title = '区服列表';
				$this->assign('commonset',M('Kuaijieicon')->where(['url'=>'Server/lists','status'=>1])->find());
				
            $this->display();
        }

    }

    //批量新增
    public function batchImport(){
        $server_str = str_replace(array("\r\n", "\r", "\n"), "", I('server'));
        $server_ar1 = explode(';',$server_str);
        array_pop($server_ar1);
        $num = count($server_ar1);
				if ($num<1) {$this->error('请添加区服数据');}
        if($num > 100 ){
            $this->error('区服数量过多,最多只允许添加100个!');
        }
        $verify = ['game_id','server_name','time'];
        $server_model = D('Server');
        foreach ($server_ar1 as $key=>$value) {
            $arr = explode(',',$value);
            foreach ($arr as $k=>$v) {
                $att = explode('=',$v);
                if(in_array($att[0],$verify)){
                    switch ($att[0]){
                        case 'time' :
														$patten = '/^\d{4}-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01])(\s+(0[0-9]|1[0-9]|2[0-3])\:(0[0-9]|[1-5][0-9])(\:(0[0-9]|[1-5][0-9]))?)$/';
                            if(!strtotime($att[1]) || !preg_match($patten,$att[1])){
                                $this->error('开服时间不正确');
                            }else{
                                $time = $server[$key]['start_time'] = strtotime($att[1]);
                            }
                            break;
                        case 'game_id':
                            $game = M('Game','tab_')->where('developers = 0')->find($att[1]);
                            if(empty($game)){
                                $this->error('game_id='.$att[1].' 数据错误,请重新上传');
                            }
                            $server[$key]['game_id'] = $att[1];
                            break;
                        default:
                            $server[$key][$att[0]] = $att[1];
                    }
                }
            }
            $server[$key]['game_name'] = get_game_name($server[$key]['game_id']);
            $server[$key]['server_num'] = 0;
            $server[$key]['recommend_status'] = 1;
            $server[$key]['show_status'] = 1;
            $server[$key]['stop_status'] = 0;
            $server[$key]['server_status'] = 0;
            $server[$key]['parent_id'] = 0;
            $server[$key]['create_time'] = time();
            $version = get_sdk_version($server[$key]['game_id']);
            $server[$key]['server_version'] = empty($version) ? 0 : $version;

            if(!$server_model->create($server[$key])){
                switch ($server_model->getError()) {
                    case '区服名称不能为空':
                        $msg = '游戏ID:'.$server[$key]['game_id'].' <'.$server[$key]['server_name'].'> 区服名称不能为空';
                        break;
                    case '区服名称不能超过30个字符':
                        $msg = '游戏ID:'.$server[$key]['game_id'].' <'.$server[$key]['server_name'].'> 区服名称不能超过30个字符';
                        break;
                    case '同游戏下区服名称已存在':
												$msg = '游戏ID:'.$server[$key]['game_id'].' <'.$server[$key]['server_name'].'> 区服名称重复';
                        break;
                    case '开始时间不能为空':
                        $msg = '游戏ID:'.$server[$key]['game_id'].' <'.$server[$key]['server_name'].'> 开始时间不能为空';
                        break;
                    default:
                        $msg = "批量添加失败";
                        break;
                }
                $this->error($msg);
            }
        }
        $server = $this->array_unset_tt($server);
        $res = M('server','tab_')->addAll($server);
        if($res !== false){
            $this->success('添加成功!',U('Server/lists'));
        }else{
            $this->error('添加失败!'.M()->getError());
        }
    }

    function array_unset_tt($arr){     
        //建立一个目标数组  
        $res = array();        
        foreach ($arr as $key => $value) {     
           //查看有没有重复项  
           if($res[$key-1]['game_id'] == $value['game_id'] && $res[$key-1]['server_name'] == $value['server_name']){  
							
							$this->error("游戏ID:{$value['game_id']} <{$value['server_name']}> 游戏区服名称重复");
					 
                //有:销毁  
                //unset($arr[$key]);  
           }  
           else{  
                $res[$key] = $value;  
           }    
        } 
        return $res;  
    }

    /**
     * excel 批量导入游戏区服
     */
    public function batchExcel(){
        $excel = new BatchImportExcelEvent();
				if (empty($_FILES['fileExcel'])) {$this->ajaxReturn(["status"=>0,"info"=>'请选择文件']);exit;}
        $info = $excel->uploadExcel($_FILES['fileExcel']);
        $data = [];
        if(is_array($info)){
            $filename = './Uploads/' . $info['savepath'] . $info['savename'];
            $data = $excel->importExcel($filename);
            if(is_array($data)){
                $excel->serverDataInsert($data,U('Server/lists'));
            }else{
                $this->ajaxReturn(["status"=>0,"info"=>$data]);
            }
        }else{
            $this->ajaxReturn(["status"=>0,"info"=>$info]);
        }
        
    }
		
		
		
		/**
     * 区服状态修改
     * @author 鹿文学
     */
    public function change_status($field = null,$value=null) {
        $id = array_unique((array)I('ids', 0));
        $id = is_array($id) ? implode(',', $id) : $id;
        if (empty($id)) {
					$this->error('请选择要操作的数据!');
        }
        $map['id'] = array('in', $id);
				$servermodel = D(self::model_name);
        $server = $servermodel->where($map)->find();
        //开发者区服
        if($server['developers'] > 0){					
					$save[$field] = $value;
					$result = $servermodel->where($map)->save($save);
        }else{
					$result = $servermodel->where($map)->setField($field,$value);
        }
        $msg = "操作";
        if($result !== false){
            $this->success($msg.'成功');
        }else{
            $this->error($msg.'失败');
        }
    }
		
		
		
		
		
}