<?php
/** App登录控制器
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaoq <xiaoq@570035208.com>
 */

namespace App\Controller;
class AjaxController extends BaseController {
	public function _initialize(){
        parent::_initialize ();
    }
	/**
	 * 发信息
	 */
	public function sendsms(){
		$param=I('param.');
		$model=D("Common/Ajax");
		$param['unverify'] = 1;
		$result=$model->sendsms($param);
		//转化为app返回数据统一格式
		if($result['status']!=1){
			$result['status']=3;
			$this->ajaxReturn($result);
		}
		$this->ajaxReturn($result);
	}
	/**
	 * 上传图片
	 */
    public function upload(){
        $upload = new \Think\Upload(); // 实例化上传类
        $upload->maxSize = C('UPLOAD_MAXSIZE')*1024*1024; // 设置附件上传大小
        $upload->exts = array('jpg', 'gif', 'png', 'jpeg'); // 设置附件上传类型
        $upload->rootPath = C('UPLOAD_PATH'); // 设置附件上传根目录
        $upload->savePath = 'image/'; // 设置附件上传（子）目录
        // 采用GUID序列命名
        $upload->saveName = md5();
        // 上传文件
        $info = $upload->upload();
        if (!$info) {// 上传错误提示错误信息
            $res['status'] =3;
            $res['msg'] =$upload->getError();
            $this->ajaxReturn($res);
        } else {// 上传成功
            $imgurl=str_exists($info['pic']['filename'],'http')?$info['pic']['filename']: __ROOT__.'/'.$info['pic']['filename'];
            //$imgurl=__ROOT__.'/'.$upload->rootPath. $info["pic"]["savepath"] . $info["pic"]["savename"];
            $res['status'] =1;
            $res['data'] =$imgurl;
            $this->ajaxReturn($res);
        }
        
    }

