<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
class CronAction extends AuthorAction
{
    public function run()
    {
        $bookId = S::gp('bid','G',2);
        $chapterId = S::gp('cid','G',2);
        $book = $this->isBookOwner($bookId);
        $chapter = Chapter::single()->getOne($chapterId);
        if (empty($chapter))
        {
            $this->_showMessage('不存在的章节', 0, false);
        }
        if ($chapter['bookid'] != $book['bookid'])
        {
            $this->_showMessage('非法操作', 0, false);
        }
        if (!$book['view'])
        {
            $this->_showMessage('此书还未在站内正式发布，不能使用定时任务，如果您的书已经达到发布标准，请站内短信给'.ilink('管理员', url('system', array('s'=>'member','uid'=>1))), 0, false);
        }
        if ($chapter['display'])
        {
            $this->_showMessage('已发布的章节不能再使用定时任务', 0, false);
        }

        $yearList = array(date('Y'), date('Y', strtotime('+1 year')));
        $monthList = array(1,2,3,4,5,6,7,8,9,10,11,12);
        $dayList = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31);
        $hourList = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,0);

        if ($_POST['year'])
        {
            $year = S::gp('year', 'P', 2);
            $month = S::gp('month', 'P', 2);
            $day = S::gp('day', 'P', 2);
            $hour = S::gp('hour', 'P', 2);
            if (date('Y') == $year)
            {
                if (date('n') > $month)
                {
                    $this->_showMessage('月份不合法，必须是本月或者之后的月份');
                }
            }
            $data = array(
                S::sqlSingle(array('bid' => $bookId)),
                S::sqlSingle(array('cid' => $chapterId)),
                S::sqlSingle(array('createdate' => CDATETIME)),
                S::sqlSingle(array('year' => $year)),
                S::sqlSingle(array('month' => $month)),
                S::sqlSingle(array('day' => $day)),
                S::sqlSingle(array('hour' => $hour)),
            );
            $sql = 'REPLACE INTO '.DraftCron::table().' SET '.implode(',', $data);
            $this->db()->query($sql);

            // TODO 将续传列表内容合并到章节里去

            if ($this->getController()->isWebRequest())
            {
                $this->_showMessage('定时任务创建成功', 1);
            }
            $message[] = '定时任务创建成功';
            $message[] = '本章节将于'.implode('-', array($year,$month,$day,$hour)).'发布';
            $this->showMessage($message);
        }

        $this->getController()->render('cron', array(
                'bookId' => $bookId,
                'chapter' => $chapter,
                'yearList' => $yearList,
                'monthList' => $monthList,
                'dayList' => $dayList,
                'hourList' => $hourList,
            )
        );
    }
}
