<?php
namespace Home\Controller;
use Think\Controller;

class IndexController extends Controller {

    protected function _initialize(){
        $website = M('website_config')->where('uid=1')->find(); //网站
        $weixin = M('weixin_config')->where('uid=1')->find(); //微信
        $this->weixin=$weixin;
         //JSSDK
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $JSSDK = A('Home/Weixin');
        $Jsapi=$JSSDK->getJsSign(1,$url);
        $this->assign(compact('website','weixin','Jsapi'));
    }

    /*采用跳转获取OPENID 可以隐藏获取但不稳定*/
    public function getOpenid(){
        $siteurl="https://water.suanok.com";
        $weixin=$this->weixin;
        $APPID=$weixin['weixinappid']; 
        $act=I('get.act'); //跳转控制器
        $state=I('get.state'); //参数
        $REDIRECT_URI=$siteurl.'/Home/index/'.$act.'/'; 
        $gourl='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$APPID.'&redirect_uri='.urlencode($REDIRECT_URI).'&response_type=code&scope=snsapi_base&state='.$state.'#wechat_redirect';  
        header("Location:".$gourl);
    }

    /*入口文件*/
    public function index(){
        $code=I('get.code'); //获取随机码
        $tab=M('qrcode');
        $tab->where("RandString='".$code."'")->setInc('ScanCount',1); //更新扫码次数
        $info=$tab->where("RandString='".$code."'")->field('QrcodeType,Parameter')->find();//查二维码表
        $this->redirect('getOpenid', array('act'=>$info['QrcodeType'],'state'=>$info['Parameter'])); //跳转至openid获取入口
    }

    /*跳转入口*/
    public function backgo(){
        $openid=I('get.openid');
        $RandString=M('scanlog')->where("openid='".$openid."'")->order('ScanlogId desc')->getfield('RandString'); 
        $this->redirect('index', array('code'=>$RandString)); //跳转至入口文件
    }

    /*写入会员手机*/
    public function userMobile(){
        if(IS_POST){
           //存入会员
           $openid=I('post.openid');
           $Mobile=I('post.Mobile');
           $dzpId=I('post.dzpId');
           $title=I('post.title');
           $MobileChk=M('user')->where("Mobile='".$Mobile."'")->count();
           if($MobileChk==0){
                $data['Mobile']=$Mobile;
                $UserId=M('user')->where("openid='".$openid."'")->save($data);
                echo 'success';
            }else{
                echo 'repeat'; //手机号已存在
            }
        }
    }

    public function upUserNettype(){
        $openid=I('post.openid');
        $net_type=I('post.net_type');
        $nettypeid=I('post.nettypeid');

        $data['net_type']=$net_type;
        $reId=M('scanlog')->where("openid='".$openid."' and ScanlogId=".$nettypeid)->save($data);
        echo $reid;
    }

    /*广告入口*/
    public function adve(){
        $openid=I('get.openid');
        if($openid==''){
            $code=I('get.code');
            $state=I('get.state');
            $OAuth = A('Home/Weixin');
            $json=$OAuth->getOauthAccessToken(1,$code);
            $openid=trim($json['openid']);
            $info=M('adve')->where('AdveId='.$state)->find();

            //写入扫码日志
            $QrcodeInfo=M('qrcode')->where("QrcodeType='adve' and Parameter=".$state)->find();
            $Tab = D("Scanlog"); 
            $data['QrcodeId'] = $QrcodeInfo['QrcodeId'];
            $data['RandString'] = $QrcodeInfo['RandString'];
            $data['QrcodeType'] = 'adve';
            $data['openid'] = $openid;
            $data['addtime'] = time();
            $nettypeid=$Tab->add($data);

            if($info['GoUrl']!=''){
                $this->redirect($info['GoUrl'], array('openid'=>$openid,'state'=>$state,'nettypeid'=>$nettypeid));
            }else{
                $this->assign(compact('info','state','openid','nettypeid'));
                $this->display();
            }
        }
    }

    /*机器入口*/
    public function mach(){
        $openid=I('get.openid');
        $MachId=I('get.MachId');
        $state=I('get.state');
        $nettypeid=I('get.nettypeid');

        
        if($openid==''&&$MachId==''){ //第一次扫码进入
                $code=I('get.code');
                $state=I('get.state');
                $OAuth = A('Home/Weixin');
                $json=$OAuth->getOauthAccessToken(1,$code);
                $openid=trim($json['openid']);   
                $machinfo=M('mach')->where('MachId='.$state)->find();//获取机器信息
                $MachId=$machinfo['MachId'];

                //写入扫码日志
                $QrcodeInfo=M('qrcode')->where("QrcodeType='mach' and Parameter=".$state)->find();
                $Tab = D("Scanlog"); 
                $data['QrcodeId'] = $QrcodeInfo['QrcodeId'];
                $data['RandString'] = $QrcodeInfo['RandString'];
                $data['QrcodeType'] = 'mach';
                $data['openid'] = $openid;
                $data['addtime'] = time();
                $nettypeid=$Tab->add($data);

                //写入用户的机器ID
                M('user')->where("openid='".$openid."'")->setField('MachId',$MachId);

                //判断是否有人取水，没有则写入
                $fetchChk=M('fetch')->where("MachId=".$MachId)->order('addtime desc')->find(); //机器可用取水检查
                if(empty($fetchChk)||(!is_null($fetchChk['FlowMl']))){
                    //写入当前取水用户信息
                    $machData['curOpenid'] = $openid;
                    $machData['scanTime'] = time();
                    M('mach')->where('MachId='.$MachId)->save($machData);
                }
                $this->redirect('/Home/index/mach/', array('openid'=>$openid,'MachId'=>$MachId,'state'=>$state,'nettypeid'=>$nettypeid));
                
        }elseif($openid!=''&&$MachId!=''){ //从其它页面转入
                $machinfo=M('mach')->where('MachId='.$MachId)->find();
        }
        $usrChk=M('user')->where("openid='".$openid."'")->count();
        if($usrChk<=0&&$machinfo['ActUrl']!=''){
            $this->redirect($machinfo['ActUrl'], array('openid'=>$openid,'state'=>$state));
        }else{
                
            $jrtj=M('website_content')->where('mid=1')->field('id,title,info,imglist')->order('id desc')->limit(3)->select();
            foreach ($jrtj as $i => $item) {
                            $img = explode('@', $item['imglist']);
                            $jrtj[$i]['img'] = $img[0];
            }
            $qwrd=M('website_content')->where('mid=2')->field('id,title,info,formto,addtime')->order('id desc')->select();

            $ShareOpenid=M('userbind')->where("BindOpenid='".$openid."'")->getfield('openid');

            //判断是否充值一元
            $DzpUserinfo=M('user')->where("openid='".$openid."' and orderId is null and wxpay_prepay_id is null")->count();

           //判断是否找房东领取礼品
            if($DzpUserinfo==0){
                $giftChk=M('fanggift')->where("UserOpenid='".$openid."' and GiftType>0")->count();
            }else{
                $giftChk=-1;
            }
           

        $this->assign(compact('machinfo','state','openid','MachId','jrtj','qwrd','ShareOpenid','DzpUserinfo','giftChk','nettypeid'));
        $this->display();
        }

//--- 20171106 DV add save log
        $datax['OpenId'] = $openid;
        $datax['VisitPage']='mach';
        $datax['VisitTmk'] = date('YmdHis');
        M('z_promo_log')->add($datax);
    }

