<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
class DialogAction extends MemberAction
{
    public function run()
    {
        $uid = intval(S::gp('uid','G'));
        try
        {
            $member = Members::single()->getOne($uid);
        }
        catch (MemberNotExistsException $exce)
        {
            throw new iSystemException($exce->getMessage());
        }
        
        $count = $this->db()->getValue('SELECT COUNT(*) FROM '.Message::table().' WHERE (msgtoid = '.$uid.' AND msgfromid = '.$this->uid().') OR (msgtoid = '.$this->uid().' AND msgfromid = '.$uid.') AND msgfromid <> 1 AND msgtoid <> 0 AND isdelete = 0 ORDER BY mid DESC');

        $pageSize = is3GRequest() ? 10 : 5;
        $pageObj = new iPage();
        $pageObj->setPageSize($pageSize);
        $pageObj->setTotalRecord($count);
        $sql = 'SELECT * FROM '.Message::table().' AS im INNER JOIN '.MessageData::table().' AS imd ON im.did = imd.did WHERE (msgtoid = '.$uid.' AND msgfromid = '.$this->uid().') OR (msgtoid = '.$this->uid().' AND msgfromid = '.$uid.') AND msgfromid <> 1 AND msgtoid <> 0 AND im.isdelete = 0 ORDER BY mid DESC LIMIT '.$pageObj->getOffset().','.$pageObj->getPageSize();
        $result = $this->db()->setQueryString($sql)->find();
        
        $mids = array();
        if (!empty($result))
        {
            foreach ($result as $row)
            {
                if ($row['msgfromid'] == $uid && $row['isnew'])
                {
                    $mids[] = $row['mid'];
                }
            }
            if (!empty($mids))
            {
                $sql = 'UPDATE '.Message::table().' SET isnew = 0 WHERE msgfromid = '.$uid.' AND msgtoid = '.$this->uid().' AND mid IN ('.implode(',',$mids).')';
                $this->db()->query($sql);
                Message::single()->updateNewCount($this->uid());
            }
        }
        
        $this->getController()->render('dialog',array(
            	'result' => $result,
                'pageObj' => $pageObj,
                'member' => $member,
            	'uid' => $uid,
            	'suid' => $this->uid()
            )
        );
    }
}