<?php
/*
 * 愚子方提供解码
 * 联系QQ: 179210540
 * 仅提供学习使用
 */
defined('THINK_PATH') OR exit();
class OrderAction extends AliziAction {

    public function _initialize(){
        parent::_init();
    }

    public function index($id,$tpl='index'){
	    if(empty($id) || !ctype_alnum($id))$this->error(lang('error'));
		
		$ipcloak = $this->ipcloak($id);
		if($ipcloak['status']=='1'){
			$url = $ipcloak['url'];
			if(ctype_alnum($url)){
				$id = $url;
			}else{
				header('location:'.$url);exit;
				//echo $this->file_get_content_sstr($url);exit;
			}
		}
		global $info;
        $info  = M('Item')->where(array('sn'=>$id))->find();//$info  = getCache('Item',array('sn'=>$id));
		if(empty($info) || $info['is_delete']==1) $this->error(lang('empty_item'));
		
		if(!empty($info['redirect_url'])){
			header("location:".$info['redirect_url']);exit;
		}else{
			$domains= array_filter(explode("<br />",nl2br($this->aliziConfig['redirect_domains'])));

			if($_SERVER['HTTP_HOST']==$this->aliziConfig['main_domain'] && $tpl=='detail' && $domains){
				$redirect = trim($domains[array_rand($domains)].$_SERVER['REQUEST_URI']);
				header("location:".$redirect);exit;
			}
		}
		
        
        $template  = getCache('ItemTemplate',array('id'=>$info['id']),true);
        $template['extend'] = unserialize($template['extend']);
        $template['color'] = json_decode($template['color'],true);
        if(isset($_GET['theme'])) $template['template']=str_replace('-', '/', $_GET['theme']);
	

		if($tpl=='detail'){	
			$_GET['page'] = 'detail';
			$tpl = file_exists(TMPL_PATH.'Alizi/'.$template['template'].'/detail.html')?"Alizi/{$template['template']}/detail":'Order/detail';
        }else{
			$_GET['page'] = 'single';
			$info['content'] = "{[AliziOrder]}";
            $tpl = "Order/".$tpl;
        }
	
		$_GET['id'] = $id;
		
		import("Home.Alizi.AliziTags");
		$info = AliziTags::alizi($info);

		//加密内容	
		if($this->aliziConfig['is_encode']){
			$info['content'] = '<script tyle="text/javascript" src="'.$this->aliziHost.'Public/Alizi/seajs/alizi/base64.js?v='.ALIZI_VERSION.'"></script><script tyle="text/javascript">var content="Alizi'.base64_encode($info['content']).'";var b = new Base64();document.write(b.decode(content));</script>';
		}
		
		
		$this->assign('template',$template);
        $this->assign('info',$info);
    
        if(isset($_GET['buildHtml'])){
			$id = intval($_GET['uid'])<=1?$id:$id.'-'.$_GET['uid'];
			$html = $this->aliziHost.$this->aliziConfig['html_file'].$id.C('HTML_FILE_SUFFIX');
			$this->assign('thisUrl',$html);
			
            $this->buildHtml($id,$this->aliziConfig['html_file']?$this->aliziConfig['html_file']:'./',$tpl);
            header("location:".$html);
        }else{
			$html = $this->host.urlencode($_SERVER['REQUEST_URI']);
			$this->assign('thisUrl',$html);
			$this->display($tpl);
		}
    }

    public function aliziBooking(){
		$_POST = $_REQUEST;
		if(isset($_POST['name']))$_POST['name'] = strFilter($_POST['name']);
        $_POST['sign'] = createSign($_POST,C('ALIZI_KEY'));
		 
        $result = R('Api/aliziBooking',array('data'=>$_POST));

        $data  = array();
        if($result['status']==1){
            $data = array('order_id'=>$result['data']['order_id'],'order_no'=>$result['data']['order_no']);
        }
		
		if(isset($_REQUEST['callback'])){
			$ret = array('data'=>$data,'info'=>$result['message'],'status'=>$result['status']);
			$this->ajaxReturn($ret,'jsonp');exit;
		}
        if(IS_AJAX){
            $this->ajaxReturn($data,$result['message'],$result['status']);
        }else{
            if($result['status']==1){
                header("location:".U('Order/pay',array('order_no'=>$data['order_no'])));
            }else{
                $this->error($result['message']);
            }
        }
    }

