<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
class ProgressAction extends MemberAction
{
    public function run()
    {
        $fTable = Favorites::table();
        $bTable = Book::table();
        $cTable = Chapter::table();
        $iorange = $this->iorange();
        $bNum = u('bnum');
        $bookLimit = $iorange['user']['group']['booklimit'];
        
        $sid = $iorange['user']['iorange'];
        $pageSize = isWebRequest() ? 15 : 10;
        if ('down' == $_GET['do'])
        {
            $bid = S::gp('bid', 'G', 2);
            if (1 == $_GET['confirm'])
            {
                $this->db()->delete($fTable)->where(array('memberid'=>$this->uid(),'bid'=>$bid))->q();
                Book::single()->updateFavorites($bid);
                Favorites::single()->updateBnum($this->uid());
                if ($this->getController()->isAjaxRequest())
                {
                    exit(0);
                }
                $page = S::gp('page', 'G', 2);
                $params = array('s'=>'member','c'=>'my','a'=>'progress');
                $page && $params = array_merge($params, array('page'=>$page));
                iforward(url('system', $params));
            }
            else
            {
                $message[] = '确定要删除吗？删除后将不可恢复！';
                $message[] = ilink('删除',url('system',array('s'=>'member','c'=>'my','a'=>'progress','do'=>'down','bid'=>$bid,'confirm'=>1))).'|'.ilink('取消',url('system',array('s'=>'member','c'=>'my','a'=>'progress')));
                $this->showMessage($message);
            }
        }
        
        $sort = empty($_GET['sort']) ? 'desc' : 'asc';
        $field = S::gp('f', 'G', 2) ? 'F.createdate' : 'B.updatedate';
        
        $sqlAdd = '';
        if (isset($_GET['class']) && in_array($_GET['class'],array(1,2)) && !empty($_GET['key']))
        {
            $class = S::gp('class','G',2);
            $key = S::gp('key','G');
            switch ($class)
            {
                case 1:
                    $sqlAdd = ' AND B.bookname LIKE '.S::sqlEscape('%'.$key.'%');
                    break;
                case 2:
                    $sqlAdd = ' AND B.author LIKE '.S::sqlEscape('%'.$key.'%');
                    break;
            }
        }
        
        if ($_GET['filter'])
        {
            $sqlAdd .= ' AND B.lastchapterid > F.cid';
        }
        
        $sql = 'SELECT COUNT(*) AS c FROM `'.$fTable.'` AS F
             		 INNER JOIN `'.$bTable.'` AS B ON B.`bookid` = F.`bid`
             		 WHERE F.`memberid` = '.$this->uid().' 
             		 AND (F.`cid` IS NOT NULL OR F.`sp` IS NOT NULL)'.$sqlAdd;
        $count = $this->db()->getValue($sql);
        
        $pageObj = new iPage();
        $pageObj->setTotalRecord($count);
        $pageObj->setPageSize($pageSize);
        $floor = $pageObj->getFloor();

        $sql = 'SELECT `bid`, `cid`, `sp`, B.`bookname`, B.`wlastchapterid`, B.`wlastchaptername`, 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` = '.$this->uid().'
                AND (F.`cid` IS NOT NULL OR F.`sp` IS NOT NULL)'.$sqlAdd.'
        		ORDER BY '.$field.' '.$sort.' LIMIT '.$pageObj->getOffset().','.$pageObj->getPageSize();
        $result = $this->db()->setQueryString($sql)->find();
        
        if (!empty($result))
        {
            foreach ($result as $row)
            {
                $ar = '';
                $denyKey = array('status', 'bookname', 'lastchapterid', 'lastchaptername', 'updatedate','c', 'wlastchapterid', 'wlastchaptername',);
                foreach ($row as $key => $value)
                {
                    if (!is_null($value) && !in_array($key, $denyKey))
                    {
                        $ar[$key] = $value;
                    }
                }
                $noRead = Chapter::single()->getNotReads($row['bid'], $row['cid']);
                $row['c'] = false === $noRead ? 0 : $noRead;
                $progressurl = url('read', $ar);
                $row['progressurl'] = $progressurl;

                $progresss[] = $row;
                $cids[] = $row['cid'];
            }
        
            $sql = "SELECT chapterid,chaptername FROM {$cTable} WHERE chapterid IN (".implode(',', $cids).')';
            $chapters = $this->db()->setQueryString($sql)->find();
            foreach ($progresss as &$v)
            {
                foreach ($chapters as $key => $chapter)
                {
                    if ($v['cid'] == $chapter['chapterid'])
                    {
                        $v['progresschapter'] = $chapter['chaptername'];
                        unset($chapters[$key]);
                        break;
                    }
                }
            }
        }
        
        if ($this->getController()->isAjaxRequest())
        {
            if (empty($progresss))
            {
                die('没有阅读记录');
            }
            $ajaxResult = array('');
            $ajaxResult[] = "<div id='myprogress'><li class='g1'>书名</li><li class='g2'>进度</li><li class='g3'>最新章节</li><li class='g4'>操作</li>";
            foreach ($progresss as $progress)
            {
                $ajaxResult[] = '<div class="mybid" id="bid'.$progress['bid'].'"><li class="g1">'.$this->getController()->link($progress['bookname'], $this->getController()->url('bookshow', array('bid'=>$progress['bid']))) . '[';
                if ($progress['c'])
                {
                    $ajaxResult[] = '有<span class="hasnew">'.$progress['c'].'</span>章';
                }
                else
                {
                    $ajaxResult[] = $progress['status'] ? '<span class="over">已看完</span>' : '无新章';
                }
                $ajaxResult[] = ']</li>';
                
                $ajaxResult[] = '<li class="g2">'.$this->getController()->link($progress['progresschapter'], $this->getController()->url('read', array('bid'=>$progress['bid'],'cid'=>$progress['cid']))).'</li>';
                
                $ajaxResult[] = '<li class="g3">'.$this->getController()->link($progress['wlastchaptername'], $this->getController()->url('read', array('bid'=>$progress['bid'],'cid'=>$progress['wlastchapterid']))).'</li>';
                
                $ajaxResult[] = '<li class="g4">[<a href="javascript:void(0);" onclick="deleteProgress('.$progress['bid'].');">下架</a>]</li></div>';
            }
            $pagination = $pageObj->show();
            if (!empty($pagination))
            {
                $ajaxResult[] = str_replace($pageObj->getCurrentPage(), '<strong>'.$pageObj->getCurrentPage().'</strong>', '<div class="clear"></div><div class="pagination">' . preg_replace_callback('/<a href=\"(.*?)\">(.*?)\<\/a>/is', 'autoAddClass', $pagination) . '</div>');
            }
            $ajaxResult[] = '</div>';
            die(implode('', $ajaxResult));
        }
        
        $bookshelfs = unserialize($this->db()->getValue('SELECT bookshelfs FROM '.Memberfields::table().' WHERE uid = '.$this->uid()));
        
        $this->getController()->render('progress',array(
                'progresss' => $progresss,
                'pageObj' => $pageObj,
                'floor' => $floor,
                'bookshelfs' => $bookshelfs,
                'field' => $field,
                'sort' => $sort,
                'sid' => $sid,
                'bNum' => $bNum,
                'bookLimit' => $bookLimit,
            )
        );
    }
}

function autoAddClass($matches)
{
    $page = 1;
    preg_match('/page=(\d+)/i', $matches[1], $m);
    if ($m[1])
    {
        $page = $m[1];
    }
    return '<a href="javascript:;" onclick="myProgress(event, '.$page.');">'.$matches[2].'</a>';
}