<?php

/**
 * MainController
 * Feel free to delete the methods and replace them with your own code.
 *
 * @author JieRen
 */
class AdminController extends DooController {
    private $cashlimit = 100; // 充值金额奖励底限
    private $perlimit = 0.05; // 奖励百分比
    private $salelimit = 0.2; // 销售人员提成
    public $data;

    /**
     * 	构造函数
     */
    function __construct() {
        session_start();
        $this->data['rootUrl'] = Doo::conf()->APP_URL;
    }

    /**
     * 	构造函数
     */
    function main() {
        if (empty($_SESSION['main'])) {
            return Doo::conf()->APP_URL . 'm';
        }
        Doo::loadModel('pay');
        $pay = new Pay();
        $unpaycount = $pay->count(array('where' => 'status="unpay" or status="waitting"', 'asArray' => TRUE));
        $this->data['unpaycount'] = $unpaycount;

        $thistime = time();
        $day = date('Y-m-d',$thistime);

        $today = strtotime($day);
        $yesterday = $today-86400;

//        Doo::loadModel('users');
//        $users = new Users();
        //已激活用户
        $todaysql='SELECT count(*) as count FROM `zh_users` left join `zh_users_switch` on `zh_users`.id=`zh_users_switch`.uid WHERE `regdate` between '. $today .' and '. $thistime.' and (`mobile`!="" or `actime`!=0)';
        $todayquery = Doo::db ()->query ( $todaysql );
        $todayuseraddnum = $todayquery->fetch();

        $yesterdaysql = 'SELECT count(*) as count FROM `zh_users` left join `zh_users_switch` on `zh_users`.id=`zh_users_switch`.uid WHERE `regdate` between '. $yesterday .' and '. $today.' and (`mobile`!="" or `actime`!=0)';
        $yesterdayquery = Doo::db ()->query ( $yesterdaysql );
        $yesterdayuseraddnum = $yesterdayquery->fetch();
        $this->data['tuaddnum'] = $todayuseraddnum['count'];
        $this->data['yuaddnum'] = $yesterdayuseraddnum['count'];

        //获取最近的12个月激活用户人数
        $monthstr = $muaddnumstr = array();
        $monthday = $thistime;
        for($i = 1; $i <= 12; $i++){
            $thismonth = date('m',$monthday);
            $thismonthday = intval($thismonth) >= 10 ? $thismonth.'月' : intval($thismonth).'月';
            array_unshift($monthstr,$thismonthday);

            $monthday = date('Y-m-d',$monthday);
            $endmonth = date('Y-m-01',strtotime("$monthday + 1 month"));
            $startmonth = date('Y-m-01',strtotime("$monthday - 1 month"));

            $monthsql = 'SELECT count(*) as count FROM `zh_users` left join `zh_users_switch` on `zh_users`.id=`zh_users_switch`.uid WHERE `regdate` between '. strtotime($startmonth) .' and '. strtotime($endmonth) .' and (`mobile`!="" or `actime`!=0)';
            $monthquery = Doo::db ()->query ( $monthsql );
            $monthuseraddnum = $monthquery->fetch();
            array_unshift($muaddnumstr,$monthuseraddnum['count']);

            $monthday = strtotime($startmonth);
        }
        $this->data['monthstr'] = $monthstr;
        $this->data['muaddnumstr'] = $muaddnumstr;

        //充值记录
        $alipaytodaycount = $pay->get_sum_succ_posts('alipay', $today, $thistime);
        $alipayyesterdaycount = $pay->get_sum_succ_posts('alipay', $yesterday, $today);

        $offlinetodaycount = $pay->get_sum_succ_posts('offline', $today, $thistime);
        $offlineyesterdaycount = $pay->get_sum_succ_posts('offline', $yesterday, $today);

        $this->data['atcount'] = $alipaytodaycount['sum'];
        $this->data['aycount'] = $alipayyesterdaycount['sum'];
        $this->data['otcount'] = $offlinetodaycount['sum'];
        $this->data['oycount'] = $offlineyesterdaycount['sum'];
        $this->data['alltcount'] = floatval($alipaytodaycount['sum'])+floatval($offlinetodaycount['sum']);
        $this->data['allycount'] = floatval($alipayyesterdaycount['sum'])+floatval($offlineyesterdaycount['sum']);


        //2015,2016年充值数据
        $yearstart2015 = 1420041600;
        $yearend2015 = 1451577599;
        $yearstart2016 = 1451577600;
        $yearend2016 = 1483199999;

        $alipay2015 = $pay->get_sum_succ_posts('alipay', $yearstart2015, $yearend2015);
        $alipay2016 = $pay->get_sum_succ_posts('alipay', $yearstart2016, $yearend2016);

        $offline2015 = $pay->get_sum_succ_posts('offline', $yearstart2015, $yearend2015);
        $offline2016 = $pay->get_sum_succ_posts('offline', $yearstart2016, $yearend2016);

        $recharge2015 = $pay->get_sum_succ_posts('recharge', $yearstart2015, $yearend2015);
        $recharge2016 = $pay->get_sum_succ_posts('recharge', $yearstart2016, $yearend2016);

        $all2015 = floatval($alipay2015['sum'])+floatval($offline2015['sum'])+floatval($recharge2015['sum']);
        $all2016 = floatval($alipay2016['sum'])+floatval($offline2016['sum'])+floatval($recharge2016['sum']);

        $this->data['alipay2015'] = $alipay2015['sum'];
        $this->data['alipay2016'] = $alipay2016['sum'];
        $this->data['offline2015'] = $offline2015['sum'];
        $this->data['offline2016'] = $offline2016['sum'];
        $this->data['recharge2015'] = $recharge2015['sum'];
        $this->data['recharge2016'] = $recharge2016['sum'];
        $this->data['all2015'] = $all2015;
        $this->data['all2016'] = $all2016;

        //2016每个月的充值数据
        $data2016 = array();
        for($i = 0; $i < 12; $i++){
            $j = $i+1;
            $data2016[$i]['month'] = $j.'月';
            $j = $j < 10 ? '0'.$j : $j;
            $nowmonth = '2016-'.$j.'-01';
            $starttime = strtotime($nowmonth);
            $endtime = strtotime("+1 months", strtotime($nowmonth))-1;

            $alipay = $pay->get_sum_succ_posts('alipay', $starttime, $endtime);
            $offline = $pay->get_sum_succ_posts('offline', $starttime, $endtime);
            $recharge = $pay->get_sum_succ_posts('recharge', $starttime, $endtime);
            $allpost = floatval($alipay['sum'])+floatval($offline['sum'])+floatval($recharge['sum']);

            $data2016[$i]['alipay'] = empty($alipay['sum']) ? 0 : $alipay['sum'] ;
            $data2016[$i]['offline'] = empty($offline['sum']) ? 0 : $offline['sum'];
            $data2016[$i]['recharge'] = empty($recharge['sum']) ? 0 : $recharge['sum'];
            $data2016[$i]['allpost'] = $allpost;
        }
        $this->data['data2016'] = $data2016;

        //总充值总计
        $firsttime = mktime(0,0,0,11,1,2012);
        $all = $pay->getOne(array('select' => 'sum(money) as sum', 'where' => 'status="succ" and addtime between '. $firsttime .' and '. $thistime, 'asArray' => TRUE));

        $this->data['all'] = round($all['sum'],2);

        $this->data['selectindex'] = true;
        $this->render('admin/admin-index', $this->data);
    }

