<?php

/**
 * 我的收藏
 *
 * @author Yang
 */
class FavoriteAction extends PublicAction {

    //初始化检测
    public function _initialize() {
        parent::_initialize();
        if (!isset($_SESSION['user_id']) || empty($_SESSION['user_id'])) {
            //页面跳转
            echo "<script language='javascript' type='text/javascript'>window.location.href='" . __APP__ . "/Login/index?url=" . rawurlencode(__APP__ . '/favorite/') . "'</script>";
        }
    }


    //我的收藏
    public function index() {
        $map[C('DB_PREFIX').'soft_favorites.user_id'] = $_SESSION['user_id'];
        $map['status'] = 1;
        $map['LENGTH(jumpurl)'] = 0;

        $favorite = M('soft_favorites');
        import("ORG.Util.Page"); //导入分页类

        $count = count($favorite->where($map)->join(C('DB_PREFIX').'software ON '.C('DB_PREFIX').'software.id = '.C('DB_PREFIX').'soft_favorites.soft_id')
                        ->join(C('DB_PREFIX').'comment ON '.C('DB_PREFIX').'comment.soft_id = '.C('DB_PREFIX').'soft_favorites.soft_id')
                        ->group(C('DB_PREFIX').'software.id')->select());
        $page = new Page($count, 15);
        $show = $page->show();

        $favoriteList = $favorite->field(C('DB_PREFIX').'soft_favorites.id, '.C('DB_PREFIX').'software.id AS soft_id, icon, name,'.C('DB_PREFIX').'software.time, version, ROUND(AVG('.C('DB_PREFIX').'comment.score), 1) AS score')
                        ->where($map)->join(C('DB_PREFIX').'software ON '.C('DB_PREFIX').'software.id = '.C('DB_PREFIX').'soft_favorites.soft_id')
                        ->join(C('DB_PREFIX').'comment ON '.C('DB_PREFIX').'comment.soft_id = '.C('DB_PREFIX').'soft_favorites.soft_id')
                        ->group('soft_id')->order(C('DB_PREFIX').'soft_favorites.id DESC')
                        ->limit($page->firstRow . ',' . $page->listRows)->select();

        for ($i = 0; $i < count($favoriteList); $i++) {
            $favoriteList[$i]['score'] = empty($favoriteList[$i]['score']) ? scoreToStar(0) : scoreToStar($favoriteList[$i]['score']);
        }
        //dump($favoriteList);
        $this->assign('title', '我的收藏');
        $this->assign('favoriteList', $favoriteList);
        $this->assign('page', $show);
        $this->display();
    }

    //删除收藏
    public function delfavorite() {
        $map['user_id'] = $_SESSION['user_id'];
        $map['soft_id'] = intval($_GET['id']);

        $favorite = M('soft_favorites');
        if ($favorite->where($map)->delete()) {
            $this->ajaxReturn('', '', 1);
        } else {
            $this->ajaxReturn('', '', 0);
        }
    }

}

?>
