<?php
class FetchAction extends BaseAction
{
    public function run()
    {
        $bookid = trim(Yii::app()->request->getPost('bookid'));
        $spider = trim(Yii::app()->request->getPost('spider'));
        $newNum = trim(Yii::app()->request->getPost('new'));
        $listurl = trim(Yii::app()->request->getPost('listurl'));
        $detialurl = trim(Yii::app()->request->getPost('detialurl'));
        
        $collect = Collects::model()->find('bookid=:bookid',array(':bookid'=>$bookid));
        if (empty($collect))
        {
            echo '采集记录不存在，无法完成对应';
            Yii::app()->end();
        }
        
        Front::spider();
        $spiderObj = Spider::factory($detialurl, $spider);
        $spiderObj->getInfoFile();
        $listurl = $spiderObj->getChapterListUrl();
        
        $chapterurl = $spiderObj->getChapterList();
        foreach ($chapterurl as $key => $value)
        {
            if (!empty($key))
            {
                $sourceurls[] = $spiderObj->getChapterContentUrl($key);
            }
        }
        
        $sourceurlCount = count($sourceurls);
        $newUrls = array_splice($sourceurls, $sourceurlCount - $newNum);
        
        // 载入前台的Chapter类
        Front::getChapterClass();
        if (!empty($newUrls))
        {
            foreach ($newUrls as $new)
            {
                $collectObj = Front::getCollectObj($spiderObj, $bookid);
                $collectObj->setSpiderName($spider);
                $chapterContent = $collectObj->fetchChapterContent($new);
                $content = $collectObj->getChapterContent($chapterContent);
                $chapterName = $collectObj->getChapterName($chapterContent);
                if (!empty($chapterName))
                {
                    $collectLog = new Collectlog();
                    $collectLog->collectid = $collect->collectid;
                    $collectLog->sourceurl = $new;
                    $collectLog->createdate = date('Y-m-d H:i:s');
                    $collectLog->date = date('Y-m-d');
                    $collectLog->save();

                    if ($collectLog->collectlogid)
                    {
                        $content['chaptername'] = $chapterName;
                        $chapterId = Chapter::single()->create($bookid, $content);
                        
                        $collectLog->chapterid = $chapterId;
                        $collectLog->status = 1;
                        $collectLog->save();
                    }
                }
            }
        }
        
        $collect->spider = $spider;
        $collect->count = $sourceurlCount;
        $collect->listurl = $listurl;
        $collect->detialurl = $detialurl;
        $collect->save();
        
        Front::updateBooksFile($bookid);
        echo '抓取完成';
        Yii::app()->end();
    }
}