    public function mainCharts(){
        //获取最近的30天充值记录
        Doo::loadModel('pay');

        $thistime = time();
        $day = date('Y-m-d',$thistime);
        $endtime = strtotime($day)+86400;
        $starttime = strtotime("$day - 1 month")+86400;
        $hadnum = ($endtime-$starttime)/86400;
        $lastday = $endtime;
        $daystr = $alipaystr = $offlinestr = $allstr = array();
        for($i = 1; $i <= $hadnum; $i++){
            $pay = new Pay();
            $addoneday = date('Y-m-d',$lastday);
            $lastday = strtotime("$addoneday - 1 day");
            $monthnum = date('m',$lastday);
            $daynum = date('d',$lastday);
            $thisday = intval($daynum);
            $starttoday = date('Y',$lastday).'-'.$monthnum.'-'.$daynum;
            $endtoday = date('Y-m-d',strtotime("$starttoday + 1 day"));
            array_unshift($daystr,$thisday);

            $alipaycount = $pay->get_sum_succ_posts('alipay', strtotime($starttoday), strtotime($endtoday));
            $alipaycount = empty($alipaycount['sum']) ? 0 : floatval($alipaycount['sum']);
            array_unshift($alipaystr,$alipaycount);

            $offlinecount = $pay->get_sum_succ_posts('offline', strtotime($starttoday), strtotime($endtoday));
            $offlinecount = empty($offlinecount['sum']) ? 0 : floatval($offlinecount['sum']);
            array_unshift($offlinestr,$offlinecount);

            array_unshift($allstr,floatval($alipaycount)+floatval($offlinecount));
        }

        echo json_encode(array("daystr" => $daystr, "alipaystr" => $alipaystr, "offlinestr" => $offlinestr, 'allstr' => $allstr));
        exit;
    }