    public function getAliziPrice(){
		$payment = explode('-',$_POST['payment']);
        $data = array(
            'sn'=>$_POST['sn'],
            'quantity'=>(int)$_POST['quantity'],
            'item_params'=>trim($_POST['params']),
            'payment'=>$payment[0],
        );
        $data['sign'] = createSign($data,C('ALIZI_KEY'));
        $result = R('Api/getAliziPrice',array('data'=>$data));
        $this->ajaxReturn($result,'success',1);
    }

    public function query(){
        if(IS_POST){
            $kw = strFilter($_POST['kw']);
            $Model = M('Order');
            $Item  = M('Item');
            $OrderLog = M('OrderLog');
            $status = C('ORDER_STATUS');
            $where = "mobile='{$kw}' OR order_no='{$kw}' OR name='{$kw}'";
            $orders = $Model->where($where)->order('id desc')->select();
	
            $list = array();
            if($orders){
                foreach($orders as $li){
                    $item_extends = json_decode($li['item_extends'],true);
                    $itemExtends = '';
                    foreach($item_extends as $k=>$v){$itemExtends.=$k.lang('colon').(is_array($v)?implode(' ', $v):$v)."<br>";}
					
					if($li['status']==3){
						$items = $Item->field('is_auto_send,send_content')->where(array('id'=>$li['item_id']))->find();
					}else{
						$items = array( 'is_auto_send'=>0, 'send_content'=>'', );
					}
                    $list[] = array(
                        'title'=>$li['item_name'],
                        'order_no'=>$li['order_no'],
                        'order_status'=>(int)$li['status'],
                        'status'=>strip_tags($status[$li['status']]),
                        'payment'=>$li['payment'],
                        'quantity'=>$li['quantity'],
                        'price'=>$li['total_price'],
                        'name'=>$li['name'],
                        'params'=>$li['item_params'],
                        'itemExtends'=>$itemExtends,
                        'datetime'=>substr($li['datetime'],0,10),

                        'address'=>$li['region'].$li['address'],
                        'time'=>date('Y-m-d H:i:s',$li['add_time']),
                        'express'=>experss($li['delivery_name'],$li['delivery_no']),
                        'qq'=>$li['qq'],
                        'is_auto_send'=>$items['is_auto_send'],
                        'send_content'=>nl2br($items['send_content']),
                    );
                }
            }
            if($list){
                $this->ajaxReturn(array('title'=>'query','list'=>$list),'true',1);
            }else{
                $this->ajaxReturn(array('title'=>'query','list'=>null),lang('empty'),0);
            }
        }else{
            $this->display();
        }
    }
    public function apply(){
        if(IS_POST){
            $order_no = strFilter($_POST['order_no']);
            $mobile = strFilter($_POST['mobile']);
            $Model = M('Order');
            $where = array('order_no'=>$order_no,'mobile'=>$mobile);
            $order = $Model->where($where)->field('id,status')->find();

            if(empty($order)){
                $msg = lang('empty');
            }else{
                switch($order['status']){
                    case '1':
                        $msg = lang('applySuccess');
                        $data = array(
                            'order_id'=>$order['id'],
                            'status'=>8,
                            'remark'=>htmlspecialchars($_POST['refund_payment'].' , '.$_POST['refund_account']),
                        );
                        $data['sign'] = createSign($data,C('ALIZI_KEY'));
                        $rs = http($this->aliziHost."index.php?m=Api&a=aliziUpdateStatus", 'POST', array('data'=>$data));
                        break;
                    case '8':$msg = lang('applyIn');break;
                    default: $msg = lang('status_err');
                }
            }
            $this->ajaxReturn(1,$msg,1);
        }else{
            $this->display();
        }
    }

