<?php

/**
 * 本类放置Home分组中公共操作类
 *
 * @author 杨金球
 */
class PublicAction extends Action {

    public function _initialize() {
        //dump($_COOKIE);
        $this->getSetting();
        $this->getbpiinfo();
        $this->autologin();
        $this->headerClass();
    }

//自动登录
    private function autologin() {
        if (C('BIND_BBS')) {
			if (isset($_COOKIE[C('BBS_COOKIE') . 'bpi_auth']) && !empty($_COOKIE[C('BBS_COOKIE') . 'bpi_auth'])) {
                Vendor('Ucenter.UcApi');  //载入UcApi扩展
                $userMsg = explode("\t", uc_authcode($_COOKIE[C('BBS_COOKIE') . 'bpi_auth'], 'DECODE', C('AUTH_KEY'))); //得到加了密的password和uid
                $map['bbs_id'] = $userMsg[0];
                if (!isset($_SESSION['user_id']) || empty($_SESSION['user_id']) || $map['bbs_id'] != $_SESSION['bbs_id']) {
                    $user = M('user');
                    if ($user->where($map)->find()) {
                        $_SESSION['user_id'] = $user->id;
                        $_SESSION['username'] = $user->name;
                        $_SESSION['user_status'] = $user->user_status;
                        $_SESSION['bbs_id'] = $user->bbs_id;
                    } else {
                        unset($_SESSION['user_id'], $_SESSION['username'],  $_SESSION['user_status'],  $_SESSION['bbs_id']);
                        //自动激活
                        $userInfo = uc_get_user($userMsg[0], 1);
                        //dump('激活' . $userInfo);
                        $arg['name'] = $userInfo[1];
                        $arg['email'] = $userInfo[2];
                        $arg['bbs_id'] = $userInfo[0];
                        $arg['pwd'] = md5(date('YmdHis'));
                        $arg['reg_date'] = time();
                        if (!$user->where('name = ' . $arg['name'])->find()) {
                            $userID = $user->add($arg);
                            $_SESSION['user_id'] = $userID;
                            $_SESSION['username'] = $userInfo[1];
                            $_SESSION['user_status'] = 1;
                            $_SESSION['bbs_id'] = $userInfo[0];
                        }
                    }
                }
            }
        }
    }

    //获取网站相关设置
    private function getSetting() {
        $setting = M('setting');
        $settingInfo = $setting->select();
        $set = array();
        foreach ($settingInfo as $val) {
            $set[$val['name']] = $val['data'];
        }
        $this->setting = $set;
        $this->assign('set', $set);
    }

    //获取产品相关设置
    private function getbpiinfo() {
        $bpiinfo = markerinfo();
        $this->assign('bpiinfo', $bpiinfo);
    }

