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

/**
 * 按时间生成章节静态文件
 * @author yzxh24
 */
class CreateByTimeAction 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');
        $start = $_GET['createdate_start'];
        $end = $_GET['createdate_end'];
        $id = intval($_GET['bookid']);
        $interval = isset($_GET['interval']) ? intval($_GET['interval']) : 10;
        $page = empty($_GET['page']) ? 1 : intval($_GET['page']);
        $bookId = $_GET['bookid'];

        $criteria = new CDbCriteria();
        if (!empty($start))
        {
            $criteria->addCondition("createdate>='$start'");
        }
        if (!empty($end))
        {
            $criteria->addCondition("createdate<='$end'");
        }
        if (!empty($bookId))
        {
            $criteria->addCondition("bookid=$bookId");
        }

        $totalRecord = Chapter::model()->published()->count($criteria);
        $totalPage = ceil($totalRecord / $interval);
        $offset = ($page - 1) * $interval;

        $criteria->limit = $interval;
        $criteria->offset = $offset;

        $chapters = Chapter::model()->published()->findAll($criteria);
        if (!empty($chapters))
        {
            foreach ($chapters as $chapter)
            {
                $bookId = $chapter->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('createbytime',array('page'=>$page + 1,'createdate_start'=>$start,'createdate_end'=>$end,'interval'=>$interval,'bookid'=>$bookId));
			echo "<meta http-equiv='refresh' content='0;url={$jump}'>";
        }
    }
}