    /*
    取水检查返回值
    -10  所有水库为0
    -11  自己水库小于当前取水量
    -20  自己钱包为0
    -30  当前不能取水（机器被占用）
    -31  当前不能取水（二维码失效）
    20   一切正常(取自己水)
    21   一切正常(取共享帐户)
    */
    public function getwaterChk(){
        if(IS_POST){
           
            $openid=I('post.openid');
            $MachId=I('post.MachId');
            $MachNum=I('post.MachNum');
            $paytype=I('post.paytype');
            $getWaterId=I('post.getWaterId');
            //取水之前检查
            $machChk=M('mach')->where("MachId=".$MachId)->find();
            $second=time()-$machChk['scanTime'];
            if($machChk['curOpenid']!=$openid) {
                if($second>900){
										//前次取水大于15分钟已超时,MQTT server 未收到取水完成,主动生成关阀记录，并发出关阀命令
                    mysql_connect('localhost','root','revres88') or die('connect fail!!');
                    $tmpdb="Ko001";
                    mysql_select_db($tmpdb);
                    $ValveTmk=date("Y-m-d H:i:s",intval(time()));
                    $sql="INSERT INTO Ko001.mq_valve (GateId,PipeId,ValveTmk,ValveStat,ValveTmkStamp) VALUES ('".$MachNum."','0','".$ValveTmk."','f',".time().")";
                    mysql_query($sql);
                     require_once "DvAPI/mqtt-tool-dv.php";
                    MqttCloseValve($MachNum);

                }
                echo -30;
            }elseif($second>30){
                echo -31;
            }else{
                switch ($getWaterId) {//用户取水设定
                    case '1':
                        $userGetWater=1000; 
                        break;
                    case '2':
                        $userGetWater=3000;
                        break;
                    case '3':
                        $userGetWater=1000;
                        break;
                    case '4':
                        $userGetWater=1000;
                        break;
                }
                //用户自己库存
                $userInfo=M('user')->where("openid='".$openid."'")->field('Money,Water')->find();
                $userWater=$userInfo['Water'];
                $userMoney=$userInfo['Money'];
                if($userWater==0){ //自己水库为空查询共享帐户
                    $ShareOpenid=M('userbind')->where("BindOpenid='".$openid."'")->getfield('openid');
                    if($ShareOpenid!=''){
                      $ShareWater=M('user')->where("openid='".$ShareOpenid."'")->field('Water')->find(); //绑定用户水库
                    }
                }
                if($userWater==0&&$ShareWater==0&&$paytype==1){
                    echo -10;
                }elseif($userWater==0&&$ShareWater>0&&$paytype==1){ //使用共享帐号
                    switch ($getWaterId) {
                        case '1':
                            if($ShareWater<1000){
                                echo -11;
                            }else{
                                echo 21;
                            }
                            break;
                        case '2':
                            if($ShareWater<3000){
                                echo -11;
                            }else{
                                echo 21;
                            }
                            break;
                        case '3':
                                echo 21;
                            break;
                    }
                }elseif($userMoney==0&&$paytype==2){//钱包为0
                    echo -20;
                }elseif($userWater<=3000&&$paytype==1){ //水库小于等于3L
                    switch ($getWaterId) {
                        case '1':
                            if($userWater<1000){
                                echo -11;
                            }else{
                                echo 20;
                            }
                            break;
                        case '2':
                            if($userWater<3000){
                                echo -11;
                            }else{
                                echo 20;
                            }
                            break;
                        case '3':
                                echo 20;
                            break;
                    }
                }elseif($userWater>3000&&$paytype==1){ //水库大于3L
                     echo 20;
                }elseif($paytype==2){ //钱包取水（钱包不为0)
                     echo 20;
                }
            }//是否可以取水检查
          
        }//POST判断
    }

    /*
    -112 机器故璋
    120  正常取水
    110  水箱不足，但可取水
    */
    public function getwaterOk(){
        if(IS_POST){
            $openid=I('post.openid');
            $FetchOpenid=I('post.FetchOpenid');
            $MachId=I('post.MachId');
            $MachNum=I('post.MachNum');
            $paytype=I('post.paytype');
            $getWaterId=I('post.getWaterId');
            //清空机器目前用户
            $machData['curOpenid'] = '';
            $machData['scanTime'] = '';
            $reid=M('mach')->where('MachId='.$MachId)->save($machData);
            $userInfo=M('user')->where("openid='".$openid."'")->field('Discount,Money,Water')->find();
            $UnitPrice=M('mach')->where("MachId=".$MachId)->getfield('UnitPrice');
            switch ($getWaterId) {
                case '1':
                    $userGetWater=1000; //用户取水设定
                    $ReqMode='1升';
                    break;
                case '2':
                    $userGetWater=3000;
                    $ReqMode='3升';
                    break;
                case '3':
                    $userGetWater=$userInfo['Water'];
                    $ReqMode='不限量取水';
                    break;
                case '4':
                    $userGetWater=($userInfo['Money']/($userInfo['Discount']*$UnitPrice))*1000;
                    $ReqMode='钱包支付取水';
                    break;
            }
            require_once "DvAPI/mqtt-tool-dv.php";
            MqttSetValve($MachNum,$userGetWater);
            for ($x=1; $x<=3; $x++) {
                    sleep($x);
                    $machinfo=M('mach')->where("MachNum='".$MachNum."'")->field('BankStock,ValveStat')->find();
                    $tmpSta=$machinfo['ValveStat'];
                    $tmpBank=$machinfo['BankStock'];
                    if($tmpSta=='o'){
                      break;
                    }
                    MqttSetValve($MachNum,$userGetWater);  
            }
            if($tmpSta!='o'){
                //写入机器故障
                mysql_connect('localhost','root','revres88') or die('connect fail!!');
                $tmpdb="Ko001";
                mysql_select_db($tmpdb);
                $ValveTmk=date("Y-m-d H:i:s",intval(time()));
                $sql="INSERT INTO Ko001.mq_valve (GateId,PipeId,ValveTmk,ValveStat,ValveTmkStamp) VALUES ('".$MachNum."','0','".$ValveTmk."','e',".time().")";
                mysql_query($sql);
                //清空取水记录
                $data['MqFlowId'] = 0;
                $data['FlowMl'] = 0;
                $map['MachId']=array('eq',$MachId);
                $map['FlowMl']=array('EXP','IS NULL');
                $reid=M('fetch"')->where($map)->save($data);
                $tmpSta=-112;

                //把阀再关闭一次 dv 20171117
            		MqttCloseValve($MachNum);
              }elseif($tmpBank>=$userGetWater){
                $tmpSta=120; //正常取水
              }else{
                $tmpSta=110; //水箱不足
              }
                //写入取水表
                $Tab = D("Fetch"); 
                $data['MachId'] = $MachId;
                $data['MachNum'] = $MachNum;
                $data['openid'] =  $openid;
                $data['FetchOpenid'] =  $FetchOpenid; 
                $data['paytype'] = $paytype;
                $data['ReqMode'] = $ReqMode;
                $data['addtime'] = time();
                $reid=$Tab->add($data);
                echo $tmpSta;
               
        }//POST判断
    }

