<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
class IndexAction extends BaseAction
{
    public function run()
    {
        $mTable = Message::table();
        $mModel = Message::single();
        $newAddCondition = $allAddCondition = '';
        $unReadCount = $readCount = 0;
        
        $isReadMessage = $mModel->getIsReadGroupMessage($this->uid());
        if (!empty($isReadMessage))
        {
            $newAddCondition = ' AND mid NOT IN ('.implode(',',$isReadMessage).')';
        }
        $sql = 'SELECT mid FROM '.$mTable.' WHERE msgtoid = '.$this->uid().' AND isnew = 1 AND isdelete = 0 UNION SELECT mid FROM '.$mTable.' WHERE msgtoid=0 AND msgfromid=1'.$newAddCondition;
        $newMessage = $this->db()->setQueryString($sql)->find();
        $new = array();
        if (!empty($newMessage))
        {
            foreach ($newMessage as $item)
            {
                $new[] = $item['mid'];
            }
        }
        
        $allGroupMessage = $mModel->getGroupMessage();
        $allCroupCount = count($allGroupMessage);
        $isDeleteGroupMessage = $mModel->getIsDeleteGroupMessage($this->uid());
        $allDeleteGroupCount = count($isDeleteGroupMessage);
        $isReadGroupMessage = $mModel->getIsReadGroupMessage($this->uid());
        $allIsReadGroupCount = count($isReadGroupMessage);

        $sql = 'SELECT COUNT(*) AS num,isnew FROM '.$mTable.' WHERE msgtoid='.$this->uid().' AND isdelete = 0 GROUP BY isnew = 0';
        $result = $this->db()->setQueryString($sql)->find();
        if (!empty($result))
        {
            foreach ($result as $itme)
            {
                $itme['isnew'] ? $unReadCount = $itme['num'] : $readCount = $itme['num'];
            }
        }
        $allMeassageCount = $unReadCount + $readCount;
        $allIsReadCount = $readCount + count(array_diff($isReadGroupMessage, $isDeleteGroupMessage));

        $messageCount = $allMeassageCount + ($allCroupCount - $allDeleteGroupCount);
        $newMessageCount = count(array_diff($new,$isDeleteGroupMessage));

        $this->getController()->render('index',array(
                'messageCount' => $messageCount,
                'newMessageCount' => $newMessageCount,
                'allIsReadCount' => $allIsReadCount,
            )
        );
    }
}