<?php
// +----------------------------------------------------------------------
// | WANCMS游戏平台管理系统
// +----------------------------------------------------------------------
// | Copyright (c) 2015 http://www.wancms.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 顽皮蛋 <shf_l@163.com> <http://www.wancms.com>
// +----------------------------------------------------------------------
// | 修改时间: 2016/04/19
// +----------------------------------------------------------------------

namespace Phonegame\Controller;
use Common\Controller\AdminbaseController;
/**
 * 游戏管理控制器
 * @author 顽皮蛋 <shf_l@163.com>
 */
class IndexadminController extends AdminbaseController{

	/**
     * 游戏管理
     * @author 顽皮蛋 <shf_l@163.com>
     */
	public function index(){
        $gametype = I('gametype');
        $gamename = I('gamename');
        $plat=I('platform');
        if($plat)$map['gametype'] = $gametype;
        if($gamename)$map['gamename'] = array('like', '%'.(string)$gamename.'%');
        if($gametype)$map['gametype'] = $gametype;
        $count=M("m_game")->where($map)->count();
        $page       = new \Think\Page($count,20);//实例化分页类 传入总记录数和每页显示的记录数
        /*条件*/
        $parameter['gamename'] = $gamename;
        $parameter['gametype'] = $gametype;
        foreach($parameter as $key=>$val){
            $page->parameter[$key]   =   urlencode($val);
        }
        $show  = $page->show();// 分页显示输出
        $lists = M("m_game")
        ->where($map)
        ->order("addtime DESC")
        ->limit($page->firstRow . ',' . $page->listRows)
        ->select();
        $platform=M('m_game_platform')->where(array('status'=>1))->getField('id,name',true);
        $this->assign('lists',$lists);
        $this->assign("page", $show);
        $this->assign('platform', $platform);
        $this->assign('plat', $plat);
        $this->assign('gametype', $gametype);
        $this->assign('gamename', $gamename);
        $this->display();
    }
	/**
     * 增加游戏
     * @author 顽皮蛋 <shf_l@163.com>
     */
    public function add(){
        if(IS_POST){
            if (D("Common/MGame")->create()){
                if (D("Common/MGame")->add()!==false) {
                    $this->success("添加成功！", U("Indexadmin/index"));
                } else {
                    $this->error("添加失败！");
                }
            } else {
                $this->error(D("Common/MGame")->getError());
            }
        }else{
            $this->assign('info', '');   
            $this->display();
        }
    }
    /**
     * 修改游戏
     * @author 顽皮蛋 <shf_l@163.com>
     */
    public function edit(){
    	if(IS_POST){
            if (D("Common/MGame")->create()) {
                if (D("Common/MGame")->save()!==false) {
                    $this->success("保存成功！", U("Indexadmin/index"));
                } else {
                    $this->error("保存失败！");
                }
            } else {
                $this->error(D("Common/MGame")->getError());
            }
        }else{
            $id=  intval(I("get.id"));
            $info = M('m_game')->where(array("id"=>$id))->find(); 
            $this->assign('info', $info);   
            $this->display('add');
        }
    }
    /**
     * 删除游戏
     * @author 顽皮蛋 <shf_l@163.com>
     */
    public function del(){
    	if(isset($_POST['ids'])){
            $ids = implode(",", $_POST['ids']);
            /*判断该游戏下没有区服*/
            if (M('m_game')->where("id in ($ids)")->delete()!==false) {
                $this->success("删除成功！");
            }else{
                $this->error("删除失败！");
            }
        }else{
            $id = intval(I("get.id"));
            /*判断该游戏下没有区服*/
            if (M('m_game')->delete($id)!==false) {
                $this->success("删除成功！");
            } else {
                $this->error("删除失败！");
            }
        }
    }
    /**
     * 排序
     * @author 顽皮蛋 <shf_l@163.com>
     */
    public function listorders(){
        $status = parent::_listorders(M('m_game'));
        if ($status) {
            $this->success("排序更新成功！");
        } else {
            $this->error("排序更新失败！");
        }
    }

    /**
     * 开启、关闭
     * @author 顽皮蛋 <shf_l@163.com>
     */
    public function toggle(){
        if(isset($_POST['ids']) && $_GET["display"]){
            $ids = implode(",", $_POST['ids']);
            $data['isdisplay']=1;
            if (M('m_game')->where("id in ($ids)")->save($data)!==false) {
                $this->success("开启成功！");
            } else {
                $this->error("开启失败！");
            }
        }
        if(isset($_POST['ids']) && $_GET["hide"]){
            $ids = implode(",", $_POST['ids']);
            $data['isdisplay']=0;
            if (M('m_game')->where("id in ($ids)")->save($data)!==false) {
                $this->success("关闭成功！");
            } else {
                $this->error("关闭失败！");
            }
        }

    }