    //今日推荐
    public function jrtjlist(){
        $openid=I('get.openid');
        $MachId=I('get.MachId');
        $state=I('get.state');
        $jrtj=M('website_content')->where('mid=1')->field('id,title,info,imglist')->order('id desc')->limit(3)->select();
        foreach ($jrtj as $i => $item) {
            $img = explode('@', $item['imglist']);
            $jrtj[$i]['img'] = $img[0];
        }
        $this->assign(compact('MachId','state','openid','jrtj'));
        $this->display();
    }

    //媒体展示
    public function viewcontent(){
        $openid=I('get.openid');
        $MachId=I('get.MachId');
        $state=I('get.state');
        $id=I('get.id');
        $info=M('website_content')->where('id='.$id)->find();
        $this->assign(compact('info','state','MachId','openid','jrtj','qwrd'));
        $this->display();
    }

    public function sign(){
        $openid=I('get.openid');
        $MachId=I('get.MachId');
        $state=I('get.state');
        if($openid==''){
            $this->redirect('/Home/index/msg/', array('msgType'=>'getwaterChk','openid'=>$openid,'MachId'=>$MachId,'state'=>$state));
        }else{
             //判断今天是否签到
            $date=strtotime(date("Y-m-d 00:00:00"));
            $signchk=M("usersign")->where('addtime>"'.$date.'"')->count();
            if($signchk>0){
                $this->redirect('/Home/index/msg/', array('msgType'=>'userSignOver','openid'=>$openid,'MachId'=>$MachId,'state'=>$state));
            }else{
                //没有获取到机器ID，则从广告二维码来
                if($MachId==''){
                    $ScanFrom = 'adve'; 
                }else{
                    $ScanFrom = 'mach';
                }
                //取出二维码相关信息
                $qrcodeinfo=M('qrcode')->where("QrcodeType='".$ScanFrom."' and Parameter=".$state)->find();
                $Tab = D("usersign"); //签到表
                $data['ScanFrom'] = $ScanFrom;
                $data['openid'] = $openid;
                $data['MachId'] = $MachId;
                $data['QrcodeId'] = $qrcodeinfo['QrcodeId'];
                $data['RandString'] = $qrcodeinfo['RandString'];
                $data['addtime'] = time();
                $reid=$Tab->add($data);
                if($reid>0){
                    $this->redirect('/Home/index/msg/', array('msgType'=>'userSign','openid'=>$openid,'MachId'=>$MachId,'state'=>$state));
                }
            }
        }
    }

    /*用户中心*/
    public function user(){
        $openid=I('get.openid');
        $MachId=(int)I('get.MachId');
        $state=(int)I('get.state');
        if($openid==''&&$MachId==''){ //第一次扫码进入
            $code=I('get.code');
            $state=I('get.state');
            $OAuth = A('Home/Weixin');
            $json=$OAuth->getOauthAccessToken(1,$code);
            $openid=trim($json['openid']);   
            $userinfo=M('user')->where("openid='".$openid."'")->find();
        }elseif($openid!=''){ //从其它页面转入
            $userinfo=M('user')->where("openid='".$openid."'")->find();
        }
        //通过最后扫码ID取出机器编号，预防机器扫码丢失
        $QrcodeId=M('scanlog')->where("openid='".$openid."' and QrcodeType='mach'")->order('ScanlogId desc')->getfield('QrcodeId'); 
        if($MachId!=''&&$QrcodeId>0){
           $MachId=M('qrcode')->where("QrcodeId=".$QrcodeId)->getfield('Parameter'); 
        }

        //判断是否领取新手礼包
        $DzpUserinfo=M('user')->where("openid='".$openid."' and orderId is null and wxpay_prepay_id is null")->count();

        //判断是否找房东领取礼品
        if($DzpUserinfo==0){
            $giftChk=M('fanggift')->where("UserOpenid='".$openid."' and GiftType>0")->count();
        }else{
            $giftChk=-1;
        }

        //判断是否房东
        $FangInfo=M('fang')->where("openid='".$openid."'")->find();

        $this->assign(compact('openid','MachId','userinfo','state','scanInfo','DzpUserinfo','FangInfo','giftChk'));
        $this->display(); 

//--- 20171106 DV add save log
        $datax['OpenId'] = $openid;
        $datax['VisitPage']='my';
        $datax['VisitTmk'] = date('YmdHis');
        M('z_promo_log')->add($datax);
    }

    /*用户水库*/
    public function mywater(){
        $openid=I('get.openid');
        $MachId=(int)I('get.MachId');
        $state=I('get.state');
        $Water=M('user')->where("openid='".$openid."'")->getfield('Water'); //用户水库余额
        $Water=$Water/1000;
        $list=M('buywater')->where("openid='".$openid."' and ((types=1 and wxpay_prepay_id!='') or (types=2))")->order('buyWaterId desc')->select();
        foreach ($list as $key => $value) {
            $waterl=$value['waterMl']/1000;
            switch ($value['types']) { //判断类型
                case '1':
                    $list[$key]['waterInfo']='您订购了'.$value['goodsName'];
                    break;
                case '2':
                    $list[$key]['waterInfo']='赠送给您'.$waterl.'升';
                    break;
            }
           
        }
        $this->assign(compact('openid','MachId','state','Water','list'));
        $this->display();

//--- 20171106 DV add save log
        $datax['OpenId'] = $openid;
        $datax['VisitPage']='mybank';
        $datax['VisitTmk'] = date('YmdHis');
        M('z_promo_log')->add($datax);
    }