    /**
     * 	默认路由、登陆
     */
    public function login() {
        if (!empty($_SESSION['main'])) {
            return Doo::conf()->APP_URL . 'm/main';
        }
        if (!empty($_POST['username']) && !empty($_POST['password'])) {
            $username = addslashes($_POST['username']);
            $password = addslashes($_POST['password']);
            $muser = Doo::loadModel('m/musers', TRUE);
            $userArray = $muser->getOne(array(
                'select' => 'username,password,salt',
                'where' => 'username=?',
                'param' => array($username),
                'limit' => 1,
                'asArray' => TRUE,
                    ));
            $pwd = md5(md5($password) . $userArray['salt']);
            $newpwd = $userArray['password'];
            if ($pwd == $newpwd) {
                $_SESSION['main'] = 'Main';
                $_SESSION['userArray'] = $userArray;
                return Doo::conf()->APP_URL . 'm/main';
            }
        } else {
            $this->render('admin/login', $this->data, TRUE);
        }
    }

    /**
     * 	录入
     */
    public function addcity() {
        if (empty($_SESSION['main'])) {
            return Doo::conf()->APP_URL . 'm';
        }
        Doo::loadModel('category');
        $cat = new Category();
        if (!empty($_POST['citysubmit'])) {
            $cat->add_cat(htmlspecialchars($_POST['categoryname']), intval($_POST['acsel']));
            echo '添加完毕';
        }
        $this->data['arrcat'] = $cat->get_all();
        $this->render('admin/addcity', $this->data);
    }

    /**
     *
     * @param type $param
     */
    public function user($param) {
        $this->render('admin/addcity', $this->data);
    }

    /**
     *
     * @param type $param
     */
    public function logout() {
        $_SESSION['main'] = NULL;
        session_destroy();
        session_unset();
        return Doo::conf()->APP_URL . 'm';
    }