    public function pay(){
        $order_no = strFilter($_GET['order_no']);
        $order = M('Order')->where(array('order_no'=>$order_no))->find();
        if($order['status']!=0){
            $this->redirect('Order/result',array('order_no'=>$order['order_no']));
        }
        $payment = isset($_GET['payment'])?$_GET['payment']:$order['payment'];
		$subpayment = explode('-',$payment);

		$redirectUrl = $order['url'];
		$options = json_decode($this->aliziConfig['order_options'],true);
		if(in_array($order['order_page'],array('single','detail'))){
			$template = M('ItemTemplate')->where(array('id'=>$order['item_id']))->field('redirect_uri,options')->find();
			if($template){
				$redirectUrl = $template['redirect_uri']=='1'?$order['referer']:$template['redirect_uri'];
				$options = json_decode($template['options'],true);
			}
		}
		$this->assign('redirectUrl',$redirectUrl);
				
        $this->assign('order',$order);
        switch ($subpayment[0]) {
            case 'alipay':
                $this->alipayInWx($order);
                $this->display('alipay');
				$this->payAlipay($order);
                break;
            case 'codepay':
				Vendor('codepay.codepay');
				$this->aliziConfig['notify_url'] = $this->aliziHost."Api/codepay.php";
				$this->aliziConfig['return_url'] = $this->aliziHost."index.php?m=Order&a=result&order_no={$order['order_no']}";
				$codepay = new codepay($this->aliziConfig);
				$pay = $codepay->create_order($order);
				
				$this->assign('pay',json_decode($pay,true));
				$this->assign('payJson',$pay);
				$this->display('codepay');
                break;
            case 'paypay':
				$api_url = 'https://www.paypayzhu.com/api/pay';
				$api_user = $this->aliziConfig['paypay_user'];
				$api_key = $this->aliziConfig['paypay_key'];
				// 从网页传入 type [1: 微信, 2: 支付宝]
				//$type = $this->aliziConfig['paypay_type'];
				$type = $subpayment[1];
				$price = $order['total_price'];
				$order_id = $order['order_no'];
				$order_info = trim($order['item_name']);
				// 用户支付成功之后, 跳转到的页面
				$redirect = $this->aliziHost."index.php?m=Order&a=result&order_no={$order['order_no']}";

				// 签名 
				$signature = md5($api_key. $api_user. $order_id. $order_info. $price. $redirect. $type);

				$pay['api_user'] = $api_user;
				$pay['price'] = $price;
				$pay['type'] = $type;
				$pay['redirect'] = $redirect;
				$pay['order_id'] = $order_id;
				$pay['order_info'] =$order_info;
				$pay['signature'] = $signature;
				//$pay = http( $api_url, 'POST',$ret);
				
				$this->assign('pay',$pay);
				$this->display('paypay');
                break;
            case 'wxpay':
                if(isWeixin()==true && in_array(2, json_decode($this->aliziConfig['wxpay_type'],true))){
                    $this->redirect('Order/payWxPayJsApi',array('order_id'=>$order['id']));exit;
                }elseif(isWeixin()==false && isMobile()==true && in_array(2, json_decode($this->aliziConfig['wxpay_type'],true)) ){
					$this->redirect('Order/payWxPayWap',array('order_id'=>$order['id']));exit;
				}else{
                    $result = R('Api/payWxpay',array('data'=>$order));
                    if($result['return_code']=='FAIL'){
                        $this->error($result['return_msg']);
                    }else{
                        $this->assign('result',$result);
                        $this->display('payWxpay');
                    }
                }
                break;
            case 'qrcode'://二维码
                $qrcode = R('Api/payQrcode',array('data'=>$order));
                $this->assign('qrcode',$qrcode);

                $this->display('payQrcode');
                break;
            case '7':
                $this->yunpay($order);
                break;
            case '8':
                $this->display('alipay');
                $link = M('Item')->where(array('id'=>$order['item_id']))->getField('link_pay_url');
                header('location:'.$link);exit;
                break;
			case '9':
				Vendor('aiyangPay.aiyangPay');
				$aiyang = new aiyangPay($this->aliziConfig['ay_partner'],$this->aliziConfig['ay_key']);
				$data = array(
					'type'=>1007,
					'total_price'=>$order['total_price'],
					'out_trade_no'=>$order['order_no'].'-'.time(),
					'notify_url'=>$this->aliziHost.'Api/aiyangpay.php',
					'return_url'=>$this->aliziHost.'Api/aiyangpayCallbak.php',
					'attach'=>$order['order_no'],
				);
				$payURl = $aiyang->getPayUrl($data);
				header('location:'.$payURl);exit;
			break;
			case 'creaditcard':
				$this->gleepay($order);
			break;
            default:$this->result($order);
        }
    }
	public function payAlipay($order){
		$this->assign('order',$order);
		$this->display('payAlipay');
        //R('Api/payAlipay',array('data'=>$order));
	}
	public function gleepay($order){
		Vendor('gleepay.gleepay');
		$Pay = new gleepay($this->aliziConfig);
		
		$card = json_decode($order['creditcard'],true);
		
		// Other Information
		$os = '';
		$brower = $Pay->getBrowser();
		$browerLang = $Pay->getBrowserLang();
		$ip = get_client_ip();
		$acceptLang = $_SERVER ['HTTP_ACCEPT_LANGUAGE'];
		$userAgent = $_SERVER ['HTTP_USER_AGENT'];
		$webSite = $_SERVER ['HTTP_HOST'];
		// set cookie
		$newCookie = 'billCountry=' . $order['country'];
		$newCookie .= '&email=' . $order['mail'];
		$newCookie .= '&timeZone=' . C('DEFAULT_TIMEZONE');
		$newCookie .= '&orderNo=' . $order ['order_no'];
		$newCookie .= '&lang=' . $browerLang;
		$newCookie .= '&ip=' . $ip;
		$oldCookie = '';
		if (isset ( $_COOKIE ['CARD_PAY_COOKIE'] )) {
			$oldCookie = $_COOKIE ['CARD_PAY_COOKIE'];
			$oldCookie = strlen ( $oldCookie ) > 1000 ? substr ( $oldCookie, 0, 1000 ) : $oldCookie;
		}
		$newCookie = $newCookie . (empty ( $oldCookie ) ? "" : '$$' . $oldCookie);
		$newCookie = strlen ( $newCookie ) > 1000 ? substr ( $newCookie, 0, 1000 ) : $newCookie;
		setcookie ( "CARD_PAY_COOKIE", $newCookie, time () + 21474836 );
		
		// Parameter combination encryption
		$signSrc = $this->aliziConfig['creditcard_mid'] . $this->aliziConfig['creditcard_gateway'] . $order['order_no'] . L('currency') . $order['total_price'] . $card['num'] . $card ['year'] . $card ['month'] . $card ['cvv'] .$this->aliziConfig['creditcard_key'];
		$signInfo = hash ( 'sha256', $signSrc );
		$goodsInfo = $order['item_name'].'#,#'.$order['item_id'].'#,#'.$order['item_price'].'#,#'.$order['quantity'];
		$country = L('default_country');
		
		$data = array (
			'merNo' => $this->aliziConfig['creditcard_mid'],
			'gatewayNo' => $this->aliziConfig['creditcard_gateway'],
			'orderNo' => $order ['order_no'],
			'orderAmount' => $order ['total_price'],
			'orderCurrency' => L('currency'),
			'shipFee' => $order ['shipping_pricee2'],
			'firstName' => mb_substr($order['name'],0,1,'utf-8'),
			'lastName' => mb_substr($order['name'],1,20,'utf-8'),
			'email' => $order ['mail'],
			'phone' => $order ['mobile'],
			'zip' => $order ['zcode'],
			'address' => $order ['address'],
			'city' => $order ['city'],
			'state' => $order ['province'],
			'country' => $country,
			'shipFirstName' => mb_substr($order['name'],0,1,'utf-8'),
			'shipLastName' => mb_substr($order['name'],1,20,'utf-8'),
			'shipPhone' => $order ['mobile'],
			'shipEmail' => $order ['mail'],
			'shipCountry' => $country,
			'shipState' => $order ['province'],
			'shipCity' => $order ['city'],
			'shipAddress' => $order ['address'],
			'shipZip' => $order ['zcode'],
			
			'returnUrl' => $this->aliziHost.'Api/gleepayCallbak.php',
			'notifyUrl' => $this->aliziHost.'Api/gleepay.php',
			'uniqueId' => session_id(),
		
			'signInfo' => $signInfo,
			'cardNo' => $card['num'],
			'cardSecurityCode' => $card ['cvv'],
			'cardExpireMonth' => $card ['month'],
			'cardExpireYear' => $card ['year'],
			'issuingBank' => '',
			'webSite' => $webSite,
			'ip' => $ip,
			'brower' => $brower,
			'browerLang' => $browerLang,
			'os' => $os,
			'timeZone' => C('DEFAULT_TIMEZONE'),
			'resolution' => '',
			'isCopyCard' => 0,
			'goodsInfo' => $Pay->string_replace ( $goodsInfo ),
			'oldCookie' => $Pay->string_replace ( $oldCookie ),
			'newCookie' => $Pay->string_replace ( $newCookie ),
			'acceptLang' => $Pay->string_replace ( $acceptLang ),
			'userAgent' => $Pay->string_replace ( $userAgent ),
			'remark' => $Pay->string_replace ( $order ['remark'] ) 
		);
		
		$result = $Pay->payment_submit ( $this->aliziConfig['creditcard_url'], http_build_query ( $data, '', '&' ) );
		$payXml = $Pay->xml_parser( $result );
		
		
		$redirectUrl = $order['url'];
        $options = json_decode($this->aliziConfig['order_options'],true);
        if(in_array($order['order_page'],array('single','detail'))){
            $template = M('ItemTemplate')->where(array('id'=>$order['item_id']))->field('redirect_uri,options')->find();
            if($template){
                if($template['redirect_uri']=='1' && !empty($order['referer'])){
                    $redirectUrl = $order['referer'];
                }elseif($template['redirect_uri']!='1' && !empty($template['redirect_uri'])){
                    $redirectUrl = $template['redirect_uri'];
                }
                $options = json_decode($template['options'],true);
            }
        }
        $this->assign('redirectUrl',$redirectUrl);
		
		//print_r($payXml);
		$this->assign('pay',$payXml);
		$this->assign('order',$order);
		$this->display('gleepay');
	}
    public function yunpay($order){

        $yun_config['partner'] = $this->aliziConfig['yunpay_pid'];//合作身份者id
        $yun_config['key'] = $this->aliziConfig['yunpay_key'];//安全检验码
        $seller_email = $this->aliziConfig['yunpay_email'];//云会员账户（邮箱）
        $GLOBALS['i2ekeys']=$yun_config['key'];
        Vendor('yunpay.lib.yun_md5#function');

        $out_trade_no = $order['order_no'];//商户网站订单系统中唯一订单号，必填
        $subject = $order['item_name'];//订单名称，必填
        $total_fee = $order['total_price'];//付款金额,必填 需为整数
        $body = $order['item_params'];//订单描述

        $nourl = $this->aliziHost.'Api/yunpay.php'; //服务器异步通知页面路径,需http://格式的完整路径,不能加参数
        $reurl = $this->aliziHost.'Api/yunpayCallbak.php';//页面跳转同步通知页面路径,需http://格式的完整路径，不能加?id=123这类自定义参数

        $orurl = '';
        //商品展示地址需http://格式的完整路径，不能加?id=123这类自定义参数，如原网站带有 参数请彩用伪静态或短网址解决
        $orimg = '';
        //商品形象图片地址 需http://格式的完整路径，必须为图片完整地址

        //构造要请求的参数数组，无需改动
        $parameter = array(
            "partner" => trim($yun_config['partner']),
            "seller_email"	=> $seller_email,
            "out_trade_no"	=> $out_trade_no,
            "subject"	=> $subject,
            "total_fee"	=> $total_fee,
            "body"	=> $body,
            "nourl"	=> $nourl,
            "reurl"	=> $reurl,
            "orurl"	=> $orurl,
            "orimg"	=> $orimg
        );
        //dump($parameter);exit;
        $html_text = i2e($parameter, "支付进行中...");
        echo $html_text;
    }
    public function payWxPayJsApi(){

        $order_id = intval($_GET['order_id']);
        $order = M('Order')->where(array('id'=>$order_id))->find();
        $redirectUrl = $this->aliziHost."index.php?m=Order&a=payWxPayJsApi&order_id={$order_id}";
        //$redirectUrl = $this->aliziHost."Api/wxPayJsApi.php?order_id={$order_id}";


        Vendor('wxPay.WxPay#JsApiPay');
        WxPayConfig::setConfig($this->aliziConfig);
        $JsApiPay = new JsApiPay();
        $openid = $JsApiPay->GetOpenid($redirectUrl);
        $total_price = $order['total_price']*100;//价格，单位为分
		$title = $order['item_params']?$order['item_params']:$order['item_name'];
		
        $input = new WxPayUnifiedOrder();
        $input->SetOpenid($openid);
        $input->SetBody($title);
        $input->SetOut_trade_no($order['order_no'].'-'.time());//$order['order_no']
        $input->SetTotal_fee($total_price);
        $input->SetProduct_id($order['item_id']);
        $input->SetAttach(L('aliziSystem'));
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag('Alizi'.$order['order_no']);
        $input->SetNotify_url($this->aliziHost."Api/wxPay.php");
        $input->SetTrade_type("JSAPI");

        $param = WxPayApi::unifiedOrder($input);

        if(empty($param)){
            $this->error('error');exit;
        }
        if($param['result_code']=='FAIL'){
            $this->error($param['err_code_des']);exit;
        }
        $wxPayRequest = $param?$JsApiPay->GetJsApiParameters($param):array();
        $this->assign('wxPayRequest',$wxPayRequest);
        $this->assign('order',$order);
        $this->assign('config',$this->aliziConfig);
        $this->display('Order:payWxPayJsApi');

    }
	 public function payWxPayWap(){

        $order_id = intval($_GET['order_id']);
        $order = M('Order')->where(array('id'=>$order_id))->find();
        $redirectUrl = $this->aliziHost."Api/payWxPayH5.php?order_id={$order_id}";


        Vendor('wxPay.WxPay#JsApiPay');
        WxPayConfig::setConfig($this->aliziConfig);
        $total_price = $order['total_price']*100;//价格，单位为分
		$title = $order['item_params']?$order['item_params']:$order['item_name'];
		
        $input = new WxPayUnifiedOrder();
        $input->SetBody($title);
        $input->SetOut_trade_no($order['order_no'].'-'.time());//$order['order_no']
        $input->SetTotal_fee($total_price);
        $input->SetProduct_id($order['item_id']);
        $input->SetAttach(L('aliziSystem'));
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 300));
        $input->SetGoods_tag('Alizi'.$order['order_no']);
        $input->SetNotify_url($this->aliziHost."Api/wxPay.php");
        $input->SetTrade_type("MWEB");
        $input->SetSpbill_create_ip(get_client_ip());

        $param = WxPayApi::unifiedOrder($input);
		//$mweb_url = $param['mweb_url'].'&redirect_url='.urlencode($this->aliziHost.'?m=Order&a=result&order_no=17091957052298');
        if(strtoupper($param['return_code'])=='FAIL'){
        	$this->error($param['return_msg'],U('Order/result',array('order_no'=>$order['order_no'])));exit;
        }else{
			//header("location:".$param['mweb_url']);
			$this->assign('order',$order);
			$this->assign('pay',$param);
			$this->display('payWxPayWap');
        }
    }

    public function result($order=array()){
		
		$order_no = strFilter($_GET['order_no']);
        if(empty($order) && isset($_GET['order_no'])){
            $order = M('Order')->where(array('order_no'=>$order_no))->find();
        }

        //优惠券支付成功提示页面
        if(isset($_GET['order_no']) && strstr($order_no,'_')){
            $this->display('UserWap/paySuccess');exit;
        }

        $redirectUrl = $order['url'];
        $options = json_decode($this->aliziConfig['order_options'],true);

        if(in_array($order['order_page'],array('single','detail'))){
            $template = M('ItemTemplate')->where(array('id'=>$order['item_id']))->field('redirect_uri,options')->find();
            if($template){
                if($template['redirect_uri']=='1' && !empty($order['referer'])){
                    $redirectUrl = $order['referer'];
                }elseif($template['redirect_uri']!='1' && !empty($template['redirect_uri'])){
                    $redirectUrl = $template['redirect_uri'];
                }
                $options = json_decode($template['options'],true);
            }
        }

        foreach($options as $k=>$opt){ if(in_array($opt, array('salenum'))) unset($options[$k]); }
        $this->assign('options',$options);
        $this->assign('order',$order);
        $this->assign('redirectUrl',$redirectUrl);
        $this->display('result');
    }
    private function alipayInWx($data){
        if(isWeixin()==true){
            $this->assign('info',$data);
            $this->display('Order:payInWx');exit;
        }
    }
    //订单轮询
    public function orderQuery($order_no){
		$order_no = strFilter($order_no);
        if(strstr($order_no,'_')){
            $no = explode('_',$order_no);
            $status = M('User')->where(array('id'=>$no[0]))->getField('status');
            $this->ajaxReturn(null,null,(int)$status);
        }
        $status = M('Order')->where(array('order_no'=>$order_no))->getField('status');
        $this->ajaxReturn(null,null,(int)$status);
    }

    public function getComments(){
        if(IS_POST){
            $Model = M('Comments');
            $item_id = intval($_POST['item_id']);
            $currentPage = intval($_POST['currentPage']);
            $page = intval($_POST['page']);
            $order = isset($_POST['order'])?trim($_POST['order']):'id DESC';

            $where = array('item_id'=>$item_id,'status'=>1);
            $total = $Model->where($where)->count();
            $list = $Model->where($where)->limit($currentPage,$page)->order($order)->select();

            $count = count($list);
            $data = array(
                'list'=>$list,
                'currentPage'=>$currentPage+$count,
                'leftPage'=>$total-$currentPage-$count,
            );
            $this->ajaxReturn($data,1,1);
        }
    }
    public function comment(){
        if(IS_POST){
            $item_id = intval($_POST['item_id']);
            $name = strip_tags(trim($_POST['name']));
            $mobile = strip_tags(trim($_POST['mobile']));
            $content = strip_tags(trim($_POST['content']));
		
            if(empty($name) || mb_strlen($name,'utf-8')>5){  $this->ajaxReturn('name',lang('invalid_realname'),0);  }
            if(empty($mobile)){  $this->ajaxReturn('mobile',lang('invalid_mobile'),0);  }
            if(empty($content)){  $this->ajaxReturn('content',lang('content_notempty'),0); }
			
			
			$where = array('item_id'=>$item_id,'mobile'=>$mobile);
			$order = M('Order')->where(array_merge($where,array('status'=>array('EGT',1))))->field('id,province')->find();
			if(empty($order)){
				$this->ajaxReturn('mobile',lang('commentErrorMessage'),0);
			}
			
			if(empty($order['province'])){
				$str = http("http://ip.taobao.com/service/getIpInfo.php?ip=".get_client_ip());
				$json = json_decode($str,true);
				$address = $json['data']['region'];
			}else{
				$address = $order['province'];
			}
			
			$Comments = M('Comments');
			$count   = $Comments->where($where)->count();
			if($count>=5){
				$this->ajaxReturn('mobile',lang('TooMuchComment'),0);
			}
            $data = array(
                'item_id'=>$item_id,
                'status'=>0,
                'mobile'=>$mobile,
                'region'=>$address,
                'name'=>$name,
                'content'=>$content,
                'add_time'=>date('Y-m-d'),
            );
            $Comments->add($data);
            $this->ajaxReturn(1,lang('submit_success'),1);
        }
    }
    public function getCode(){
        $item_id = intval($_POST['item_id']);
        $mobile = strFilter($_POST['mobile']);
        $verify = $_POST['verify'];
        $page = $_POST['page'];

        if(isMobileNum($mobile)==false){  $this->error(lang('pleaseInputMobile'));}
        if(in_array($page,array('single','detail'))){
            $options = M('ItemTemplate')->where(array('id'=>$item_id))->getField('options');
        }else{
            $options = $this->aliziConfig['order_options'];
        }
        $optionArr = json_decode($options,true);

        if(in_array('verify',$optionArr)){
            if(empty($verify)){ $this->error(lang('pleaseInputCode'));}
            if(md5($verify)!=$_SESSION['verify']){  $this->error(lang('invalid_verify'));}
        }
        $code = randCode(4);

		$rs = parent::send_sms($mobile,sprintf(L('smsCodeContent'),$code));
	
        if(strtolower($rs['status'])=='1'){
            $data = array(
                'item_id'=>$item_id,
                'mobile'=>$mobile,
                'code'=>$code,
                'type'=>1,
                'status'=>0,
                'add_time'=>time(),
            );
            $flag = M('Code')->add($data);
			$this->success(lang('send_success'));
        }else{
			$this->error(lang('send_failure_colon'));
        }
    }
	 
    public function wx(){
		if($this->aliziConfig['weixin_status']){
			$url = urldecode(trim($_GET['url']));
			Vendor('wxShare.jssdk');
			$jssdk = new JSSDK($this->aliziConfig['weixin_appid'], $this->aliziConfig['weixin_appsecret']);
			$signPackage = $jssdk->GetSignPackage($url);
			echo json_encode($signPackage);
		}
    }
	
	public function ipcloak($id){
		$purchase_url = M('Item')->where(array('sn'=>$id))->getField('purchase_url');
		if(empty($purchase_url)){ 
			return array('status'=>0,'url'=>$purchase_url);
		}
		if(C('DEFAULT_LANG') == 'zh-cn'){
			return array('status'=>1,'url'=>$purchase_url);
		}else if(empty($this->aliziConfig['ipcloak_status']) || empty($this->aliziConfig['ipcloak_username']) || empty($this->aliziConfig['ipcloak_password']) || empty($this->aliziConfig['ipcloak_countries'])){
			return array('status'=>0,'url'=>$purchase_url);
		}
		
		if(isset($_COOKIE['ip_token'])){
			$status = ($_COOKIE['ip_token']=='AliziIpcloak')? true: false;
		}else{
			// 获取IP地址	
			if (isset($_SERVER['HTTP_CF_CONNECTING_IP'])) {     //使用cloudflare 转发的IP地址
				$ip = $_SERVER['HTTP_CF_CONNECTING_IP'];
			} else {
				if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
					$ip = getenv('HTTP_CLIENT_IP');
				} elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
					$ip = getenv('HTTP_X_FORWARDED_FOR');
				} elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
					$ip = getenv('REMOTE_ADDR');
				} elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
					$ip = $_SERVER['REMOTE_ADDR'];
				}
			}
				
			$postData = array();
			$postData['username'] = $this->aliziConfig['ipcloak_username'];//"1394368940"; //您的接口用户名
			$postData['password'] = $this->aliziConfig['ipcloak_password'];//'cMHh0a3JjKT7dfSI'; //您的接口密码
			$postData['ip'] = $ip; // 当前客户的IP地址，下面的参数可以在文件里手动传输，也可以在ipcloak后台配置，可以根据自己的需求选择使用。
			$postData['ads_countries'] = $this->aliziConfig['ipcloak_countries']; //US+CA+GB 打广告的国家代码(美国，加拿大，英国)，多个国家代码之间用+号连接，为空表示不判断此项条件，所有国家将可以访问您的FP。国家代码参见：http://www.ipcloak.com/country_code.html	                                         	                                         
			$postData['ban_countries'] = ''; // 如果上面打广告的国家参数填写了，这里就不能够填写，2者只能够填写1者。除非有十足的把握知道想要屏蔽哪些国家，否则不建议使用该参数。                          
			$postData['site'] = isset($_SERVER['HTTP_X_FORWARDED_HOST']) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '');
			$postData['site_call_page'] = $_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].((isset($_SERVER['QUERY_STRING'])&&!empty($_SERVER['QUERY_STRING']))?('?'.$_SERVER['QUERY_STRING']):'');
			
			$ch = curl_init('https://www.ipcloakads.com/api/');				
			
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
			curl_setopt($ch, CURLOPT_REFERER, isset($_SERVER['HTTP_REFERER'])?$_SERVER['HTTP_REFERER']:'');
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  // 关闭SSL验证, 如果测试接口返回数据为null， 请去掉此行和下面一行代码前面的注释
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
			
			$return = curl_exec($ch);
			curl_close($ch);
			$result = json_decode($return, true); // json数据解码成数组	
			//var_dump($result); exit; // 调试语句，如果你对接好以后，发现我们的后台没有日志，你就去掉这句代码前面的双斜杠，然后清楚浏览器cookie，重新打开你的网站试试，如果浏览器有信息输出，则接口工作正常。
			$status = $result['status']; // 切记，切记，切记，接口返回【0】表示此IP不是你想要的客户，应该看到ZP，返回【1】表示此IP是你想要的客户，可以看到FP。
			
			// 设置cookie   
			setcookie('ip_token', ($status ? 'AliziIpcloak' : '123456789'), time() + 60 * 60 * 24 * 180, '/', '', false);
		}


		// 如果IP通过我们的审核了则显示指定页面的内容, 重要的事情说三遍，一定要先正后仿！！！先显示正品，IP通过我们接口审核后再显示仿品，不能搞错了顺序，否则网站会挂掉。
		if($status){
			if(!empty($result['jump_fp_url'])){ // 如果在后台配置域名的时候填写了跳转地址
				
				$purchase_url = $result['jump_fp_url'];
				//echo file_get_content_sstr($result['jump_fp_url']); // $result['jump_fp_url']是您在我们的后台账户->域名设置里填写的跳转地址		
				// header("Location:".$result['jump_fp_url']); // 上面一句代码表示抓取网页内容，如果速度很慢，或者版面乱了，请注释上面一句，使用此行的header函数强制跳转到指定网页
				
			}else{ // 如果后台没有设置该域名的跳转地址，则直接手动在下面写
				//echo file_get_content_sstr($jump_fp_url); 
				// 如果你后台没有填写跳转网址，就要在这里手动输入跳转到的网址, 我这里暂时用百度的网址替代了。
				// header("Location:冒号后面填写你要跳转到的仿品页面链接"); // 跨域名抓取部分网站时会有显示排版错乱的问题，请改用header函数强制跳转
			}
			//exit;
		}
		return array('status'=>$status,'url'=>$purchase_url);
		
	} 

}