    /*用户钱包*/
    public function mymoney(){
        $openid=I('get.openid');
        $MachId=(int)I('get.MachId');
        $state=I('get.state');
        $Money=M('user')->where("openid='".$openid."'")->getfield('Money'); //用户钱包余额
        $list=M('moneylog')->where("openid='".$openid."' and ((types=1 and wxpay_prepay_id!='') or (types=2))")->order('moneyLogId desc')->select();
        foreach ($list as $key => $value) {
            switch ($value['types']) { //判断类型
                case '1':
                    $types='充值';
                    break;
                case '2':
                    $types='赠送';
                    break;
                case '3':
                    $types='转帐';
                    break;  
                default:
                    $types='消费';
                    break;
            }
            if($value['state']==1){$moneyinfo=$value['money'].'元';}
            if($value['state']==-1){$moneyinfo='-'.$value['money'].'元';}
            $list[$key]['moneyInfo']=$types.$moneyinfo;
        }
        $this->assign(compact('openid','MachId','state','Money','list'));
        $this->display();

//--- 20171106 DV add save log
        $datax['OpenId'] = $openid;
        $datax['VisitPage']='mywallet';
        $datax['VisitTmk'] = date('YmdHis');
        M('z_promo_log')->add($datax);
    }

    /*用水记录*/
    public function userwaterlog(){
        $openid=I('get.openid');
        $MachId=(int)I('get.MachId');
        $state=I('get.state');
        $list=M('fetch')->where("openid='".$openid."'")->order('ScanId desc')->select();
        foreach ($list as $key => $value) {
             $list[$key]['FlowL']=round($list[$key]['FlowMl']/1000,1);
             if($value['FetchOpenid']!=''){
               $list[$key]['Mobile']=M('user')->where("openid='".$value['FetchOpenid']."'")->getfield('Mobile');
             }
        }
        $this->assign(compact('openid','MachId','state','list'));
        $this->display();

//--- 20171106 DV add save log
        $datax['OpenId'] = $openid;
        $datax['VisitPage']='fetchlog';
        $datax['VisitTmk'] = date('YmdHis');
        M('z_promo_log')->add($datax);
    }

    /*充水库*/
    public function paywater(){
        $openid=I('get.openid');
        $MachId=(int)I('get.MachId');
        $state=I('get.state');
        //取水包
        $list=M('goods')->order('sort asc')->select();
        $this->assign(compact('openid','MachId','list','state'));
        $this->display();
        
//--- 20171106 DV add save log
        $datax['OpenId'] = $openid;
        $datax['VisitPage']='bank';
        $datax['VisitTmk'] = date('YmdHis');
        M('z_promo_log')->add($datax);
    }

    /*订购生成唯一订单号*/
    public function build_paywater_no(){
        $orderId = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        $info = M('buywater')->where("orderId='".$orderId."'")->find();//检测是否存在
        (!empty($info)) && $orderId = $this->build_paywater_no();
        return $orderId;
    }

    public function paywater_save(){
        if(IS_POST){
                $Cart = D('Buywater');
                $openid= $_POST['openid'];
                $goodsId=$_POST['goodsId'];
                $orderId=$this->build_paywater_no(); //生成订单号
                $_POST['orderId']=$orderId;
                $GoodsInfo=M('goods')->where('GoodsId='.$goodsId)->find();
                $_POST['goodsName']=$GoodsInfo['goodsName'];
                $_POST['price']=$GoodsInfo['price'];
                $_POST['waterMl']=$GoodsInfo['waterMl'];
                $data = $Cart->create();
                if($data){
                        $id = $Cart->add();
                        if($id){
                            header("Content-Type:text/html;charset=utf-8");
                            ini_set('date.timezone','Asia/Shanghai');
                            //订单提交之后，开始调用微信支付接口
                            require_once "WxPay/lib/WxPay.Api.php";
                            require_once "WxPay/WxPay.JsApiPay.php";
                            require_once 'WxPay/log.php';
                            $logHandler= new \CLogFileHandler("WxPay/paywater_logs/".date('Y-m-d').'.log');
                            $log = \Log::Init($logHandler, 15);
                            $tools = new \JsApiPay();
                            //下单
                            $body='订购'.$GoodsInfo['goodsName'];
                            $attach='自来开水';
                            $out_trade_no=$orderId;
                            $total_fee=$GoodsInfo['price']*100;
                            $goods_tag='';
                            $notify_url='https://water.suanok.com/WxPay/paywater_notify.php';
                            $input = new \WxPayUnifiedOrder();
                            $input->SetBody($body);
                            $input->SetAttach($attach);
                            $input->SetOut_trade_no($out_trade_no);
                            $input->SetTotal_fee($total_fee);
                            $input->SetTime_start(date("YmdHis"));
                            $input->SetTime_expire(date("YmdHis", time() + 600));
                            $input->SetGoods_tag($goods_tag);
                            $input->SetNotify_url($notify_url);
                            $input->SetTrade_type("JSAPI");
                            $input->SetOpenid($openid);
                            $order = \WxPayApi::unifiedOrder($input);
                            $jsApiParameters = $tools->GetJsApiParameters($order);
                            echo $jsApiParameters;
                        } else {
                            echo 0;
                        }
                    } else {
                        $this->error($Cart->getError());
                }
        }
    }

    /*充钱包*/
    public function paymoney(){
        $openid=I('get.openid');
        $MachId=(int)I('get.MachId');
        $state=I('get.state');
        //取钱包
        $list=M('goodsmoney')->order('sort asc')->select();
        $this->assign(compact('openid','MachId','state','list'));
        $this->display();
        
//--- 20171106 DV add save log
        $datax['OpenId'] = $openid;
        $datax['VisitPage']='wallet';
        $datax['VisitTmk'] = date('YmdHis');
        M('z_promo_log')->add($datax);
    }

    /*钱包充值生成唯一订单号*/
    public function build_order_no(){
        $orderId = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        $info = M('moneylog')->where("orderId='".$orderId."'")->find();//检测是否存在
        (!empty($info)) && $orderId = $this->build_order_no();
        return $orderId;
    }