    //给头部添加样式
    //通过对id的不同标志用户在哪个module类中，在导航栏中友好显示CSS样式
    private function headerClass() {
        switch (strtolower(MODULE_NAME)) {
            case 'index' : $id = 1;
                break;
            case 'app' : $id = 2;
                break;
            case 'game' : $id = 3;
                break;
            case 'subject' : $id = 4;
                break;
            case 'develop' : $id = 5;
                break;
            case 'favorite' : $id = 6;
                break;
            default : $id = 1;
        }
        $this->assign('headerid', $id);
    }

//返回热门应用和热门游戏数据
    public function hot() {
        $status = C('DB_PREFIX') . 'software.status';
        $map[$status] = 1;
        $map['menu_id'] = C('HOME_APPLY_ID');
        $map['jumpurl'] = 0;

		$soft = new Model();
        $app_list = S('app_list');
        if (empty($app_list)) {

			$app_list = $soft->query("SELECT B.id,B.icon,B.jumpurl,SUBSTR(B.name, '1',6) AS name,B.hits FROM ".C('DB_PREFIX')."software B LEFT JOIN ".C('DB_PREFIX')."soft_belong A ON B.id=A.soft_id where B.status='1' AND A.menu_id='$map[menu_id]' AND B.jumpurl='0' GROUP BY A.soft_id ORDER BY B.hits DESC LIMIT 0,10");

            S('app_list', $app_list, 86400); //缓存24小时
        }



        $map['menu_id'] = C('HOME_GAMEACTION_ID');

        $game_list = S('game_list');
        if (empty($game_list)) {
            $game_list = $soft->query("SELECT B.id,B.icon,B.jumpurl,SUBSTR(B.name, '1',6) AS name,B.hits FROM ".C('DB_PREFIX')."software B LEFT JOIN ".C('DB_PREFIX')."soft_belong A ON B.id=A.soft_id where B.status='1' AND A.menu_id='$map[menu_id]' AND B.jumpurl='0' GROUP BY A.soft_id ORDER BY B.hits DESC LIMIT 0,10");
            S('game_list', $game_list, 86400); //缓存24小时
        }

        $this->assign('hot_app_list', $app_list);
        $this->assign('hot_game_list', $game_list);
        //dump($app_list);
        // dump($game_list);
    }

//分类列表(包含应用分类，游戏分类, 专题列表)
    public function sort_list() {
        $map = 'pid IN (' . C('HOME_APPLY_ID') . ',' . C('HOME_GAMEACTION_ID') . ',' . C('HOME_CUSTOMACTION_ID') . ')  AND  status = 1 ';

        $model = new Model();

        $menu_list = F('List/menu_list');
        if (!$menu_list) {
            $menu_list = $model->query('SELECT id, name, pid, count, icon
                                        FROM `' . C('DB_PREFIX') . 'menu`
                                        LEFT JOIN (SELECT menu_child_id, count(`menu_child_id`) as count
                                                   FROM `' . C('DB_PREFIX') . 'soft_belong`
                                                   LEFT JOIN ' . C('DB_PREFIX') . 'software ON ' . C('DB_PREFIX') . 'software.id = ' . C('DB_PREFIX') . 'soft_belong.soft_id
                                                   WHERE STATUS = 1
                                                   GROUP BY menu_child_id
                                        )AS TMP ON TMP.menu_child_id = ' . C('DB_PREFIX') . 'menu.id WHERE ' . $map);

            F('List/menu_list', $menu_list);
        }
        $this->assign('sort_menu_list', $menu_list);
//dump($menu_list);
    }

//下载排行榜（包含日，周，月）
    /**
     * 选取出本日，本周，本月下载排行榜并返回总下载数量
     */
    public function download_rank_list() {
        $down = M('download');
        $day_list = $this->getDownloadRankSortList('DATE_FORMAT(NOW(),"%Y-%m-%d 00:00:00")', '$day_list', 14400);
        $week_list = $this->getDownloadRankSortList('DATE_SUB(DATE_FORMAT(NOW(),"%Y-%m-%d %H:%i:%s"),INTERVAL 7 DAY)', '$week_list', 86400);
        $month_list = $this->getDownloadRankSortList('DATE_FORMAT(NOW(),"%Y-%m-1 00:00:00")', '$month_list', 604800);

        $this->assign('download_day_list', $day_list);
        $this->assign('download_week_list', $week_list);
        $this->assign('download_month_list', $month_list);
    }

    /**
     *  软件列表
     *  针对（应用软件， 游戏软件）
     * @param type $map 搜索条件
     * @param type $order 排序字段
     * @param type $sortby 排序规则
     *  @param type $pageCount 分页数量(设大的话表示不分页)
     * 默认下载量排行降序
     *
     */
    public function software_list($map, $order = 'down', $sortby = 'desc', $pageCount = '10') {

		$soft = M('soft_belong');
        import("ORG.Util.Page");    //导入分页类
		$num = new Model();

		if($map['menu_child_id']){
			$nsql = "AND A.menu_child_id='$map[menu_child_id]'";
		}else {
			$nsql = "AND A.menu_id='$map[menu_id]' ";
		}

		$numdb = $num->query("SELECT count(`soft_id`) as num FROM ".C('DB_PREFIX')."soft_belong A Left Join ".C('DB_PREFIX')."software B ON A.soft_id=B.id where B.status='$map[status]' $nsql AND B.jumpurl='0'");

		$count = $numdb['0']['num'];   //总记录数
        $page = new Page($count, $pageCount);
        $page->setConfig('theme', '%totalRow% %header% %nowPage%/%totalPage% 页 %upPage%  %linkPage%  %downPage% %nextPage%'); //自定义分页显示
        $show = $page->show();

        $soft_list = $num->query("SELECT B.id,B.name,B.version,B.mobile_name,B.time,B.icon,B.suitsdk,SUBSTR(B.explain, '1',60) AS b_explain,B.hits FROM ".C('DB_PREFIX')."software B LEFT JOIN ".C('DB_PREFIX')."soft_belong A ON B.id=A.soft_id where B.status='$map[status]' $nsql AND B.jumpurl='0' GROUP BY B.id ORDER BY B.time desc LIMIT $page->firstRow,$page->listRows ");

		for ($i = 0; $i < count($soft_list); $i++) {
            $soft_list[$i]['time'] = date("Y-m-d",$soft_list[$i]['time']);
        }

        $this->assign('page', $show);
        $this->assign('soft_list', $soft_list);
        return;
    }


	/**
     *  我的软件列表
     *  针对（应用软件， 游戏软件）
     * @param type $map 搜索条件
     * @param type $order 排序字段
     * @param type $sortby 排序规则
     *  @param type $pageCount 分页数量(设大的话表示不分页)
     * 默认下载量排行降序
     *
     */
    public function my_software_list($map, $order = 'down', $sortby = 'desc', $pageCount = '10') {
        $soft = M('software');

        import("ORG.Util.Page");    //导入分页类
        $count = $soft->where($map)->count();   //总记录数
        $page = new Page($count, $pageCount);
        $page->setConfig('theme', '%totalRow% %header% %nowPage%/%totalPage% 页 %upPage%  %linkPage%  %downPage% %nextPage%'); //自定义分页显示
        $show = $page->show();




		$soft_list = $soft->field(C('DB_PREFIX') .'software.id, icon, name, mobile_name, version, '.C('DB_PREFIX').'software.time, charge, status, recommend ,
                                   COUNT('.C('DB_PREFIX').'download.soft_id) AS down,  TMP.comment')
                        ->join(C('DB_PREFIX').'download ON '.C('DB_PREFIX').'software.id = '.C('DB_PREFIX').'download.soft_id')
                        ->join('(SELECT soft_id, COUNT(soft_id) AS comment FROM '.C('DB_PREFIX').'comment WHERE 1 GROUP BY soft_id)AS TMP  ON '.C('DB_PREFIX').'software.id = TMP.soft_id')
                        ->where($map)->group(C('DB_PREFIX').'software.id')->order($order)->limit($page->firstRow . ',' . $page->listRows)->select();




        //echo $soft->getLastSql();
        for ($i = 0; $i < count($soft_list); $i++) {
            $soft_list[$i]['score'] = empty($soft_list[$i]['score']) ? scoreToStar(0) : scoreToStar($soft_list[$i]['score']); //转换评分为图片显示
        }
        //dump($soft_list);
        $this->assign('page', $show);
        $this->assign('soft_list', $soft_list);
        return;
    }


	/**
     *  待审核新版列表
     *
     */
    public function news_soft_list() {
        $map['status'] = 0;
		$order = 'id DESC';
		$soft = M('software_temp');
        import("ORG.Util.Page"); //导入分页类

        $count = $soft->where($map)->count();
        $page = new Page($count, 15);
        $show = $page->show();

        $soft_list = $soft->field()->where($map)->order($order)->limit($page->firstRow . ',' . $page->listRows)->select();

		$this->assign('page', $show);
        $this->assign('news_soft_list', $soft_list);
        return;
    }

    /**
      +-------------------------------------------------------
     * 根据周期,计算相应周期内软件的总下载排行，并返回列表
      +-------------------------------------------------------
     * @access private
      +-------------------------------------------------------
     * @param string $map 查找条件
     * @param string $cycleListName 周期列表名称
     * @param int $cacheTime 缓存保存时间，单位：s
      +-------------------------------------------------------
     * @return array $cycleRankList 周期内软件总下载排行列表
      +-------------------------------------------------------
     */
    private function getDownloadRankSortList($map, $cycleListName, $cacheTime, $order = 'down2 DESC', $limit = '0,10') {
        $map = C('DB_PREFIX') . 'software.status = 1 AND LENGTH(jumpurl) AND ' . C('DB_PREFIX') . 'download.time > ' . $map;
        $down = M('download');
        $downloadSortListInCycle = S("$cycleListName");
        if (empty($downloadSortListInCycle)) {
            $downloadSortListInCycle = $down->field(C('DB_PREFIX') . 'download.soft_id AS id, name, icon, jumpurl, count(' . C('DB_PREFIX') . 'download.soft_id) AS down2 , TMP.down')
                            ->join(C('DB_PREFIX') . 'software ON ' . C('DB_PREFIX') . 'software.id = ' . C('DB_PREFIX') . 'download.soft_id')
                            ->join('(SELECT soft_id, COUNT(soft_id) AS down FROM `' . C('DB_PREFIX') . 'download`  GROUP BY soft_id ) AS TMP ON TMP.soft_id = ' . C('DB_PREFIX') . 'download.soft_id')
                            ->where($map)->group(C('DB_PREFIX') . 'download.soft_id')->order($order)->limit($limit)->select();

            //当数组长度不足10时，输出排名前10的软件
            if (count($downloadSortListInCycle) < 10) {
                $downloadSortListInCycle = $down->field('soft_id AS id, count(soft_id) AS down, name, icon, jumpurl')
                                ->join(C('DB_PREFIX') . 'software ON ' . C('DB_PREFIX') . 'software.id = ' . C('DB_PREFIX') . 'download.soft_id')
                                ->where('status = 1 AND LENGTH(jumpurl) = 0')->group('soft_id')->order('down DESC')->limit('0, 10')->select();
            }

            S('$cycleListName', $downloadSortListInCycle, $cacheTime);
        }
        return $downloadSortListInCycle;
    }



	//获取软件类别下拉列表以及第一个类别中的子类别列表(下拉列表)
    public function get_menu() {
        $menu = M('menu');

        $map['extend'] = 1; //确保此类别是支持自动扩展的

        $menu_list = $menu->field('id, name')->where($map)->select(); //获取父类别

        if ($menu_list) {
            $arg['pid'] = $menu_list[0]['id']; //获取第一个父类别下的子类别列表

            $menu_child_list = $menu->field('id, name')->where($arg)->select();

            $count = count($menu_list);
            $menu_msg = '';

            for ($i = 0; $i < $count; $i++) {//转换为HTML语句
				if($menu_list[$i]['id'] != '4'){
					$menu_msg .= "<option value=" . $menu_list[$i]['id'] . ">" . $menu_list[$i]['name'] . "</option>";
				}
            }

            $count = count($menu_child_list);
            $child = '';

            for ($i = 0; $i < $count; $i++) {//转换为HTML语句
                $child .= "<option value=" . $menu_child_list[$i]['id'] . ">" . $menu_child_list[$i]['name'] . "</option>";
            }

            $this->assign('menu', $menu_msg);
            $this->assign('child', $child);
        }
    }

    //通过选取父类别的下拉列表AJAX加载子类别
    public function get_child_menu() {
        $map['pid'] = $_GET['pid'];

        $menu = M('menu');

        $menu_child = $menu->field('id, name')->where($map)->select();

        $count = count($menu_child);
        $menu_child_list = '';

        for ($i = 0; $i < $count; $i++) {
            $menu_child_list .= "<option value=" . $menu_child[$i]['id'] . ">" . $menu_child[$i]['name'] . "</option>";
        }

        $this->ajaxReturn('', $menu_child_list, 1);
    }

    //获取镜像列表
    public function get_passageway() {
        $map['status'] = 1;

        $way = M('passageway');

        $way_list = $way->where($map)->order('type DESC')->select();

        $this->assign('way_list', $way_list);
    }


	/**
     *
     * 文件上传类
     * @param int 	     最大文件大小 单位Byte
     * @param array   允许的文件后缀，数组表示
     * @param url 	     存储路径
     * @param varchar 图片文件压缩后图片名前缀
     * @param int 	     图片最大宽度
     * @param int     图片最大高度
     */
    public function upload($size, $ext, $path, $name, $maxwidth, $maxheight, $rule = true) {
        //导入上传类
        import("ORG.Net.UploadFile");
        //实例化上传类
        $upload = new UploadFile();
        $upload->maxSize = $size; // 设置附件上传大小
        $upload->allowExts = $ext; // 设置附件上传类型
        $upload->savePath = $path; // 设置附件上传目录
        if ($rule) { //文件保存规则
            $upload->saveRule = 'time';
        }
        $upload->uploadReplace = false; //存在同名文件是否覆盖
        $upload->thumb = true;   //是否进行缩略图处理
        $upload->thumbPrefix = $name; //保存时文件名前缀
        $upload->thumbMaxWidth = $maxwidth; //最大宽度
        $upload->thumbMaxHeight = $maxheight; //最大高度
        $upload->thumbRemoveOrigin = true; //是否删除原图

        if (!$upload->upload()) {
            $info[0] = 0;
            $info[1] = $upload->getErrorMsg();
            return $info; //上传失败时返回错误信息
        } else {
            $info = $upload->getUploadFileInfo();
            return $info; //上传成功时返回文件信息
        }
    }



}
?>


