<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
class ListAction extends BaseAction
{
    public function run()
    {
        $mModel = Message::single();
        $mTable = Message::table();
        $mdTable = MessageData::table();
        $do = S::getGP('do','G');

        !in_array($do, array('new','all')) && $this->showMessage('非法操作，请返回');
        
        $condition1 = $condition2 = '';
        $allRead = $mModel->getIsReadGroupMessage($this->uid());
        $allDelete = $mModel->getIsDeleteGroupMessage($this->uid());
            
        if ('new' == $do)
        {
            $title = '未读短信';
            $notIn = $allDelete + $allRead;
            !empty($notIn) && $condition1 = ' AND m.mid NOT IN ('.implode(',',$notIn).')';
            $condition2 = ' AND isnew = 1';
        }
        else
        {
            $title = '所有短信';
            !empty($allDelete) && $condition1 = ' AND m.mid NOT IN ('.implode(',',$allDelete).')';
        }
        
        $countField = 'mid';
        $dataField = 'm.mid,m.msgfromid,msgfrom,md.createdate,md.subject';
        
        $sql = 'SELECT '.$countField.' FROM '.$mTable.' AS m INNER JOIN '.$mdTable.' AS md ON md.did=m.did WHERE msgtoid='.$this->uid().' AND isdelete = 0'.$condition2.'
        		UNION
        		SELECT '.$countField.' FROM '.$mTable.' AS m INNER JOIN '.$mdTable.' AS md ON md.did=m.did WHERE msgtoid=0 AND msgfromid = 1'.$condition1;
        $count = count($this->db()->setQueryString($sql)->find());
        
        $pageObj = new iPage();
        $pageObj->setPageSize(10);
        $pageObj->setTotalRecord($count);
        
        $sql = 'SELECT '.$dataField.' FROM '.$mTable.' AS m INNER JOIN '.$mdTable.' AS md ON md.did=m.did WHERE msgtoid='.$this->uid().' AND isdelete = 0'.$condition2.'
        		UNION
        		SELECT '.$dataField.' FROM '.$mTable.' AS m INNER JOIN '.$mdTable.' AS md ON md.did=m.did WHERE msgtoid=0 AND msgfromid = 1 '.$condition1.' ORDER BY createdate DESC LIMIT '.$pageObj->getOffset().','.$pageObj->getPageSize();
        $message = $this->db()->setQueryString($sql)->find();
        
        $this->getController()->render('list',array(
                'title' => $title,
        		'message' => $message,
                'pageObj' => $pageObj,
            )
        );
    }
}