<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
require_once 'init.php';

$allowMonth = array(6,8,10,12,2,4);

//if (date('d') == '01' && in_array(date('n'), $allowMonth))
//{
    $newBookBMs = array();
    $month = date("Y-m" , strtotime("-1 month" , strtotime(date('Y-m-d'))));
    //$month = '2010-04';
    $date = date('Y-m-d H:i:s');
    $denyUpdateBookIds = array(13089);

    $sql = 'SELECT id,uid,username,bookid FROM ' . BookVote::table() . " WHERE issuper = 0 AND FROM_UNIXTIME(createdate,'%Y-%m') = '$month' AND voterids IS NOT NULL";
    $votes = $db->setQueryString($sql)->find();
    if (!empty($votes))
    {
        foreach ($votes as $vote)
        {
            $bookid = $vote['bookid'];
            $voteid = $vote['id'];
            
            $sql = 'SELECT COUNT(1) FROM '.BookMembers::table().' WHERE bookid = ' . $bookid;
            $count = $db->getValue($sql);
            $num = getNum($count);
            if ($num == 0)
            {
                continue;
            }

            $sql = 'SELECT votes,`option` FROM ' . BookVote::optionTable().' WHERE voteid=' . $voteid .'  ORDER BY votes DESC LIMIT ' . $num;
            $result = $db->setQueryString($sql)->find();
            if (!empty($result))
            {
                foreach ($result as $row)
                {
                    if ($row['votes'] < 1)
                    {
                        continue;
                    }
                    preg_match('/\[UID:(\d+)\]/i', $row['option'], $user);
                    if ($user[1])
                    {
                        $newBookBMs[$bookid][$user[1]]['votes'] = $row['votes'];
                    }
                }
            }
        }
    }

    $sql = 'SELECT bookid FROM '.Book::table().' WHERE `type` = 2';
    $books = $db->setQueryString($sql)->find();
    if (!empty($books))
    {
        foreach ($books as $book)
        {
            $denyUpdateBookIds[] = $book['bookid'];
        }
    }

    $sql = "UPDATE ".BookManagers::table()." SET `status` = 2, updatedate = '$date' WHERE bookid NOT IN (" . implode(',', $denyUpdateBookIds) . ')';
    $db->query($sql);

    foreach ($newBookBMs as $id =>$newBookBM)
    {
        $bookInfo = getBookInfo($id);
        foreach ($newBookBM as $uid => $bm)
        {
            $sql = 'SELECT COUNT(1) FROM '.BookManagers::table().' WHERE uid=' . $uid . ' AND bookid = ' . $id;
            $count = $db->getValue($sql);
            if (!empty($count))
            {
                $sql = "UPDATE ".BookManagers::table()." SET `status` =1,updatedate = '$date' WHERE uid = " . $uid . ' AND bookid = ' . $id;
                $db->query($sql);
            }
            else
            {
                $userName = userName($uid);
                if (empty($userName))
                {
                    continue;
                }
                $data = array(
                    'bookid' => $id,
                    'uid' => $uid,
                    'username' => mysql_real_escape_string($userName),
                    'createdate' => $date,
                    'status' => 1,
                    'remarks' => '新一届书管',
                );
                $db->insert(BookManagers::table())->value($data)->q();
            }

            $subject = '[系统消息]书会选举结果';
            $message = '恭喜您在《' . $bookInfo['bookname'] . '》书会选举中获得'.$bm['votes'].'票，成为该书会新一届的书管';
            $did = MessageData::single()->create($subject,$message);
            Message::single()->send($did,1,'admin',$uid);
            updateBookManage($id);
        }
    }
//}


function getNum($count)
{
    if ($count <= 2)
    {
        $num = 0;
    }
    else if ($count > 2 && $count <= 10)
    {
        $num = 2;
    }
    else if ($count > 10 && $count <= 200)
    {
        $num = 3;
    }
    else if ($count > 200)
    {
        $num = 4;
    }

    return $num;
}