<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
class IndexAction extends MemberAction
{
    public function run()
    {
        $fTable = Favorites::table();
        $bTable = Book::table();

        $uid = isset($_GET['uid']) ? S::gp('uid','G',2) : $this->uid();
        $isSelf = $uid == $this->uid() ? true : false;
        $member = $this->getMember($uid);
        $iorange = $this->iorange();
        $cbs = array();
        if (!$isSelf && $member['zstatus'] && !isGM() && !u('superbm'))
        {
            // 检查访问
            if (1 == $member['zstatus'])
            {
                if (!Friends::single()->isFriend($this->uid(), $uid))
                {
                    throw new iSystemException('本空间仅好友可以访问<br/>'.ilink('加Ta为好友&gt;&gt;', url('system', array('s'=>'member','c'=>'friend','a'=>'add','uid'=>$uid))));
                }
            }
            else if (2 == $member['zstatus'])
            {
                throw new iSystemException('此空间不对外开放');
            }
        }
        
        if (!empty($member['medals']))
        {
            $member['medals'] = iMedals::single()->getMedalsString($member['medals']);
        }
        
        if (!$isSelf)
        {
            # 处理书架
         	if ($member['bookshelf'])
         	{
        	 	$sql = "SELECT B.`bookid` AS bookid, B.`typeid`, B.`bookname`, B.`lastchapterid`, B.`lastchaptername`, B.`updatedate`, B.`author`, B.`status`
        	 			FROM `{$fTable}` AS F
        	         	INNER JOIN `{$bTable}` AS B ON B.`bookid`=F.`bid`
        	         	WHERE F.`memberid` = '$uid'
        	         	ORDER BY F.favoritesid DESC
        	         	LIMIT 5";
        	 	$bookShelfs = $this->db()->setQueryString($sql)->find();
         	}
        }
        else
        {
            /**
            // 由于session表做了分表处理，所以以后不再显示在线好友人数
            $firends = $this->db()->select(array('fuid'))->from(Friends::table())->where(array('uid'=>$uid))->find();
            if (!empty($firends))
            {
                foreach ($firends as $firend)
                {
                    $firends_id[] = $firend['fuid'];
                }
                $time = CTIME;
                $onlineCount = $this->db()->getValue('SELECT COUNT(*) FROM '.$sTable.' AS s WHERE s.uid IN ('.implode(',',$firends_id).')');
            }
            /**/
     				             
            # 找出五条阅读记录
        	$sql = "SELECT `bid`, `cid`, `sp`, B.`bookname`, B.`lastchapterid`, B.`lastchaptername`, B.`updatedate`, B.`status`
         		 	FROM `{$fTable}` AS F
                 	INNER JOIN `{$bTable}` AS B ON B.`bookid` = F.`bid`
                 	WHERE F.`memberid` = '$uid'
        		 	ORDER BY F.`createdate` DESC
        		 	LIMIT 5";
        	$query = $this->db()->query($sql);
        	while ($row = $this->db()->getArr($query))
        	{
        		$ar = '';
        		$denyKey = array('status', 'bookname', 'lastchapterid', 'lastchaptername', 'updatedate');
        	    foreach ($row as $key => $value)
        	    {
        			if (!is_null($value) && !in_array($key, $denyKey))
        	        {
        				$ar[$key] = $value;
        	        }
        	    }
        		$progressurl = url('read', $ar);
        	    $row['progressurl'] = $progressurl;
                $noRead = Chapter::single()->getNotReads($row['bid'], $row['cid']);
                $row['c'] = false === $noRead ? 0 : $noRead;
        	    $progresss[] = $row;
            }
            
            # 检查是否有推荐的书
            if (!empty($member['commends']))
            {
                $commends = explode(',', $member['commends']);
                $ccount = count($commends);
                shuffle($commends);
                $c = array_splice($commends, 0, 5);
                $sql = 'SELECT typeid,bookid,bookname FROM '.Book::table().' WHERE bookid IN ('.implode(',', $c).')';
                $cbs = $this->db()->setQueryString($sql)->find();
            }
        }
        
        # 书会职务
        $sql = 'SELECT bf.forumname,bf.bookid FROM '.BookForum::table().' AS bf INNER JOIN '.BookManagers::table().' AS bm ON bm.bookid = bf.bookid WHERE bm.status = 1 AND bm.uid = '.$uid;
        $bmRole = $this->db()->setQueryString($sql)->find();
        
        # 社区职务 TODO 暂时like一下，今后用单独表记录版主
        $sql = 'SELECT fid,name FROM '.Forums::table().' WHERE forumadmin LIKE "%,'.$uid.',%"';
        $bbsRole = $this->db()->setQueryString($sql)->find();

        $isPigFace = false;
        $face = Members::single()->getFace($uid, $member['gender']);
        if (preg_match('/pig/i', $face))
        {
            $isPigFace = true;
        }

        
        $banAction = false;
        if (!$isSelf && isGM() || u('superbm'))
        {
            $banAction = true;
        }
        
        $nextGroupCredits = false;
        if ('member' == $member['gptype'])
        {
            // 计算到下一级所需积分
            $nextGroupCredits = $member['creditslower'] - $member['credits'];
        }
        
        $expiry = '';
        if (in_array($member['groupid'],array(4,5)))
        {
            // 计算禁止到期时间
            $expiry = $member['groupexpiry'] ? (CTIME > $member['groupexpiry'] ? '刑满释放' : '还剩'.expireTime(date('Y-m-d H:i:s',$member['groupexpiry']))) : '无期徒刑';
        }
        
        // 处理当前帐号的好友动态
        $sql = 'SELECT fuid FROM '.Friends::table().' WHERE uid='.S::sqlEscape($uid);
        $result = $this->db()->setQueryString($sql)->find();
        if (!empty($result))
        {
            $fuids = array();
            foreach ($result as $item)
            {
                $fuids[] = $item['fuid'];
            }
            $feeds = iFeed::single()->getFeedsByUids($fuids);
        }
        
        if ($authorId = Authors::single()->isAuthor($uid))
        {
            // 找出原创作品
            $originalBooks = $this->db()->select(array('bookid', 'bookname', 'status', 'updatedate'))->from(Book::table())->where('authorid='.$authorId.' AND view = 1')->find();
        }

        // 最后活跃时间
        $lastActivity = Members::single()->getLastActivity($uid);
        if (false === $lastActivity)
        {
            $lastActivity = $member['lastactivity'];
        }

        $easou = new iEasou(array(array(4, '美图'), array(11, '网页'), array(11 , '新闻')));

        $this->getController()->render('index', array(
                'uid' => $uid,
                'isSelf' => $isSelf,
                'member' => $member,
                'progresss' => $progresss,
                'bookShelfs' => $bookShelfs,
                'bmRole' => $bmRole,
                'bbsRole' => $bbsRole,
                'face' => $face,
                'banAction' => $banAction,
                'nextGroupCredits' => $nextGroupCredits,
                'expiry' => $expiry,
                'feeds' => $feeds,
                'cbs' => $cbs,
                'ccount' => $ccount,
                'originalBooks' => $originalBooks,
                'lastActivity' => $lastActivity,
                'isPigFace' => $isPigFace,
                'easou' => $easou,
            )
        );
    }
}