<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * 按小说ID生成静态文件
 * @author yzxh24
 */
class CreateByIdAction extends BaseAction
{
    public function run()
    {
        echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
		echo '生成中，请稍候...';

        set_time_limit(0);
		ini_set('memory_limit', '200M');
		$bookStart = intval($_GET['start']);
		$bookEnd = intval($_GET['end']);
		$interval = empty($_GET['interval']) ? intval($_GET['interval']) : 1;
		$page = empty($_GET['page']) ? 1 : intval($_GET['page']);
		$offset = ($page - 1) * $interval;

		if (!empty($bookStart))
		{
			$condition[] = "bookid >= $bookStart";
		}

		if (!empty($bookEnd))
		{
			$condition[] = "bookid <= $bookEnd";
		}

		$criteria = new CDbCriteria();
		if (!empty($condition))
		{
			$criteria->condition = implode(' AND ', $condition);
		}

        $totalRecord = Book::model()->count($criteria);
		$totalPage = ceil($totalRecord / $interval);
		$criteria->limit  = $interval;
		$criteria->offset = $offset;

		$books = Book::model()->published()->findAll($criteria);
		if (!empty($books))
		{
			foreach ($books as $book)
			{
				$chapters = Chapter::model()->findAll("bookid=$book->bookid AND display = 1");
				if (!empty($chapters))
				{
					foreach ($chapters as $chapter)
					{
                        $bookId = $book->bookid;
                        $tid = IFileHelper::selfType($bookId);
                        $chapterId = $chapter->chapterid;
                        
                        $_GET['id'] = $bookId;
                        $_GET['tid'] = $tid;
                        $_GET['cid'] = $chapterId;
                        $_GET['html'] = 1;
                        $route = 'site/chapter/read';
                        Yii::app()->runController($route);
                        $params = Yii::app()->getParams();
                        $content = $params['chapterHtml'];
                        
                        $file = Yii::app()->params['htmlFileSavePath'] . $tid . DS . $bookId . DS . $chapterId . '.html';
                        IFileHelper::createFile($file, $content);
					}
				}
			}
		}
		if ($page == $totalPage)
		{
			echo '完成';
		}
		else
		{
			$jump = $this->getController()->createUrl('createbyid',array('page'=>$page + 1,'start'=>$bookStart,'end'=>$bookEnd,'interval'=>$interval));
			echo "<meta http-equiv='refresh' content='0;url={$jump}'>";
		}

    }
}