    public function paymoney_save(){
        if(IS_POST){
                $Cart = D('Moneylog');
                $openid= $_POST['openid'];
                $GoodsMoneyId=$_POST['GoodsMoneyId'];
                $money= $_POST['money'];
                $orderId=$this->build_order_no(); //生成订单号
                $_POST['orderId']=$orderId;
                //取出钱
                if($money>0){
                    $PayMoney=$money;
                    $_POST['paymoney']=$money;
                    $_POST['money']=$money;
                }else{
                    $MoneyInfo=M('goodsmoney')->where('GoodsMoneyId='.$GoodsMoneyId)->field('PayMoney,GetMoney')->find();
                    $PayMoney=$MoneyInfo['PayMoney'];
                    $_POST['paymoney']=$PayMoney;
                    $_POST['money']=$MoneyInfo['GetMoney'];
                }
                $data = $Cart->create();
                if($data){
                        $id = $Cart->add();
                        if($id){
                            header("Content-Type:text/html;charset=utf-8");
                            ini_set('date.timezone','Asia/Shanghai');
                            //订单提交之后，开始调用微信支付接口
                            require_once "WxPay/lib/WxPay.Api.php";
                            require_once "WxPay/WxPay.JsApiPay.php";
                            require_once 'WxPay/log.php';
                            $logHandler= new \CLogFileHandler("WxPay/paymoney_logs/".date('Y-m-d').'.log');
                            $log = \Log::Init($logHandler, 15);
                            $tools = new \JsApiPay();
                            //下单
                            $body='会员充值'.$PayMoney.'元';
                            $attach='自来开水';
                            $out_trade_no=$orderId;
                            $total_fee=$PayMoney*100;
                            $goods_tag='';
                            $notify_url='https://water.suanok.com/WxPay/paymoney_notify.php';
                            $input = new \WxPayUnifiedOrder();
                            $input->SetBody($body);
                            $input->SetAttach($attach);
                            $input->SetOut_trade_no($out_trade_no);
                            $input->SetTotal_fee($total_fee);
                            $input->SetTime_start(date("YmdHis"));
                            $input->SetTime_expire(date("YmdHis", time() + 600));
                            $input->SetGoods_tag($goods_tag);
                            $input->SetNotify_url($notify_url);
                            $input->SetTrade_type("JSAPI");
                            $input->SetOpenid($openid);
                            $order = \WxPayApi::unifiedOrder($input);
                            $jsApiParameters = $tools->GetJsApiParameters($order);
                            echo $jsApiParameters;
                        } else {
                            echo 0;
                        }
                    } else {
                        $this->error($Cart->getError());
                }
            }
    }


    public function edituserMobile(){
        $openid=trim(I('post.openid'));
        $BindMobile=trim(I('post.BindMobile'));

        //检测是否注册会员
        $chkuser=M('user')->where("Mobile='".$BindMobile."' and openid!='".$openid."'")->find();
        if($chkuser){
            echo 0;
        }else{
           
            $data['Mobile'] = $BindMobile;
            $reid=M('user')->where("openid='".$openid."'")->save($data);
            echo 'ok';
           
        }
    }

    /*共享帐号*/
    public function myshare(){
        $openid=I('get.openid');
        $MachId=(int)I('get.MachId');
        $state=I('get.state');
        if($MachId>0){
            $QrcodeId=M('qrcode')->where("QrcodeType='mach' and Parameter=".$state)->getfield('QrcodeId');
        }else{
            $QrcodeId=M('qrcode')->where("QrcodeType='adve' and Parameter=".$state)->getfield('QrcodeId');
        }
        $QrcodeImg='https://water.suanok.com/Uploads/qrcode/water_'.$QrcodeId.'.png';
        $list=M('Userbind')->where("openid='".$openid."'")->order('addtime desc')->select();
        $this->assign(compact('openid','MachId','state','QrcodeImg','list'));
        $this->display();
    }

    public function adduserbind(){
        $openid=trim(I('post.openid'));
        $BindMobile=trim(I('post.BindMobile'));
        //检测是否注册会员
        $chkuser=M('user')->where("Mobile='".$BindMobile."'")->find();
        if(!$chkuser){
            echo 0;
        }elseif($openid==$chkuser['openid']){
            echo 1;
        }else{
            //检测是否已经存在
            $chkuser2=M('Userbind')->where("BindMobile='".$BindMobile."'")->find();
            if(!$chkuser2){
                $Tab = D("Userbind"); //签到表
                $data['openid'] = $openid;
                $data['BindOpenid'] = $chkuser['openid'];
                $data['BindMobile'] = $chkuser['Mobile'];
                $reid=$Tab->add($data);
                echo 'ok';
            }else{
                echo 2; 
            }
        }
    }

    public function clearuserbind(){
        $openid=I('get.openid');
        $MachId=(int)I('get.MachId');
        $state=I('get.state');
        $UserBindId=I('get.UserBindId');
        $delid=M('Userbind')->where('UserBindId='.$UserBindId)->delete();
        if($delid>0){
        $this->redirect('/Home/index/msg/', array('msgType'=>'clearuserbind','openid'=>$openid,'MachId'=>$MachId,'state'=>$state));
        }
    }

    /*推荐有奖*/
    public function tjyj(){
        $openid=I('get.openid');
        $MachId=(int)I('get.MachId');
        $state=I('get.state');
        $this->assign(compact('openid','MachId','state'));
        $this->display();
    }
    /*水质检测*/
    public function waterchk(){
        $openid=I('get.openid');
        $MachId=(int)I('get.MachId');
        $state=I('get.state');
        if($MachId!=''){
            $info=M('mach')->where('MachId='.$MachId)->find();
            $address=M('fang')->where('FangId='.$info['FangId'])->getfield('Address');
            $this->assign(compact('openid','MachId','state','info','address'));
            $this->display();
        }else{
            $this->redirect('/Home/index/msg/', array('msgType'=>'waterchk','openid'=>$openid,'state'=>$state));
        }
    }
    /*用户帮助*/
    public function userhelp(){
        $openid=I('get.openid');
        $MachId=(int)I('get.MachId');
        $state=I('get.state');
        $list=M('website_content')->where('mid=3')->order('sort asc')->field('id,title')->select();
        $this->assign(compact('openid','MachId','state','list'));
        $this->display();
    }
    public function ajax_getContent(){
        $id=I('post.id');
        $content=M('website_content')->where('id='.$id)->field('title,content')->find();
        $this->ajaxReturn($content,'JSON'); 
    }