    /**
     *
     * @param type $param
     */
    public function userAdd() {
        if (empty($_SESSION['main'])) {
            return Doo::conf()->APP_URL . 'm';
        }
        Doo::loadModel('users');
        $user = new Users();
        // 添加用户方法
//        if (!empty($_POST['username']) && !empty($_POST['password']) && !empty($_POST['useremail'])) {
//            $username = addslashes(htmlspecialchars($_POST['username']));
//            $useremail = addslashes(htmlspecialchars($_POST['useremail']));
//            $password = addslashes(htmlspecialchars($_POST['password']));
//            $salt = $this->create_randomstr();
//            $muserArray = array('username' => $username, 'userpasswd' => $this->create_password($password, $salt), 'useremail' => $useremail, 'salt' => $salt, 'clientip' => $this->clientIP());
//            if ($user->userAdd($muserArray))
//                return Doo::conf()->APP_URL . 'm/user';
//        }
        // END

        if (!empty($_POST['searchuser']) && !empty($_POST['ttt'])) {
//            if (!empty($_POST['username'])) {
//                $totalArchive = $user->count(array('select' => 'username,useremail,lastloginip,lastlogintime', 'where' => 'username=?', 'param' => array($_POST['username']), 'limit' => '1', 'asArray' => TRUE));
//            } elseif (!empty($_POST['useremail'])) {
//                $totalArchive = $user->count(array('where' => 'useremail=?', 'param' => array($_POST['useremail']), 'asArray' => TRUE));
//            } else
            if ($this->isMail($_POST['ttt'])) {
                $totalArchive = $user->count(array('where' => 'useremail=?', 'param' => array(trim($_POST['ttt'])), 'asArray' => TRUE));
//                if(empty($totalArchive))
//                	$totalArchive = $user->count(array('where' => 'username=?', 'param' => array(trim($_POST['ttt'])), 'asArray' => TRUE));
            }
            else if($this->isMobile($_POST['ttt'])) {
                $totalArchive = $user->count(array('where' => 'mobile=?', 'param' => array(trim($_POST['ttt'])), 'asArray' => TRUE));
            }else {
                $totalArchive = $user->count(array('where' => 'username=?', 'param' => array(trim($_POST['ttt'])), 'asArray' => TRUE));
            }
        } else {
            $totalArchive = $user->count();
        }
        Doo::loadHelper('DooPager');
        $pager = new DooPager(Doo::conf()->APP_URL . "m/user/page", $totalArchive, 30, 10);
        if (!empty($this->params['pindex']))
            $pager->paginate(intval($this->params['pindex']));
        else
            $pager->paginate(1);

        if (!empty($_POST['searchuser']) && !empty($_POST['ttt'])) {
            $this->data['search'] = true;
//            if (isset($_POST['username'])) {
//                $userArray = $user->getOne(array('where' => 'username=?', 'param' => array($_POST['username']), 'asArray' => TRUE));
//            } elseif (isset($_POST['useremail'])) {
//                $userArray = $user->getOne(array('where' => 'useremail=?', 'param' => array($_POST['useremail']), 'asArray' => TRUE));
//            } else
            if ($this->isMail($_POST['ttt'])) {
                $userArray[0] = $user->getOne(array('where' => 'useremail=?', 'param' => array(trim($_POST['ttt'])), 'asArray' => TRUE));
//                	if(empty($userArray[0]))
//                		$userArray[0] = $user->getOne(array('where' => 'username=?', 'param' => array(trim($_POST['ttt'])), 'asArray' => TRUE));
            } elseif($this->isMobile($_POST['ttt'])) {
                $userArray[0] = $user->getOne(array('where' => 'mobile=?', 'param' => array(trim($_POST['ttt'])), 'asArray' => TRUE));
            }else {
                $userArray[0] = $user->getOne(array('where' => 'username=?', 'param' => array(trim($_POST['ttt'])), 'asArray' => TRUE));
            }
        } else {
            $userArray = $user->getAll($pager->limit);
        }
        foreach($userArray as $k => $v){
            $userArray[$k]['status'] = self::isUserActive($v['id']);
        }
        $this->data['pager'] = $pager->output;
        $this->data['userArray'] = $userArray;
        $this->data['selectuser'] = true;
        $this->render('admin/user', $this->data, TRUE);
    }

    /**
     *
     * @param $password 密码
     * @param $random 随机数
     */
    function create_password($password = '', $random = '') {
        if (empty($random)) {
            $array['random'] = $this->create_randomstr();
            $array['password'] = md5(md5($password) . $array['random']);
            return $array;
        }
        return md5(md5($password) . $random);
    }

    /**
     * 生成随机字符串
     * @param string $lenth 长度
     * @return string 字符串
     */
    function create_randomstr($lenth = 6) {
        return $this->random($lenth, '123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ');
    }

    /**
     * 随机字符串函数
     * @param $password 密码
     * @param $random 随机数
     */
    function random($length, $chars = '0123456789') {
        $hash = '';
        $max = strlen($chars) - 1;
        for ($i = 0; $i < $length; $i++) {
            $hash .= $chars[mt_rand(0, $max)];
        }
        return $hash;
    }

    /**
     *
     * @param type $param
     */
    public function adminAdd() {
        if (empty($_SESSION['main'])) {
            return Doo::conf()->APP_URL . 'm';
        }
        Doo::loadModel('m/musers');
        $musers = new Musers();
        // 添加用户方法
        if (!empty($_POST['username']) && !empty($_POST['password'])) {
            $username = addslashes(htmlspecialchars($_POST['username']));
            $password = addslashes(htmlspecialchars($_POST['password']));
            $salt = $this->create_randomstr();
            $muserArray = array('username' => $username, 'password' => $this->create_password($password, $salt), 'groups' => 'admin', 'salt' => $salt);
            if ($musers->muserAdd($muserArray))
                return Doo::conf()->APP_URL . 'm/admin';
        }
        // END
        $totalArchive = $musers->getCountz();
        Doo::loadHelper('DooPager');
        $pager = new DooPager(Doo::conf()->APP_URL . "m/admin/page", $totalArchive, 2, 5);
        if (!empty($this->params['pindex']))
            $pager->paginate(intval($this->params['pindex']));
        else
            $pager->paginate(1);
        $userArray = $musers->getAll($pager->limit);
        $this->data['pager'] = $pager->output;
        $this->data['userArray'] = $userArray;
        $this->data['selectuser'] = true;
        $this->render('admin/admin', $this->data, TRUE);
    }