    /**
	 * 获取网站配置参数
	 */
    public function getconfig(){
        $return['status'] = 1;
        $return['data']['CONTENT_SEARCH'] = C('CONTENT_SEARCH')?explode(',',C('CONTENT_SEARCH')):'';//热门搜索关键字
        $return['data']['WEB_SITE_PHONE'] = C('WEB_SITE_PHONE');//客服电话
        $return['data']['WEB_SITE_QQ'] = C('WEB_SITE_QQ');//客服QQ
        //自定义添加
        $this->ajaxReturn($return);
    }
    /**
     * 更新微信配置参数
     */
    public function save_wx(){
        $post = I('post.');
        $data_k = array('wx_account','wx_appid','wx_appsecret','wx_type');
        for ($i=0; $i < count($data_k); $i++) {
            $map = array();
            $map['name'] = $data_k[$i];
            $data = M('Config')->where($map)->setField('value', $post[$data_k[$i]]);
        }
        $map = array();
        $map['name'] = 'wx_token';
        $wx_token = M('Config')->where($map)->field('value')->find();
        $wx_token = $wx_token['value'];
        if(!$wx_token){
            $wx_token = randStr(8,'1234567890');
            M('Config')->where($map)->setField('value',$wx_token);
        }
        if(!empty($post['verify_name']) && ($data || $data == 0)){
            $verify_name=$post['verify_name'];
            if(strlen($verify_name)!=16 || empty($verify_name)){
                $return['status'] =3;
                $return['msg'] = '配置成功,权限文件名错误';
            }
            $file_name='MP_verify_'.$verify_name.'.txt';
            if(file_exists($file_name)){
                $return['status'] =3;
                $return['msg'] = '配置成功,权限文件已存在';
            }
            file_put_contents($file_name,$verify_name);
            if(file_exists($file_name)){
                $return['verify_name'] =$verify_name;
            }else{
                $return['verify_name'] =0;
            }
            $return['status'] =1;
            $return['wx_token'] =$wx_token;
            $return['url'] = U('Home/Weixin/index','','html',true);        
        }else if($data || $data == 0){
            $return['status'] =1;
            $return['wx_token'] =$wx_token;
            $return['url'] = U('Home/Weixin/index','','html',true);
            $return['msg'] = '配置成功';
        }else{
            $return['status'] =3;
            $return['msg'] = '配置失败';
        }
        $this->ajaxReturn($return);
    }
    /**
    *微信配置数据
    */ 
    public function update_config_data(){
        $check = check_use_auth('WeChatMarket');
        if($check['status'] == 1){
            $data_k = array('wx_account','wx_appid','wx_appsecret','wx_type','wx_token');
            for ($i=0; $i < count($data_k); $i++) { 
                $map = array();
                $map['name'] = $data_k[$i];
                $data[$data_k[$i]] = M('Config')->where($map)->getfield('value');
            }
            $data['url'] = U('Home/Weixin/index','','html',true);
            if($data){
                $return['status'] =1;
                $return['data'] = $data;
            }else{
                $return['status'] =3;
            }
        }else{
            $return['status'] = 3;
            $return['msg']=$check['msg'];
            $return['url']=$check['url'];
        }
        $this->ajaxReturn($return);
    }
    /**
    *微信第一次关注
    */
    public function config_guan(){
        $postdata = I('post.');
        $WxFirst = M('WxFirst');
        $info=$WxFirst->field(true)->find();
        if($postdata){
            $data['keyword'] = $postdata['keyword'];
            $data['content'] = $postdata['content'];
            if($info){//更新
                $map = array();
                $map['id'] = $info['id'];
                $wxfirst = $WxFirst->where($map)->save($data);
            }else{
                $wxfirst = $WxFirst->add($data);
            }
            if($wxfirst || $wxfirst == 0){
                $return['status'] = 1;
                $return['msg'] = '更新成功';
            }else{
                $return['status'] = 3;
                $return['msg'] = '更新失败';
            }
        }else{
            if($info){
                $return['status'] = 1;
                $return['data'] = $info;
            }else{
                $return['status'] = 3;
            }
        }
        $this->ajaxReturn($return);
    }
    /**
	 * 获取定位信息
	 */
    public function resetlocation(){
        $param=I('param.');
        $return = array('status'=>3,'msg'=>'定位失败');
        if(empty($param['lat'])||empty($param['lon'])){
            $this->ajaxReturn($return);
        }
        $url='http://api.map.baidu.com/geocoder/v2/?ak=TXDl6KnzoMR8TaQ1t5Vao8D3&callback=renderReverse&location='.$param['lat'].','.$param['lon'].'&output=json&pois=0';
        $result=curlget($url);
        $result=strtr($result,array('renderReverse&&renderReverse('=>'',')'=>''));
        $result=json_decode($result,true);
        $city=$result['result']['addressComponent']['city'];
        $district=$result['result']['addressComponent']['district'];
        $cityreplace=array('市'=>'','自治区'=>'');
        if(strlen($city)>8)$city=strtr($city,$cityreplace);
        $map=array();
        $map['status']=1;
        $area=M('Area')->where($map)->field('id,pid,name')->cache(true)->select();
        foreach($area as $val){
            if($val['pid']==1){
                $sheng[] = $val['id'];
                $shengitem[$val['id']] = $val['name'];
            }
        }
        foreach($area as $k=>$v){
            if(in_array($v['pid'],$sheng)){
                if(str_exists($v['name'],$city)){
                    $regresult['province']['i']=$v['pid'];
                    $regresult['province']['n']=$shengitem[$v['pid']];
                    $regresult['city']['i']=$v['id'];
                    $regresult['city']['n']=strlen($v['name'])>8?strtr($v['name'],$cityreplace):$v['name'];
                    foreach($area as $key=>$val){
                        if($val['pid']==$v['id']&&str_exists($val['name'],$district)){
                            $regresult['district']['i']=$val['id'];
                            $regresult['district']['n']=$val['name'];
                            break;
                        }
                    }      
                    $return['status']=1;
                    $return['msg']='定位成功';
                    $return['data']=$regresult;
                    $this->ajaxReturn($return);                    
                }
            }else unset($area[$k]);
        }   
        $this->ajaxReturn($return);
    }
    /**
     * 门店列表
     */
    public function Shops(){
        $get = I('param.location_id_list');
        $map = array();
        $map['status'] = 1;
        $data = M('Shops')->where($map)->field('id,name,poi_id')->select();
        if($get){
            $location_id_list = explode(',',$get);        
            foreach ($data as $k => $v) {
                if($v['id'] && in_array($v['id'],$location_id_list)){
                    $data[$k]['location_id'] = '1';
                }else{
                    $data[$k]['location_id'] = '0';
                }
            }
        }
        if($data){
            $return['status']=1;
            $return['msg']='获取成功';
            $return['data']=$data;
            $return['get'] = $get;
        }else{
            $return['status']=3;
            $return['msg']='获取失败';
        }
        $this->ajaxReturn($return);
    }
    /**
     * 添加会员卡
     */
    public function add_card(){
        $postdata = I('post.');
        $map = array();
        if($postdata['location_id_list']){
            $map['status'] = 1;
            $map['id'] = array('in',$postdata['location_id_list']);
            $data = M('Shops')->where($map)->field('poi_id')->select();
            foreach ($data as $k => $v) {
                $location_id_list[] = $v['poi_id'];
            }
            $postdata['location_id_lists']=implode(',',$location_id_list);
        }
        $postdata['brand_name'] = C('WEB_SITE_NAME');
        // $postdata['location_id_list'] = json_decode(htmlspecialchars_decode($postdata['location_id_list']),true);
        $Weixin = new \Common\Vendor\WeixinCard();
        // 添加会员卡
        $add_coupon = $Weixin->add_coupon($postdata);
        $return['data'] = $add_coupon;
        if($add_coupon['status'] == 1){
            $return['status'] = 1;
            $return['msg']=$add_coupon['msg'];
        }else{
            $return['status'] = 3;
            $return['msg']=$add_coupon['msg'];
        }
        $this->ajaxReturn($return);
    }
    /**
     * 修改会员卡
     */
    public function card_update(){
        $postdata = I('post.');
        if($postdata['location_id_list']){
            $map = array();
            $map['status'] = 1;
            $map['id'] = array('in',$postdata['location_id_list']);
            $data = M('Shops')->where($map)->field('poi_id')->select();
            foreach ($data as $k => $v) {
                $location_id_list[] = $v['poi_id'];
            }
            $postdata['location_id_lists']=implode(',',$location_id_list);
        }
        $postdata['brand_name'] = C('WEB_SITE_NAME');
        // $postdata['location_id_list'] = json_decode(htmlspecialchars_decode($postdata['location_id_list']),true);
        $Weixin = new \Common\Vendor\WeixinCard();
        // 添加会员卡
        $add_coupon = $Weixin->card_update($postdata);
        if($add_coupon['status'] == 1){
            $return['status'] = 1;
            $return['msg']=$add_coupon['msg'];
            $return['data']=$add_coupon;
        }else{
            $return['status'] = 3;
            $return['msg']=$add_coupon['msg'];
        }
        $this->ajaxReturn($return);
    }
    // 微信分享url
    public function share_url(){
        $id = I('post.id');
        $check = check_use_auth('WeChatMarket');
        if($check['status'] == 1){
            $url = $_SERVER['HTTP_HOST'].U('Mobile/index/share',array('id'=>$id));
            $return['status'] = 1;
            $return['data']=$url;
        }else{
            $return['status'] = 3;
            $return['msg'] = '优惠券未同步微信卡券';
        }
        $this->ajaxReturn($return);
    }
    // 判断会员卡是否存在
    public function is_upd_card(){
        $res = M('Config')->field('value')->where("name='WX_CARD'")->find();
        if($res['value']){
            $val = unserialize($res['value']);
            $val['is_show'] = intval($val['is_show']);
            $val['location_id_lists'] = explode(',',$val['location_id_list']);
            $return['status'] = 1;
            $return['data'] = $val;
        }else{
            $return['status'] = 3;
        }
        $this->ajaxReturn($return);
    }
    // 更新优惠券
    public function update_card(){
        $postdata=I('post.');
        $Weixin = new \Common\Vendor\WeixinCoupon();
        if($postdata['card_id']){
            $get_coupon = $Weixin->get_coupon($postdata['card_id']);
            if($get_coupon['errmsg'] !== 'ok'){
                $return['status'] = 3;
                $return['msg'] = '优惠券ID不存在！';
                $this->ajaxReturn($return);
            }
        }
        $card_id = $postdata['card_id'];
        if($postdata['location_id_list']){
            $map = array();
            $map['status'] = 1;
            $map['id'] = array('in',$postdata['location_id_list']);
            $data = M('Shops')->where($map)->field('poi_id')->select();
            foreach ($data as $k => $v) {
                $location_id_list[] = $v['poi_id'];
            }
            $postdata['location_id_lists']=implode(',',$location_id_list);
        }
        $card = $Weixin->update_coupon($postdata["rank_id"],$postdata,$card_id);
        $return['data'] = $card;
        if($card['status'] == 1){
            $return['status'] = 1;
            $return['msg'] = '编辑成功!';
        }else{
            $return['status'] = 3;
            $return['msg'] = '编辑失败!';
        }
        $this->ajaxReturn($return);
    }
    // 判断优惠券是否是修改
    public function update_coupon_data(){
        $id = I('post.id');
        $map = array();
        $map['id'] = $id;
        $data = M('Coupons')->where($map)->field(true)->find();
        $data['begin_timestamp'] = date('Y-m-d h:i:s',$data['begin_timestamp']);
        $data['end_timestamp'] = date('Y-m-d h:i:s',$data['end_timestamp']);
        if($data['is_show'] == 1){
            $map = array();
            $map['id'] = array('in',$data['location_id_list']);
            $data['shop'] = M('Shops')->where($map)->field('id,name,poi_id')->select();
        }         
        if($data){
            $return['status'] = 1;
            $return['data'] = $data;
        }else{
            $return['status'] = 3;
            $return['msg'] = '该优惠券不存在';
        }
        $this->ajaxReturn($return);
    }
    // 优惠券二维码
    public function create(){
        $check = check_use_auth('WeChatMarket');
        if($check['status'] == 1){
            $card_id = I('post.card_id');
            $Weixin = new \Common\Vendor\WeixinCoupon();
            $create = $Weixin->create($card_id);
            if($create['status'] == 1){
                $return['status'] = 1;
                $return['data'] = $create;
            }else{
                $return['status'] = 3;
                $return['msg'] = '生成二维码失败';
            }
        }else{
            $return['status'] = 3;
            $return['msg']=$check['msg'];
            $return['url']=$check['url'];
        }
        $this->ajaxReturn($return);
    }
    // 会员卡详情
    public function particulars(){
        $return['status'] = 1;
        $status = I('param.');
        if($status['status'] == 1){
            $return = D('Member')->integral_reward();
        }elseif($status['status'] == 2){
            $return = D('Member')->grade_list();
        }elseif($status['status'] == 3){
            $return = D('Member')->many_points();
        }
        $this->ajaxReturn($return);
    }
    /**
     * 优惠券列表
     */
    public function list_coupon(){
        $is_type = I('get.id');
        $map = array();
        if($is_type == 2){//进行中
            $map['_string'] = 'type = 2 or (type = 1 and end_timestamp > '.NOW_TIME.' and begin_timestamp <'.NOW_TIME.')';
        }elseif($is_type == 3){//未开始
            $map['_string'] = 'type = 1 and begin_timestamp > '.NOW_TIME.'';
        }elseif($is_type == 4){//已结束
            $map['_string'] = 'type = 1 and end_timestamp < '.NOW_TIME.'';  
        }
        $map['status'] = 0;
        $map['coupons_type'] = 1;  
        $info=M('Coupons')->where($map)->order('id desc')->field(true)->select();
        foreach ($info as $k => $v) {
            if($v['type'] == 1){
                $info[$k]['validity'] = date('Y-m-d',$v['begin_timestamp']).'-'.date('Y-m-d',$v['end_timestamp']);
            }elseif($v['type'] == 2){
                $info[$k]['validity'] = "领取".$v['fixed_begin_term']."天后生效,有效期".$v['fixed_term']."天";
            }
        }
        if($info){
            $return['status'] = 1;
            $return['data'] = $info;
        }else{
            $return['status'] = 2;
            $return['msg'] = '暂无数据';
        }
        $this->ajaxReturn($return);
    }
    /**
     * 添加优惠券
     */
    public function add_coupon(){
        $postdata = I('post.');
        // $location_id_list = json_decode(htmlspecialchars_decode($postdata['location_id_list']),true);
        // $postdata['location_id_list'] = implode(',',$location_id_list);
        $Weixin = new \Common\Vendor\WeixinCoupon();
        // 添加优惠券
        if($postdata['location_id_list']){
            $map = array();
            $map['status'] = 1;
            $map['id'] = array('in',$postdata['location_id_list']);
            $data = M('Shops')->where($map)->field('poi_id')->select();
            foreach ($data as $k => $v) {
                $location_id_list[] = $v['poi_id'];
            }
            $postdata['location_id_lists']=implode(',',$location_id_list);
        }
        $add_coupon = $Weixin->add_coupon($postdata);
        if($add_coupon['status'] == 1){
            $return['status'] = 1;
            $return['msg'] = $add_coupon['msg'];
        }else{
            $return['status'] = 3;
            $return['msg'] = $add_coupon['msg'];
        }
        $this->ajaxReturn($return);
    }
	/**
	 * 省市县数据
	 */
    public function linkage(){
        $return['status'] = 3;
        $id = I('param.id',0);
        $type = 0;
        $data = array();
        if(!$id)$type = 1;
        $data = get_arearegion_cache($type);
        if($id>0){$result['area'] = $data[$id];}
        if($data){
           $return['status'] = 1;
           $return['data'] = ($id>0)?$result:$data; 
        }else{
            $return['msg'] = '数据获取错误';
        }
        $this->ajaxReturn($return);
    }
    /**
    *关键词列表
    */ 
    public function wx_keyword(){
        $typearr=array('完全匹配','左边匹配','右边匹配','模糊匹配');
        $keytypearray=array('text'=>'文字回复','news'=>'图文回复');
        $map = array();
        $map['status'] = 1;
        $keyword = M('WxKeywords')->where($map)->field(true)->select();
        foreach ($keyword as $k => $v) {
            $keyword[$k]['keytypearray'] = $keytypearray[$v['keytype']];
            $keyword[$k]['typearr'] = $typearr[$v['type']];
        }
        if($keyword){
            $return['status'] = 1;
            $return['data'] = $keyword;
        }else{
            $return['status'] = 2;
            $return['msg'] = '暂无数据';
        }
        $this->ajaxReturn($return);
    }
    /**
    *删除关键词列表
    */ 
    public function del_wx_keyword(){
        $id = I('get.id');
        $return['id'] = $id;
        $map = array();
        $map['id'] = $id;
        $keyword = M('WxKeywords')->where($map)->delete();
        if($keyword){
            $return['status'] = 1;
            $return['msg'] = '删除成功';
        }else{
            $return['status'] = 3;
            $return['msg'] = '删除失败';
        }
        $this->ajaxReturn($return);
    }
    /**
    *外链
    */
    public function url_navtype(){
        $url_navtype = geturlrules(3);
        $return['status'] = 1;
        $return['url'] = $url_navtype;
        $this->ajaxReturn($return);
    }
    /**
    *添加关键字列表
    */ 
    public function wx_keyword_add(){
        $post = I('post.');
        $data = array();
        $data['keytype'] = $post['keytype'];
        $data['keyword'] = $post['keyword'];
        $data['type'] = $post['type'];
        $data['sort'] = $post['sort'];
        $data['addtime'] = time();
        if($post['status']){
            $data['status'] = 1;
        }else{
            $data['status'] = 0;
        }
        $wx_keywords = M('WxKeywords')->add($data);
        if($post['keytype'] == 'text'){//文本回复
            $data = array();         
            $data['content'] = $post['content'];
            $data['id'] = $wx_keywords;
            $wx_text = M('WxText')->add($data);
            if($wx_keywords && $wx_text){
                $return['status'] = 1;
                $return['msg'] = '添加成功';
            }else{
                $return['status'] = 3;
                $return['msg'] = '添加失败';
            }
        }else if($post['keytype'] == 'news'){//图片回复
            $data = array();
            $data['title'] = $post['title'];
            $data['intro'] = $post['intro'];
            $data['cover'] = $post['cover'];
            $data['content'] = $post['content'];
            $data['jump_url'] = return_urlrules($post['jump_url']);
            $data['id'] = $wx_keywords;
            $wx_news = M('WxNews')->add($data);
            if($wx_keywords && $wx_news){
                $return['status'] = 1;
                $return['msg'] = '添加成功';
            }else{
                $return['status'] = 3;
                $return['msg'] = '添加失败';   
            }
        }
        $this->ajaxReturn($return);
    }
    /**
    *查询关键字
    */ 
    public function select_keyword(){
        $id = I('get.id');
        $map = $data = array();
        $map['id'] = $id;
        $data['keywords'] = M('WxKeywords')->where($map)->field(true)->find();
        if($data['keywords']['keytype'] == 'text'){
            $data['news'] = '';
            $data['text'] = M('WxText')->where($map)->field(true)->find();
        }else if($data['keywords']['keytype'] == 'news'){
            $data['text'] = '';
            $data['news'] = M('WxNews')->where($map)->field(true)->find();
            $arr=explode(":",$data['news']['jump_url']);
            $data['news']['url_navtype']=$arr[1];
        }
        if($data['keywords']){
            $return['status'] = 1;
            $return['data'] = $data;
        }else{
            $return['status'] = 3;
            $return['msg'] = '查询失败';
        }
        $this->ajaxReturn($return);
    }
    /**
    *编辑关键字列表
    */ 
    public function wx_keyword_upd(){
        $post = I('post.');
        $data = array();
        $data['keytype'] = $post['keytype'];
        $data['keyword'] = $post['keyword'];
        $data['type'] = $post['type'];
        $data['sort'] = $post['sort'];
        $data['addtime'] = time();
        if($post['status']){
            $data['status'] = 1;
        }else{
            $data['status'] = 0;
        }
        $map = array();
        $map['id'] = $post['id'];
        $wx_keywords = M('WxKeywords')->where($map)->save($data);
        if($post['keytype'] == 'text'){//文本回复
            $data = array();         
            $data['content'] = $post['content'];
            $wx_text = M('WxText')->where($map)->save($data);
            if($wx_keywords && ($wx_text || $wx_text == 0)){
                $return['status'] = 1;
                $return['msg'] = '编辑回复成功';
            }else{
                $return['status'] = 3;
                $return['msg'] = '编辑回复失败';
            }
        }else if($post['keytype'] == 'news'){//图片回复
            $data = array();
            $data['title'] = $post['title'];
            $data['intro'] = $post['intro'];
            $data['cover'] = $post['cover'];
            $data['content'] = $post['content'];
            $data['jump_url'] = return_urlrules($post['jump_url']);
            $wx_news = M('WxNews')->where($map)->save($data);
            if($wx_keywords && ($wx_news || $wx_news)){
                $return['status'] = 1;
                $return['msg'] = '编辑回复成功';
            }else{
                $return['status'] = 3;
                $return['msg'] = '编辑回复失败';   
            }
        }
        $this->ajaxReturn($return);
    }
    /**
    *自定义菜单列表
    */ 
    public function wx_menu_list(){
        $wxmenu=M('WxMenu')->where(array('pid'=>'0'))->field(true)->order('sort,id desc')->select();
        foreach($wxmenu as $k => $v){
            $wxmenu[$k]['wxmenu2']=M('WxMenu')->where(array('pid'=>$v['id']))->field($field)->order('sort,id desc')->select();
        }
        $return['wxmenu1'] = $wxmenu;
        $return['status'] = 1;     
        $this->ajaxReturn($return);
    }
    /**
    *自定义菜单内容
    */ 
    public function select_menu(){
        $id = I('get.id');
        $map = array();
        $map['id'] = $id;
        $wx_menu = M('WxMenu')->where($map)->field(true)->find();
        $url = explode(":",$wx_menu['url']);
        if($url[1]){
            $wx_menu['url_navtype'] = intval($url[1]);
            $wx_menu['url'] = '';
        }else{
            $wx_menu['url_navtype'] = 0;
            $wx_menu['url'] = $wx_menu['url'];
        }
        if($wx_menu){
            $return['status'] = 1;
            $return['data'] = $wx_menu;
        }else{
            $return['status'] = 2;
            $return['msg'] = '暂无数据';
        }
        $this->ajaxReturn($return);
    }
    /**
    *添加自定义菜单
    */
    public function wx_menu_add(){
        $post = I('post.');
        $map = array();
        if($post['pid'] == 0){
            $map['pid'] = 0;
            $wx_menu1 = M('wxMenu')->where($map)->count('id');
            if($wx_menu1 > 2){
                $return['status'] = 3;
                $return['msg'] = '一级菜单最多只能添加三个';
                $this->ajaxReturn($return);
            }
        }
        $data['pid'] = $post['pid'];
        $data['name'] = $post['name'];
        $data['keyword'] = $post['keyword'];
        $data['url'] = return_urlrules($post['url']);
        $data['sort'] = $post['sort'];
        $wx_menu = M('wxMenu')->add($data);
        if($wx_menu){
            $return['status'] = 1;
            $return['msg'] = '添加自定义菜单成功';
        }else{
            $return['status'] = 3;
            $return['msg'] = '添加自定义菜单失败';
        }
        $this->ajaxReturn($return);
    }
    /**
    *编辑自定义菜单
    */
    public function wx_menu_upd(){
        $post = I('post.');
        $map = $data = array();
        $map['id'] = $post['id'];
        $data['pid'] = $post['pid'];
        $data['name'] = $post['name'];
        $data['keyword'] = $post['keyword'];
        $data['url'] = return_urlrules($post['url']);
        $data['sort'] = $post['sort'];
        $wx_menu = M('WxMenu')->where($map)->save($data);
        if($wx_menu || $wx_menu == 0){
            $return['status'] = 1;
            $return['msg'] = '编辑自定义菜单成功';
        }else{
            $return['status'] = 3;
            $return['msg'] = '编辑自定义菜单失败';
        }
        $this->ajaxReturn($return);
    }
    /**
    *删除自定义菜单
    */
    public function wx_menu_del(){
        $id = I('get.id');
        $map = array();
        $map['id'] = $id;
        $wx_menu = M('WxMenu')->where($map)->delete();
        if($wx_menu){
            $return['status'] = 1;
            $return['msg'] = '删除自定义菜单成功';
        }else{
            $return['status'] = 3;
            $return['msg'] = '删除自定义菜单失败';
        }
        $this->ajaxReturn($return);
    }
    /**
    *生成微信自定义菜单
    */
    public function updatemenu(){
        $appid = C('WX_APPID');
        $appsecret = C('WX_APPSECRET');
        if(empty($appid) || empty($appsecret)){
            $return['status'] = 3;
            $return['msg'] = '请填写APPID和APPSECRET后再更新菜单!';
            $this->ajaxReturn($return);
        }
        $wxmenu=$this->getNodeTree('','');
        foreach($wxmenu[1] as $k=> $v){
            $menu[$k]['name']=$v['name'];
            if($wxmenu[2][$v['id']]){
                foreach($wxmenu[2][$v['id']] as $key=>$val){
                    if(!empty($val['url']))$val['url']=geturl($val['url'],array('URL_MODEL'=>1),true,true);
                    $menu[$k]['sub_button'][$key]['name']=$val['name'];
                    if(!empty($val['url'])){
                        $menu[$k]['sub_button'][$key]['type']='view';
                        $menu[$k]['sub_button'][$key]['url']=$val['url'];
                    }else{
                        $menu[$k]['sub_button'][$key]['type']='click';
                        $menu[$k]['sub_button'][$key]['key']=$val['keyword'];
                    }
                }
            }else{
                if(!empty($v['url']))$v['url']=geturl($v['url'],array('URL_MODEL'=>1),true,true);
                if(!empty($v['url'])){
                    $menu[$k]['type']='view';
                    $menu[$k]['url']=$v['url'];
                }else{
                    $menu[$k]['type']='click';
                    $menu[$k]['key']=$v['keyword'];
                }
            }
        }
        $menulist['button']=$menu;
        $weixin = new \Common\Vendor\WeixinChat;
        $result=json_decode($weixin->setMenu($this->json_encode_cn($menulist)),true);

        if($result['errcode']==0){
            $return['status'] = 1;
            $return['msg'] = '更新成功';
        }else{
            $return['status'] = 3;           
            $return['msg'] = '更新失败!错误信息为:'.$result['errmsg'];
        }
        $this->ajaxReturn($return);
    }
    // 发放微信优惠券
    public function coupon_issue(){
        $postdata = I('post.');
        $map = array();
        $map['status']=array('GT',0);
        if($postdata['is_tmp'] == 1){
            $map['is_tmp'] = 1;
        }else if($postdata['is_tmp'] == 0){
            $map['is_tmp'] = 0;
        }
        if(!empty($postdata['mobile'])){
            $map['mobile']=$postdata['mobile'];
        }
        if(!empty($postdata['rank_id'])){
           $map['rank_id']=$postdata['rank_id'];
        }
        if($postdata['begin_usepoints'] && $postdata['end_usepoints']){
            $map['usepoints'] = array(array('gt',$postdata['begin_usepoints']),array('lt',$postdata['end_usepoints']));
        }
        if($postdata['begin_money'] && $postdata['end_money']){
            $map['money'] = array(array('gt',$postdata['begin_money']),array('lt',$postdata['end_money']));
        }
        if($postdata['begin_card_time'] && $postdata['end_card_time']){
            $map['card_time'] = array(array('gt',strtotime($postdata['begin_card_time'])),array('lt',strtotime($postdata['end_card_time'])));
        }
        if($postdata['begin_reg_time'] && $postdata['end_reg_time']){
            $map['reg_time'] = array(array('gt',strtotime($postdata['begin_reg_time'])),array('lt',strtotime($postdata['end_reg_time'])));
        }
        $member = M('Member')->where($map)->field('id,wxid')->select();
        if(!$member){
            $return['status'] = 3;
            $return['msg'] = '会员不存在';
            $this->ajaxReturn($return);
        }

        $map = array();
        $map['id'] = $postdata['coupon_id'];
        $coupons = M('Coupons')->where($map)->find();
        if(count($member) > $coupons['quantity']){
            $return['status'] = 3;
            $return['msg'] = '库存不足';
        }else{
            $add_data['coupons_id'] = $coupons['id'];
            $add_data['card_id'] = $coupons['card_id'];
            $add_data['rank_id'] = $coupons['rank_id'];
            $add_data['discount'] = $coupons['discount'];
            $add_data['reduce_cost'] = $coupons['reduce_cost'];
            $add_data['least_cost'] = $coupons['least_cost'];

            if($coupons['type'] == '1'){//固定日期
                $add_data['begin_timestamp'] = $coupons['begin_timestamp'];
                $add_data['end_timestamp'] = $coupons['end_timestamp'];
            }else{//固定时长
                $add_data['begin_timestamp'] = time()+$coupons['fixed_begin_term']*24*60*60;
                $tian = $coupons['fixed_term']+$coupons['fixed_begin_term'];
                $add_data['end_timestamp'] = time()+$tian*24*60*60;
            }

            $add_data['add_time'] = time();
            foreach ($member as $k => $v) {
                $add_data['uid'] = $v['id'];
                // $get_w['coupons_id'] = $postdata['coupon_id'];
                // $get_w['uid'] = $v['id'];
                // $get_w['status'] = 0;
                // $count_you = M('CouponsGet')->where($get_w)->count('id');
                // if($count_you == 0)
                    $add = M('CouponsGet')->add($add_data);                  
                if($add)M('Coupons')->where('id='.$postdata['coupon_id'])->setDec('quantity',1);
                if($v['wxid'])$wxid[] = $v['wxid'];
            }
            $check = check_use_auth('WeChatMarket');
            if($check['status'] == 1 && $postdata['is_weixin'] == 'true'){
                if(count($wxid) >1 ){                   
                    $Weixin = new \Common\Vendor\WeixinCoupon();
                    $wxcard = $Weixin->wxcard($wxid,$add_data['card_id']);
                }else if(count($wxid) == 1 ){
                    $wxids[] = $wxid['0'];
                    $wxids[] = $wxid['0'];
                    $Weixin = new \Common\Vendor\WeixinCoupon();
                    $wxcard = $Weixin->wxcard($wxids,$add_data['card_id']);
                }
                
                if($wxcard['errcode'] == 45065){
                    $return['status'] = 3;
                    $return['msg'] = '该优惠券已发放，不可重复发放';
                    $this->ajaxReturn($return);
                }
                $return['wxcard'] = $wxcard;
                if($add && $wxcard['errcode'] == 0){
                    $return['status'] = 1;
                    $return['msg'] = '发放优惠券成功';
                }else{
                    $return['status'] = 3;
                    $return['msg'] = '发放优惠券失败';
                }
            }else{
                if($add){
                    $return['status'] = 1;
                    $return['msg'] = '发放优惠券成功';
                }else{
                    $return['status'] = 3;
                    $return['msg'] = '发放优惠券成功';
                }
            }
        }
        $this->ajaxReturn($return);
    }
    // 判断优惠券有效
    public function coupon_if(){
        $id = I('get.id');
        $map = array();
        $map['id'] = $id;
        $coupons = M('Coupons')->where($map)->field(true)->find();
        if($coupons['end_timestamp']<NOW_TIME && $coupons['type'] == 1){
            $return['status'] = 3;
            $return['msg'] = '该优惠券已失效';
        }else if(!$coupons['card_id']){
            $return['status'] = 3;
            $return['msg'] = '优惠券未同步微信卡券';
        }else{
            $return['status'] = 1;
        }
        $this->ajaxReturn($return);
    }
    private function json_encode_cn($data) {
        $data = json_encode ( $data );
        return preg_replace ( "/\\\u([0-9a-f]{4})/ie", "iconv('UCS-2BE', 'UTF-8', pack('H*', '$1'));", $data );
    }
    /* 得到节点树 */
    private function getNodeTree($type='',$field='id,name',$uid = '') {
       //支付方式
       if(!$field)$field=true;
       $wxmenu[1]=M('WxMenu')->where(array('pid'=>'0'))->field($field)->order('sort,id desc')->select();
       if(!$type){       
           foreach($wxmenu[1] as $v){
               $wxmenu[2][$v['id']]=M('WxMenu')->where(array('pid'=>$v['id']))->field($field)->order('sort,id desc')->select();
           }
           $wxmenu[2]=array_filter($wxmenu[2]);
       }   
       return $wxmenu;
    }
    // 商户logo
    public function logo(){
        $shop_id = I('get.shop_id');
        $map = array();
        $map['id'] = $shop_id;
        $data = M('Shops')->where($map)->field('thumb,name')->find();
        if($data){            
            $return['status'] = 1;
            $return['data'] = $data;
        }else{
            $return['status'] = 3;
        }
        $this->ajaxReturn($return);
    }

}