    /*赠品管理*/
    public function fangGift(){
       $openid=I('get.openid');
       $MachId=(int)I('get.MachId');
       $state=I('get.state');
       $keywords=I('get.keywords');

       //取出房东ID
       $FangId=M('fang')->where("openid='".$openid."'")->getfield('FangId');

       //取出机器ID
       /*$MachIdList=M('mach')->where('FangId='.$FangId)->select();
       foreach ($MachIdList as $key => $value) {
           $MachIdinfo.=$MachIdList[$key]['MachId'].',';
       }
       $MachIdinfo=substr($MachIdinfo,0,strlen($MachIdinfo)-1);*/

       $map['RegFangId']=array('eq',$FangId);
       $map['Mobile']=array('neq','');
       $map['openid']=array('neq',$openid);
       if($keywords!=''){
        $map['Mobile']=array('like','%'.$keywords.'%');
       }
       
       //取出用户
       $UserList=M('user')->where($map)->field('openid,Mobile,wxpay_prepay_id')->select();
       foreach ($UserList as $key => $value) {
           if($value['wxpay_prepay_id']!=''){
                $GiftType=M('fanggift')->where("UserOpenid='".$value['openid']."'")->getfield('GiftType');
                if($GiftType!=''){
                switch ($GiftType) {
                    case '1':
                        $gift="5升便捷式手提纯净水桶";
                        break;
                    case '2':
                        $gift="5升便携式手提折叠储水袋";
                        break;
                    case '3':
                        $gift="10升便携式手提折叠储水袋";
                        break;
                    case '4':
                        $gift="精美波纹玻璃水壶杯子套件装";
                        break;
                    
                }
                $UserList[$key]['gift']=$gift;
                }
           }
       }
       $this->assign(compact('openid','MachId','state','UserList','keywords','FangId'));
       $this->display();
      
			//--- 20171106 DV add save log
			$datax['OpenId'] = $openid;
			$datax['VisitPage']='fangGift';
			$datax['VisitTmk'] = date('YmdHis');
			M('z_promo_log')->add($datax);
    }

    public function fangGift_save(){
         if(IS_POST){
           //存入会员
           $FangId=I('post.FangId');
           $UserOpenid=I('post.UserOpenid');
           $UserMobile=I('post.UserMobile');
           $GiftType=I('post.GiftType');
           $userChk=M('fanggift')->where("UserOpenid='".$UserOpenid."'")->count();
           if($userChk==0){
                $data['FangId']=$FangId;
                $data['UserOpenid']=$UserOpenid;
                $data['UserMobile']=$UserMobile;
                $data['GiftType']=$GiftType;
                $data['addtime']=time();
                M('fanggift')->add($data);
            }else{
                $data['GiftType']=$GiftType;
                $data['addtime']=time();
                M('fanggift')->where("UserOpenid='".$UserOpenid."' and FangId=".$FangId)->save($data);
              
            }
            if($GiftType>0){
                echo 'success';
            }else{
                echo 'no';
            }
        }

				//--- 20171106 DV add save log
				$datax['OpenId'] = $openid;
				$datax['VisitPage']='fangGift_save';
				$datax['VisitTmk'] = date('YmdHis');
				M('z_promo_log')->add($datax);
    }

    /*房东收益*/
    public function fangMoney(){
       $openid=I('get.openid');
       $MachId=(int)I('get.MachId');
       $state=I('get.state');

       //判断是否房东
       $FangInfo=M('fang')->where("openid='".$openid."'")->find();

       $tenday=time()-3600*24*30;

       $sql="SELECT SUM(FangIncomeAmt) as money ,SUBSTRING(FangIncomeDat,1,8) as dat,FangIncomeType FROM  wr_fangincome where FangId=".$FangInfo['FangId']." and FangIncomeDatStamp>=".$tenday." GROUP BY SUBSTRING(FangIncomeDat,1,8),FangIncomeType order by FangIncomeDat desc";
       $list=M('fangincome')->query($sql);

       foreach ($list as $key => $value) {
           $list[$key]['dat']=substr($value['dat'],0,4).'-'.substr($value['dat'],4,2).'-'.substr($value['dat'],6,2);
           switch ($value['FangIncomeType']) {
               case '1':
                  $list[$key]['tips']='取水提成';
                  break;
               case '2':
                  $list[$key]['tips']='新会员奖金';
                  break;
               case '10':
                  $list[$key]['tips']='提现';
                  break;
               case '11':
                  $list[$key]['tips']='申请提现';
                  break;
           }

       }

      /* echo '<pre>';
       print_r($list);
       echo '</pre>';*/

       $this->assign(compact('openid','MachId','state','FangInfo','list'));
       $this->display();

			//--- 20171106 DV add save log
			$datax['OpenId'] = $openid;
			$datax['VisitPage']='fangMoney';
			$datax['VisitTmk'] = date('YmdHis');
			M('z_promo_log')->add($datax);
    }

    /*房东提现*/
    public function fangMoneyTx(){
        if(IS_POST){
           //存入会员
           $FangId=I('post.FangId');
           $FangIncomeAmt=I('post.FangIncomeAmt');

            $data['FangId']=$FangId;
            $data['FangIncomeDat']=date("YmdHis");
            $data['FangIncomeType']=11;
            $data['FangIncomeAmt']=-$FangIncomeAmt;
            $data['FangIncomeDatStamp']=time();
            M('fangincome')->add($data);
            echo 'success';
        }

        //--- 20171106 DV add save log
        $datax['OpenId'] = $openid;
        $datax['VisitPage']='fangMoneyTx';
        $datax['VisitTmk'] = date('YmdHis');
        M('z_promo_log')->add($datax);
    }

    /*新用户充值*/
    public function newuserpay(){
        $openid=I('get.openid'); //用户身份
        $MachId=I('get.MachId'); //机器ID
        $state=I('get.state');   //首次扫码参数
        if($openid==''){ //第一次进入
            $code=I('get.code');
            $state=I('get.state');
            $OAuth = A('Home/Weixin');
            $json=$OAuth->getOauthAccessToken(1,$code);
            $openid=trim($json['openid']);
            header("Location:".'/Home/index/newuserpay/?openid='.$openid); 
        }else{ //从其它页面转入
            $userInfo=M('user')->where("openid='".$openid."'")->find();
        }

         //取出最后一次扫码信息
        $RandString=M('scanlog')->where("openid='".$openid."'")->order('ScanlogId desc')->getfield('RandString'); 
        $qrcodeInfo=M('qrcode')->where("RandString='".$RandString."'")->find();
        switch ($qrcodeInfo['QrcodeType']) {
            case 'mach':
                $FangId=M('mach')->where('MachId='.$qrcodeInfo['Parameter'])->getfield('FangId');
                break;
            case 'adve':
                $FangId=M('adve')->where('AdveId='.$qrcodeInfo['Parameter'])->getfield('FangId');
                break;
        }

        $FangInfo=M('fang')->where('FangId='.$FangId)->find();

        $newUserGift=M('dzp_item')->where("dzpId=1 and dzpItemId=5")->field('newWater,newMoney')->find();
        $newUserGift['newWater']= $newUserGift['newWater']/1000;
        $this->assign(compact('openid','MachId','state','userInfo','newUserGift','FangInfo'));
        $this->display();

//--- 20171106 DV add save log
        $datax['OpenId'] = $openid;
        $datax['VisitPage']='g31';
        $datax['VisitTmk'] = date('YmdHis');
        M('z_promo_log')->add($datax);
    }