    /**
     *
     * @param type $param
     */
    public function mainIndex() {
        $this->render('admin/gloablStyle', $this->data, TRUE);
    }

    public function payStatus(){
    	$id=isset($_POST['id'])?$_POST['id']:'';
    	$username=isset($_POST['username'])?$_POST['username']:"";
    	
    	if(empty($id)||empty($username))
            return false;
    	
    	Doo::loadModel('pay');
        $pay = new Pay();
    	
        $pinfo=$pay->getRowByUid($id);
        
        if($pinfo['status']=='waitting'||$pinfo['status']=='unpay'){
        	$p = new Pay();
        	
        	$p->id=$id;
        	
        	$p->paytime=time();
        	
        	$p->checker=$username;
        	
        	$p->adminnote=2;
        	
        	$p->status="succ";
        	
        	if($pinfo['money']>0){
                if(!empty($pinfo['telephone'])&&($pinfo['money']>=$this->cashlimit)){
                    $salerGet = floor($pinfo['money']*$this->salelimit); // 计算销售人员获得的提成
                    $pinfo['money'] += floor($pinfo['money']*$this->perlimit);
                    Doo::loadModel('m/sale');
                    $saleObj = new Sale();
                    $saleObj->total = new DooDbExpression('total+' . $salerGet);
                    $saleObj->update(array('where'=>'promocode=?','param'=>array($pinfo['telephone'])));
                }
        		Doo::loadModel('users');
        		$user = new Users();
        		$k=$user->updateBank($pinfo['userid'], $pinfo['money']);
        		if($k){
                    Doo::loadModel('income_pay');
                    $incomepay = new IncomePay();
                    $incomepay->uid = $pinfo['userid'];
                    $incomepay->money = $pinfo['money'];
                    $incomepay->type = 1;
                    $incomepay->comefrom = $pinfo['payment'];
                    $incomepay->addtime = time();
                    $incomepay->insert();

        			$p->update();
//        			echo '{"success": true}';die;
        		}
        	}
        }
        return '/m/pay/add';
    }
    