    public function hot(){
        if(isset($_POST['ids']) && $_GET["display"]){
            $ids = implode(",", $_POST['ids']);
            $data['ishot']=1;
            if (M('m_game')->where("id in ($ids)")->save($data)!==false) {
                $this->success("推荐成功！");
            } else {
                $this->error("推荐失败！");
            }
        }
        if(isset($_POST['ids']) && $_GET["hide"]){
            $ids = implode(",", $_POST['ids']);
            $data['ishot']=0;
            if (M('m_game')->where("id in ($ids)")->save($data)!==false) {
                $this->success("不推荐成功！");
            } else {
                $this->error("不推荐失败！");
            }
        }

    }

    /* ajax获取游戏区服 */
    public function getSever($gid, $sid) {
        $server = M ( 'server' );
        $mar ['gid'] = $gid;
        // 获取栏目option
        $list = $server->where ( $mar )->order('sid asc')->select ();
        $j = '';
        $op = " <option  value=''>请选择区服</option>";
        for($i = 0; $i < count ( $list ); $i ++) {
            $str = '';
            if($list [$i] ['zsid']!=$list [$i] ['sid'])$str = '-->'.$list [$i] ['zsid'];
            if ($sid != '' & $sid == $list [$i] ['sid']) {
                $op .= "<option value=" . $list [$i] ['sid'] . " selected>" . $list [$i] ['servername'].$str. "</option>";
            } else {
                $op .= "<option value=" . $list [$i] ['sid'] . " >" . $list [$i] ['servername'].$str. "</option>";
            }
            $j ++;
        }
        $this->ajaxReturn($op);
    }


    public function getqrcode(){
        $url=$_POST['url']; 
        $filename=time().".png";
        if($this->qrcode($url,$filename,false,false,8,'L',2,false)){
            $temp['filename']=$filename;
            $this->ajaxReturn($temp);

        }

    }