    /*订购新用户充值订单号*/
    public function build_newuserpay_no(){
        $orderId = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        $info = M('user')->where("orderId='".$orderId."'")->find();//检测是否存在
        (!empty($info)) && $orderId = $this->build_newuserpay_no();
        return $orderId;
    }
    public function newuserpay_save(){
        if(IS_POST){
                $openid= $_POST['openid'];
                $orderId=$this->build_newuserpay_no(); //生成订单号
                $data['orderId'] = $orderId;
                $reid=M('user')->where("openid='".$openid."'")->save($data);
                if($reid){
                            header("Content-Type:text/html;charset=utf-8");
                            ini_set('date.timezone','Asia/Shanghai');
                            //订单提交之后，开始调用微信支付接口
                            require_once "WxPay/lib/WxPay.Api.php";
                            require_once "WxPay/WxPay.JsApiPay.php";
                            require_once 'WxPay/log.php';
                            $logHandler= new \CLogFileHandler("WxPay/newuserpay_logs/".date('Y-m-d').'.log');
                            $log = \Log::Init($logHandler, 15);
                            $tools = new \JsApiPay();
                            //下单
                            $body='新用户充值礼包';
                            $attach='自来开水';
                            $out_trade_no=$orderId;
                            $total_fee=100;
                            $goods_tag='';
                            $notify_url='https://water.suanok.com/WxPay/newuserpay_notify.php';
                            $input = new \WxPayUnifiedOrder();
                            $input->SetBody($body);
                            $input->SetAttach($attach);
                            $input->SetOut_trade_no($out_trade_no);
                            $input->SetTotal_fee($total_fee);
                            $input->SetTime_start(date("YmdHis"));
                            $input->SetTime_expire(date("YmdHis", time() + 600));
                            $input->SetGoods_tag($goods_tag);
                            $input->SetNotify_url($notify_url);
                            $input->SetTrade_type("JSAPI");
                            $input->SetOpenid($openid);
                            $order = \WxPayApi::unifiedOrder($input);
                            $jsApiParameters = $tools->GetJsApiParameters($order);
                            echo $jsApiParameters;
                        
                    } else {
                        $this->error($Cart->getError());
                }
        } 
    }

    /*领取赠品*/
    public function usergift(){
        $openid=I('get.openid'); //用户身份
        $MachId=I('get.MachId'); //机器ID
        $state=I('get.state');   //首次扫码参数
        if($openid==''){ //第一次进入
            $code=I('get.code');
            $state=I('get.state');
            $OAuth = A('Home/Weixin');
            $json=$OAuth->getOauthAccessToken(1,$code);
            $openid=trim($json['openid']);
            header("Location:".'/Home/index/usergift/?openid='.$openid); 
        }else{ //从其它页面转入
            $userInfo=M('user')->where("openid='".$openid."'")->find();
        }

        //取出最后一次扫码信息
        $RandString=M('scanlog')->where("openid='".$openid."'")->order('ScanlogId desc')->getfield('RandString'); 
        $qrcodeInfo=M('qrcode')->where("RandString='".$RandString."'")->find();
        switch ($qrcodeInfo['QrcodeType']) {
            case 'mach':
                $FangId=M('mach')->where('MachId='.$qrcodeInfo['Parameter'])->getfield('FangId');
                break;
            case 'adve':
                $FangId=M('adve')->where('AdveId='.$qrcodeInfo['Parameter'])->getfield('FangId');
                break;
        }

        //领取赠品房东ID
        M('user')->where("openid='".$openid."'")->setField('RegFangId',$FangId);

        $FangInfo=M('fang')->where('FangId='.$FangId)->find();
        $this->assign(compact('openid','MachId','state','FangInfo'));
        $this->display();

//--- 20171106 DV add save log
        $datax['OpenId'] = $openid;
        $datax['VisitPage']='g21';
        $datax['VisitTmk'] = date('YmdHis');
        M('z_promo_log')->add($datax);
    }
    
    /*消息页 4个调用参数 MachId为可选项*/
    public function msg(){
        $msgType=I('get.msgType'); //消息类型
        $openid=I('get.openid');
        $state=I('get.state');
        $MachId=(int)I('get.MachId'); //机器ID
        if($MachId==''){$MachId=0;} //为避免传参被URL路由混淆，给不是扫机器码的赋值0
        switch ($msgType) {
            case 'dzpOver': //大转盘抽奖次数用完
            $msg = array('type' =>'info','title'=>'您的抽奖次数用光了','btnTxt'=>'返回','goUrl'=>'/Home/index/user/?openid='.$openid.'&MachId='.$MachId.'&state='.$state);
            break;
            case 'dzpCj': //大转盘有奖没有领取
            $dzpInfo=M('dzp_user')->where('openid="'.$openid.'" and state=0')->field('url')->find();
            $msg = array('type' =>'info','title'=>'您还有礼品没有领取','btnTxt'=>'马上领取','goUrl'=>$dzpInfo['url']);
            break;
            case 'userSign': //签到成功
            $msg = array('type' =>'info','title'=>'签到成功','btnTxt'=>'返回','goUrl'=>'/Home/index/user/?openid='.$openid.'&MachId='.$MachId.'&state='.$state);
            break;
            case 'userSignOver': //签到失败（今天已经签到)
            $msg = array('type' =>'info','title'=>'您今天已经签到','btnTxt'=>'返回','goUrl'=>'/Home/index/user/?openid='.$openid.'&MachId='.$MachId.'&state='.$state);
            break;
            case 'waterchk':
            $msg = array('type' =>'info','title'=>'扫描机器二维码才能检测水质','btnTxt'=>'返回','goUrl'=>'/Home/index/user/?openid='.$openid.'&MachId='.$MachId.'&state='.$state);
            break;
            case 'clearuserbind':
             $msg = array('type' =>'info','title'=>'解绑成功','btnTxt'=>'返回','goUrl'=>'/Home/index/myshare/?openid='.$openid.'&MachId='.$MachId.'&state='.$state);
            break;
            case 'fetchChk':
            $msg = array('type' =>'info','title'=>'机器正在取水，请稍候','btnTxt'=>'返回','goUrl'=>'/Home/index/user/?openid='.$openid.'&MachId='.$MachId.'&state='.$state);
            break;
            case 'getwaterChk':
            $msg = array('type' =>'info','title'=>'二维码已超时，请重新扫描二维码','btnTxt'=>'返回','goUrl'=>'','fuct'=>'scan');
            break;
            case 'qrcodeKill':
            $msg = array('type' =>'info','title'=>'二维码已失效，请重新扫描二维码','btnTxt'=>'返回','goUrl'=>'','fuct'=>'scan');
            break;
        }
        $this->assign(compact('msg','state'));
        $this->display('Public/msg');
    }