    /**
     *
     */
    public function pay() {
        if (empty($_SESSION['main'])) {
            return Doo::conf()->APP_URL . 'm';
        }
        if (isset($_GET['op']) && !empty($_POST['ids'])) {
            $ops = $_GET['op'];
//            $ids = implode(',', $_POST['ids']);
            $ids = $_POST['ids'];
            Doo::loadModel('pay');
            $p = new Pay();
            if (!empty($ids)) {
                if ($ops == 'del') {
                    foreach ($ids as $key => $val) {
                        $p->id = $val;
                        $p->delete();
                    }
                }

                if ($ops == 'act') {
                    foreach ($ids as $key => $val) {
                        $p->status = 'succ';
                        $p->update(array('where' => 'id=' . $val));
                    }
                }
            }
        }
        
        $status=isset($_GET['status'])?$_GET['status']:'1';
        if($status==1&&isset($this->params['status']))
    		$status=urldecode($this->params['status']);

        $search = isset($_GET['search'])?$_GET['search']:'1';
        if($search==1&&isset($this->params['search']))
            $search=$this->params['search'];
        
    	$s='all';

        $ss = $sql1 = $sql2 = '';
        if($status=="succ"){
            $s='succ';
            $sql1.="status='succ'";
        }elseif($status=="waitting:unpay"){
            $s='waitting:unpay';
            $sql1.="(status='waitting' or status='unpay')";
        }
        if($search!=1){
            $ss = $search.'/';
            Doo::loadModel('users');
            $users = new Users();
            $id = $users->getidBysearch($search);
            if(isset($id['id'])){
                $sql2 .= 'userid='.$id['id'];
            }else{
                $sql2 = 'username="'.$search.'"';
            }
        }
        if(empty($sql2) && empty($sql1)){
            $sql = ' 1';
        }elseif(!empty($sql2) && empty($sql1)){
            $sql = $sql2;
        }elseif(empty($sql2) && !empty($sql1)){
            $sql = $sql1;
        }else{
            $sql = $sql2 . ' and '. $sql1;
        }
		
        Doo::loadHelper('DooPager');
        Doo::loadModel('pay');
        $pay = new Pay();
        $totalArchive = $pay->count(array('where' => $sql));
        $pager = new DooPager(Doo::conf()->APP_URL . "m/pay/add/page/".$ss.$s, $totalArchive, 30, 10);
        
        if (isset($this->params['pindex']))
            $pager->paginate(intval($this->params['pindex']));
        else
            $pager->paginate(1);
     
		$this->data['status']=$s;
		$this->data['search']= $search != 1 ? $search : '';
        if ($pager->limit != ' -30,30')
            $this->data['userArray'] = $pay->get_all_posts_status($pager->limit,$sql);
        // var_dump($this->data['userArray']);
        if(isset($this->data['userArray']) && !empty($this->data['userArray'])) {
            foreach ($this->data['userArray'] as $key => $value) {
                if (!empty($value['telephone']) && ($value['money'] >= $this->cashlimit)) {
                    Doo::loadModel('m/sale');
                    $saleObj = new Sale();
                    $saleArray = $saleObj->getOne(array('where' => 'promocode=?', 'param' => array($value['telephone']), 'asArray' => TRUE));
                    $this->data['userArray'][$key]['info'] = '(多送5%[' . $value['money'] * $this->perlimit . '元],' . $saleArray['salename'] . ')';
                }
                Doo::loadModel('users');
                $users = new Users();
                $user = $users->getRowByid($value['userid']);
                $this->data['userArray'][$key]['mobile'] = $user['mobile'];
                $this->data['userArray'][$key]['email'] = $user['useremail'];

                $this->data['userArray'][$key]['status2'] = self::isUserActive($value['userid']);
            }
        }
        $this->data['pager'] = $pager->output;
        $this->data['selectorder'] = true;
        $this->render('admin/pay', $this->data, TRUE);
    }

    /**
     *
     */
    public function payModify() {
        if (empty($_SESSION['main'])) {
            return Doo::conf()->APP_URL . 'm';
        }
        $id = intval($this->params['pid']);
        if (empty($id))
            return false;
        $money = isset($_POST['money']) ? intval($_POST['money']) : NULL;
        if (!empty($money)) {
            Doo::loadModel('pay');
            $pay = new Pay();
//            $pay->money = new DooDbExpression('money+' . $money);
            $pay->money = $money;
            $pay->update(array('where' => 'id=' . $id));
            return Doo::conf()->APP_URL . 'm/pay/add';
        }
//        Doo::loadModel('pay');
//        $pay = new Pay();
//        $this->data['userArray'] = $pay->getRowByUid($id);
        return '/m/pay/add';
//        $this->render('admin/pay_modify', $this->data, TRUE);
    }

    public function voucherList(){
        if (empty($_SESSION['main'])) {
            return Doo::conf()->APP_URL . 'm';
        }
        Doo::loadModel('voucher');
        $voucher = new Voucher();
        Doo::loadHelper('DooPager');
        $countsql = $sql = '';
        $this->data['starttime'] = strtotime(date("Y-m-d",strtotime("+1 day")));
        if(isset($this->params['status']) && is_numeric($this->params['status'])){
            $sql = 'status='.$this->params['status'];
            $countsql = 'status/'.$this->params['status'].'/';
            $this->data['status'] = $this->params['status'];
        }
        if(!empty($sql)){
            $totalArchive = $voucher->count(array('where' => $sql));
        }else{
            $totalArchive = $voucher->count();
        }
        $pager = new DooPager(Doo::conf()->APP_URL . "m/voucher/".$countsql, $totalArchive, 30, 10);
        if (isset($this->params['pindex']))
            $pager->paginate(intval($this->params['pindex']));
        else
            $pager->paginate(1);
        if ($pager->limit != ' -30,30')
            $voucherlist = $voucher->getAll($sql,$pager->limit);

        if(isset($voucherlist) && !empty($voucherlist)){
            $thistime = time();
            $this->data['thistime'] = $thistime;
            foreach($voucherlist as $k => $v){
                Doo::loadModel('users_voucher');
                $uservoucher = new UsersVoucher();
                if($thistime>=$v['vstarttime'] && $thistime<$v['vendtime']){
                    $voucherlist[$k]['status'] = 1;
                }
                $voucherlist[$k]['hadnum'] = $uservoucher->count(array('where' => 'vid='.$v['id']));
                if(($v['vcount'] != 0 && $voucherlist[$k]['hadnum'] >= $v['vcount']) || $thistime>=$v['vendtime']){
                    $voucherlist[$k]['status'] = 2;
                }
                if($voucherlist[$k]['status'] != 0){
                    $voucher2 = new Voucher();
                    $voucher2->id = $v['id'];
                    $voucher2->status = $voucherlist[$k]['status'];
                    $voucher2->update();
                }
            }

            $this->data['voucherlist'] = $voucherlist;
        }

        $this->data['pager'] = $pager->output;
        $this->data['selectvoucher'] = true;
        $this->render('admin/voucher', $this->data, TRUE);
    }