 /**
  *
  * function qrcode(){
  *     $filename='qrcode.png';
  *     $logo=SITE_PATH."\Public\Home\images\logo_80.png";
  *     qrcode('http://www.dellidc.com',$filename,false,$logo,8,'L',2,true);
  * }
  *
  * @param $data 二维码包含的文字内容
  * @param $filename 保存二维码输出的文件名称，*.png
  * @param bool $picPath 二维码输出的路径
  * @param bool $logo 二维码中包含的LOGO图片路径
  * @param string $size 二维码的大小
  * @param string $level 二维码编码纠错级别：L、M、Q、H
  * @param int $padding 二维码边框的间距
  * @param bool $saveandprint 是否保存到文件并在浏览器直接输出，true:同时保存和输出，false:只保存文件
  * return string
  */
 function qrcode($data,$filename,$picPath=false,$logo=false,$size='4',$level='L',$padding=2,$saveandprint=false){
      vendor("phpqrcode.phpqrcode");//引入工具包
     // 下面注释了把二维码图片保存到本地的代码,如果要保存图片,用$fileName替换第二个参数false
     $path = $picPath?$picPath:SITE_PATH."data/upload/qrcode"; //图片输出路径
     mkdir($path);
     //在二维码上面添加LOGO
     $QRcode = new \QRcode;
     if(empty($logo) || $logo=== false) { //不包含LOGO
       if ($filename==false) {
             $QRcode->png($data, false, $level, $size, $padding, $saveandprint); //直接输出到浏览器，不含LOGO
         }else{
             $filename=$path.'/'.$filename; //合成路径
             $QRcode->png($data, $filename, $level, $size, $padding, $saveandprint); //直接输出到浏览器，不含LOGO
         }
     }else { //包含LOGO
       if ($filename==false){
             //$filename=tempnam('','').'.png';//生成临时文件
        die('参数错误');
    }else {
             //生成二维码,保存到文件
             $filename = $path . '\\' . $filename; //合成路径
         }
         $QRcode->png($data, $filename, $level, $size, $padding);
         $QR = imagecreatefromstring(file_get_contents($filename));
         $logo = imagecreatefromstring(file_get_contents($logo));
         $QR_width = imagesx($QR);
         $QR_height = imagesy($QR);
         $logo_width = imagesx($logo);
         $logo_height = imagesy($logo);
         $logo_qr_width = $QR_width / 5;
         $scale = $logo_width / $logo_qr_width;
         $logo_qr_height = $logo_height / $scale;
         $from_width = ($QR_width - $logo_qr_width) / 2;
         imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height);
         if ($filename === false) {
           Header("Content-type: image/png");
           imagepng($QR);
       } else {
           if ($saveandprint === true) {
               imagepng($QR, $filename);
                 header("Content-type: image/png");//输出到浏览器
                 imagepng($QR);
             } else {
               imagepng($QR, $filename);
           }
       }
   }
   return $filename;
}
/*
*同步合作平台游戏数据
*/
public function update(){
    $platform=I('platform1');
    $page=I('page');
    $pagesize=I('pagesize');
    if(empty($platform))$this->error('请选择平台');
    if(empty($page))$page=1;
    if(empty($pagesize))$pagesize=20;
    if($platform==2){
        $temp=M('m_game_platform')->where(array('id'=>$platform))->find();
        $from=$temp['channel_id'];
        $type="2";
        $key=$temp['key'];
        $num= $pagesize;
        $start=$page;
        $ttt="from={$from}&num={$num}&page={$page}&pagesize={$pagesize}&start={$start}&type={$type}{$key}";
        $sign =strtolower(md5($ttt));
        $url="http://api.np.mobilem.360.cn/app/cpsgames?from={$from}&num={$num}&page={$page}&pagesize={$pagesize}&start={$start}&type={$type}&sign={$sign}";
       // $url="http://api.np.mobilem.360.cn/app/cpsgames?from={$from}&type={$type}&page={$page}&sign={$sign}";
        //请求360获得数据
        $aa = file_get_contents($url);
        $res=json_decode($aa,true);
        //返回数据并存入数据库
        if(isset($res['errno'])){
            $this->error('同步失败');
        }else{
            foreach ($res['items'] as $key => $value) {
                $map['platform_id']=$value['id'];
                $map['pic1']=$value['iconUrl'];
                $pic=explode(",",$value['screenshotsUrl']);
                $map['pic2']=$pic[0]?$pic[0]:"";
                $map['pic3']=$pic[1]?$pic[1]:"";
                $map['pic4']=$pic[2]?$pic[2]:"";
                if(strpos($value['categoryName'],"益智")||strpos($value['categoryName'],"休闲")){
                    $map['gametype']=1;
                }elseif(strpos($value['categoryName'],"网络")){
                    $map['gametype']=2;
                }elseif(strpos($value['categoryName'],"体育")||strpos($value['categoryName'],"竞速")||strpos($value['categoryName'],"竞技")){
                    $map['gametype']=3;
                }elseif(strpos($value['categoryName'],"角色")||strpos($value['categoryName'],"扮演")){
                    $map['gametype']=4;
                }elseif(strpos($value['categoryName'],"飞行")||strpos($value['categoryName'],"射击")){
                    $map['gametype']=5;
                }elseif(strpos($value['categoryName'],"策略")||strpos($value['categoryName'],"经营")){
                    $map['gametype']=6;
                }elseif(strpos($value['categoryName'],"卡片")||strpos($value['categoryName'],"棋牌")){
                    $map['gametype']=7;
                }elseif(strpos($value['categoryName'],"动作")||strpos($value['categoryName'],"冒险")){
                    $map['gametype']=8;
                }else{
                    $map['gametype']=9;
                }
                $map['platform']=$platform;
                $map['android_version']=$value['versionName'];
                $map['gamename']=$value['name'];
                $map['content']=$value['description'];
                $map['downloadnum']=$value['downloadTimes'];
                $map['addtime']=time();
                $map['updatetime']=$value['updateTime'];
                $map['language']=1;
                $map['update_info']=$value['updateInfo'];
                $map['model']=$value['priceInfo'];
                $map['android_url']=$value['downloadUrl'];
                $filename=$value['name'].$value['id'].".png";
                $this->qrcode($value['downloadUrl'],$filename,false,false,8,'L',2,false);
                $map['android_url_image']="/data/upload/qrcode/".$filename;
                $map['gamesize']=round($value['apkSize']/1024/1024,2)."MB";
                if(M('m_game')->where(array('platform_id'=>$value['id']))->find()){
                    M('m_game')->where(array('platform_id'=>$value['id']))->save($map);
                }else{
                    $map['isdisplay']=1;
                    $map['ishot']=0;
                    $map['grade']=5;
                    M('m_game')->add($map);
                }
            }
           $this->success('更新成功！');
        }
    }
}


}