    //以下为插件

    /*大转盘*/
    public function dzp(){
        $dzpId=I('get.dzpId');
        $openid=I('get.openid');
        $state=I('get.state');
        $nettypeid=I('get.nettypeid');


        M('dzp')->where('dzpId='.$dzpId)->setInc('dzpCount',1); //更新抽奖次数
        $dzp=M('dzp')->where('dzpId='.$dzpId)->find();
        $dzpItem=M('dzp_item')->where('dzpId='.$dzpId)->select();
        $i=1;
        foreach ($dzpItem as $key => $value) {
            $alldzpItem.='"'.$dzpItem[$key]['title'].'",';
            if($i%2==0){
                $alldzpColor.='"#FFF4D6",';
            }else{
                $alldzpColor.='"#FFFFFF",';
            }
            $i++;
        }
        $alldzpItem=substr($alldzpItem,0,-1);   //奖项
        $alldzpColor=substr($alldzpColor,0,-1); //颜色
        //统计抽奖人次数
        $dzpUser=M('dzp_user')->where('dzpId='.$dzpId.' and openid="'.$openid.'"')->count();
        switch ($dzpUser) {
            case 0:
                $item=2;
                break;
            case 1:
                $item=3;
                break;
            case 2:
                //判断是否领奖
                $newuserpay=M('dzp_user')->where("openid='".$openid."' and dzpItemId=4 and state=1")->count();
                if($newuserpay>0){
                   $item=1; 
                }else{
                   $item=4; 
                }
                break;
        }
        $gameCount=$dzp['dzpNumber']-$dzpUser;
        if($gameCount>0){
            $this->assign(compact('openid','dzpId','dzp','dzpItem','alldzpItem','alldzpColor','item','gameCount','state','nettypeid'));
            $this->display('Plus/dzp');
        }else{
            $this->redirect('/Home/index/msg/', array('msgType'=>'dzpOver','openid'=>$openid,'state'=>$state));
        }
    }
    /*剩余抽奖次数*/
    public function game_count(){
        $dzpId=I('get.dzpId');
        $openid=I('get.openid');
        $dzp=M('dzp')->where('dzpId='.$dzpId)->find();
        $dzpUser=M('dzp_user')->where('dzpId='.$dzpId.' and openid="'.$openid.'"')->count();
        $gameCount=$dzp['dzpNumber']-$dzpUser;

        $Mobile=M('user')->where("openid='".$openid."'")->getfield('Mobile');
        if($Mobile==''&&$gameCount==1){
          echo 'notmobile';
//--- 20171106 DV add save log
					$tmplog='g22';
        }else{
          echo $gameCount;
//--- 20171106 DV add save log
					$tmplog='g'.($dzpUser+1).'0';
        }

//--- 20171106 DV add save log
        $datax['OpenId'] = $openid;
        $datax['VisitPage']=$tmplog;
        $datax['VisitTmk'] = date('YmdHis');
        M('z_promo_log')->add($datax);
    }

    /*获取当前抽奖项目*/
    public function dzp_count(){
        $openid=I('get.openid');
        $dzpId=I('get.dzpId');
        //统计抽奖人次数
        $dzpUser=M('dzp_user')->where('dzpId='.$dzpId.' and openid="'.$openid.'"')->count();
        switch ($dzpUser) {
            case 0:
                $item=2;
                break;
            case 1:
                $item=3;
                break;
            case 2:
                $item=4;
                break;
        }
        echo $item;
    }

    /*处理中奖信息*/
    public function save_dzp(){
        $openid=I('get.openid');
        $dzpId=I('get.dzpId');
        $title=I('get.title');
        $item=I('get.item');
        //中奖信息
        $dzpItem=M('dzp_item')->where("title='".$title."' and dzpId=".$dzpId)->field('dzpItemId,types,dzpNum,url')->find();
        //判断用户是否注册
        $userInfo=M('user')->where("openid='".$openid."'")->find();

        if(empty($userInfo)&&$item==2){
            //写会员表
            $data['openid']=$openid;
            $data['addtime']=time();
            $UserId=M('user')->add($data);
        }

        //存入中奖用户表
        $data['dzpId'] = $dzpId;
        $data['dzpItemId'] = $dzpItem['dzpItemId'];
        $data['title']=$title;
        $data['url']=$dzpItem['url'];
        $data['openid'] = $openid;
        $data['addtime'] = time();
        $dzpUserId=M('dzp_user')->add($data);
            //处理中奖后续
            switch ($dzpItem['types']) {
                    case 'water': //送水
                            $data2['types'] = 2;
                            $data2['openid'] = $openid;
                            $data2['goodsName']=$title;
                            $data2['waterMl'] = $dzpItem['dzpNum'];
                            $data2['addtime'] = time();
                            M('buywater')->add($data2);
                            M('dzp_user')-> where('dzpUserId='.$dzpUserId)->setField('state',1);
                            $restr='ok';
                    break;
                    case 'money': //送钱
                            $data2['types'] = 2;
                            $data2['openid'] = $openid;
                            $data2['money'] = $dzpItem['dzpNum'];
                            $data2['info'] = $title;
                            $data2['state'] = 1;
                            $data2['addtime'] = time();
                            M('dzp_user')-> where('dzpUserId='.$dzpUserId)->setField('state',1);
                            M('moneylog')->add($data2);
                            $restr='ok';
                    break;
                    case 'url': //处理url订单
                            echo $dzpItem['url'];
                    break;
                    case 'not': //没有奖
                            $restr='not';
                            M('dzp_user')-> where('dzpUserId='.$dzpUserId)->setField('state',1);
                    break;
            }
        
        echo $restr;
    }
    
}