    public function setVoucher(){
        if(!isset($_POST['vname']) || empty($_POST['vname'])){
            exit('活动名不能为空');
        }
        if(!isset($_POST['vcost']) || empty($_POST['vcost'])){
            exit('金额不能为空');
        }
        if(!isset($_POST['starttime']) || empty($_POST['starttime'])){
            exit('请选择开始日期');
        }
        if(!isset($_POST['endtime']) || empty($_POST['endtime'])){
            exit('请选择结束日期');
        }
        if(isset($_POST['vcount']) && is_int($_POST['vcount'])){
            exit('代金券数量只能为整数');
        }
        if(strtotime($_POST['starttime'].' 00:00:00') < time()){
            exit('开始时间不能小于或等于活动添加当天');
        }
        if(strtotime($_POST['endtime'].' 23:59:59') < strtotime($_POST['starttime'].' 00:00:00')){
            exit('结束时间不能小于开始时间');
        }
        Doo::loadModel('voucher');
        $voucher = new Voucher();
        $voucher->vname = $_POST['vname'];
        $voucher->vcode = $this->MadeCode();
        $voucher->vcost = $_POST['vcost'];
        $voucher->vcount = empty($_POST['vcount']) ? 0 : $_POST['vcount'];
        $voucher->vstarttime = strtotime($_POST['starttime'].' 00:00:00');
        $voucher->vendtime = strtotime($_POST['endtime'].' 23:59:59');
        $voucher->vaddtime = time();
        $voucher->status = 0;
        $voucher->insert();

        return '/m/voucher';
    }

    public function delVoucher(){
        if(isset($this->params['vid']) && is_numeric($this->params['vid'])){
            Doo::loadModel('voucher');
            $voucher = new Voucher();
            $voucher->id = $this->params['vid'];
            $voucher->delete();
        }
        return '/m/voucher';
    }

    function isMail($mail) {
        if (preg_match("/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9\-\.])+/", $mail))
            return true;
        else
            return false;
    }

    function isMobile($mobile) {
        if(preg_match("/^1[34578]{1}\d{9}$/",$mobile)){
            return TRUE;
        } else {
            return FALSE;
        }
    }

    private static function isUserActive($uid) {
        Doo::loadModel('userswitch');
        $userswitch = new UserSwitch();
        return $userswitch->checkUserStatus($uid);
    }

    //随机生成6位的项目领取码
    private function MadeCode(){
        $string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        $code = '';
        for($i = 0; $i < 6; $i++){
            $index = rand(0,61);
            $code .= substr($string,$index,1);
        }
        return $code;
    }

//    public function payUpdate(){
//        Doo::loadModel('pay');
//        $pay = new Pay();
//        $paylist = $pay->find(array('where' => 'status="succ"', 'asArray' => TRUE));
//        Doo::loadModel('income_pay');
//        foreach($paylist as $k => $v){
//            $incomepay = new IncomePay();
//            $incomepay->uid = $v['userid'];
//            $incomepay->money = $v['money'];
//            $incomepay->type = 1;
//            if($v['pay_type'] == 'voucher'){
//                $incomepay->comefrom = '代金券';
//                $incomepay->description = $v['payment'];
//            }else{
//                $incomepay->comefrom = $v['payment'];
//                if(!empty($v['checker'])){
//                    $incomepay->description = $v['checker'];
//                }
//            }
//            $incomepay->addtime = $v['addtime'];
//            $incomepay->insert();
//        }
//    }



}

?>