<?php
/**
 * 微信回复处理类
 * @Copyright (C) 2018 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaogg <xiaogg@sina.cn>
 */

namespace Common\Vendor;
class Weixinresponse {	
	public function reply($data) {
	   if(empty($data))return false;
		if($data['Content']=='openid'){
			$backdata['type']='text';
            $backdata['content']=$data['FromUserName'];
            return $backdata;
		}
        // 消息类型
		switch ($data['MsgType']) {
			case 'text': // 类型是文本的
				return $this->getContent($data);
			case 'event' : // 类型是事件的
				switch ($data['Event']) {
					case 'subscribe': return $this->getfirst($data);break;// 首次关注 
					case 'unsubscribe': return $this->unsubscribe($data);break;//取消关注   
					case 'SCAN': return $this->getfirst($data);break;// 用户已关注时的事件推送              
					case 'CLICK': $data['Content']=$data['EventKey'];return $this->getContent($data);break;//响应菜单关键词
                    default :return $this->getdefault($data);break;//默认回复
				}break;
			default:return $this->getdefault($data);break;
		}
	}
    /**
	 * 文件文章列表及描述
	 * @param type $content
	 * @return type
	 */
	private function getContent($content) {
        $key    = $content['Content'];
        $Extension=session('Extension');
		$cache_key = 'WXCONTENT_'.$Extension.md5($key.$content['FromUserName']);
		$backdata = S($cache_key);
		if (empty($backdata)) {		  
            $model = M ('WxKeywords');
            $where['keyword']=$key;$where['type']=0;$where['status']=1;
            $where['keytype']='text';//精确定位文本关键词
            $keydata[0]= $model->where($where)->field('id,keytype')->cache(true)->order('sort,id desc')->find();
            if(!$keydata[0]['id']){
            $where['keytype']=array('neq','text');//精确定位非文本关键词
			$keydata= $model->where($where)->field('id,keytype')->cache(true)->order('sort,id desc')->select();
            }
            if(!$keydata[0]['id']){//模糊匹配
			    $like['type']= array('gt',0);$like['status']=1;
			    $list = $model->where($like)->field('id,keyword,keytype')->cache(true)->order('sort,id desc')->select();
                foreach($list as $keywordInfo) {
                    $keywordArr=$this->_contain_keyword($keywordInfo,$key);  
    			    if($keywordArr)$keydata[]=$keywordArr;
    		    }unset($list);
            }
            if(!$keydata[0]['id']){//匹配生活服务
                $keydata[0]=$this->getdefault($content);
                $keydata[0]['keytype']=$keydata[0]['type'];
            }
           if($keydata){//生成回复内容
           $nkeytype='';$backdata=array();
            foreach($keydata as $k => $v){
                if(!$v['keytype'])continue;
                if(!$nkeytype)$nkeytype=$v['keytype'];
                if($nkeytype!=$v['keytype'])return false;//当所有关键词类型不一致时跳出
                if($v['id']){$keyinfo=M('Wx'.ucfirst($v['keytype']))->field(true)->find($v['id']);//关键词
                if($keyinfo)$v=array_merge($v,$keyinfo);}
                $backdata['type']=$v['keytype'];
                $backdata['id']=$v['id'];
                switch($v['keytype']){
                    case "text":
                    $backdata['content']=$v['content'];
                    break;
                    case "news":
                    if($v['cover'] && !str_exists($v['cover'],'http://'))$v['cover']='http://'.$_SERVER['HTTP_HOST'].$v['cover'];
                    
                    $param = array();
                    if(!empty($Extension))$param['extension']=$Extension;
                    $param['id']=$v['id'];
                    $param['openid']=openid_encode($content['FromUserName']);                    
                    $v['jump_url']='http://'.C('APPID').'.'.BASE_DOMAIN.U('Home/Weixin/jump',$param,true);
                    $backdata['content'][]=array($v['title'],$v['intro'],$v['cover'],$v['jump_url']);
                    break;
                }
            } 
            if($backdata)S($cache_key, $backdata,100);//缓存
	       }
       }
        $this->request_count($backdata);
        return $backdata;
	}
    // 处理关键词包含的算法
	private function _contain_keyword($keywordInfo, $key) {
	   $keyArr='';
       $keyword=$keywordInfo['keyword'];
       switch($keywordInfo['type']){
        case "4"://正则匹配
        if (preg_match ($keyword,$key))$keyArr = $keywordInfo;break;
        case "3"://模糊匹配
        if (str_exists($keyword,$key))$keyArr = $keywordInfo;break;
        case "0":break;//不支持完全匹配
        default://左右匹配
            $arr = explode ($keyword,$key);
            if (count($arr)>1){// 在关键词不相等的情况下进行左右匹配判断，否则相等的情况肯定都匹配    			
    			if ($keyword!=$key){
    				if($keywordInfo['type']==1 && ! empty($arr[0]))return false;// 左边匹配
    				if($keywordInfo['type']==2 && ! empty($arr[1]))return false;// 右边 匹配
    			}$keyArr = $keywordInfo;
    			$keyArr['prefix']= trim($arr[0]); // 关键词前缀，即包含关键词的前面部分
    			$keyArr['suffix']= trim($arr[1]); // 关键词后缀，即包含关键词的后面部分
    		}
        break;
       }
       if($keyArr){return $keyArr;}else{return false;}
	}
	private function request_count($data){//关键词的请求数批量+1
        if(!$data)return false;
        $model = M ('WxKeywords');
        foreach($data as $v){if($v['id'])$model->where(array('id'=>$v['id']))->setInc('count');}
	}
    private function unsubscribe($data){//取消关注
        $member_info=GetmdataBywx($data['FromUserName']);
        if($member_info['id'] && is_numeric($member_info['is_follow'])){
            $save_data=$map=array();
            $map['id']=$member_info['id'];
            $save_data['is_follow']=0;
            $save_data['unfollow_time']=NOW_TIME;
            M('Member')->where($map)->save($save_data);
        }
    }
	private function getfirst($data){//获取首次关注    
        if(str_exists($data['EventKey'],'_')){
            $keyarr=explode('_',$data['EventKey']);$key=$keyarr[1];
        }else{
            $key=$data['EventKey'];
        }
        $first=array();session('Extension',null);
		$user_shop=0;
		if($key){
            session('Extension',$key);
            if(str_exists($key,'shop')){
                cookie('ExtensionShopid',$key);
				$user_shop = str_replace('shop','',$key);//门店id
                $map=array();$map['keyword']='会员卡';$map['status']=1;
                $count=M('WxKeywords')->where($map)->count();
                if($count>0){$first['keyword']='会员卡';}
            }else if(str_exists($key,'cj')){
				$order_id = str_replace('cj','',$key);//订单id
				$map = array();$map['id'] = $order_id;
				$user_shop = M('OrderInfo')->where($map)->getField('shop_id');//门店id
				if($user_shop){
					cookie('ExtensionShopid',$user_shop);
				}
                $map=array();$map['keyword']='小票抽奖';$map['status']=1;
                $count=M('WxKeywords')->where($map)->count();
                if($count>0){$first['keyword']='小票抽奖';}
            }else if(str_exists($key,'cz')){
				$user_shop = str_replace('cz','',$key);//门店id
                $map=array();$map['keyword']='会员储值';$map['status']=1;
                $count=M('WxKeywords')->where($map)->count();
                if($count>0){$first['keyword']='会员储值';}
            }else{
                cookie('ExtensionId',$key);
            }
        }
		$member_info=GetmdataBywx($data['FromUserName'],$user_shop);
        if($data['Event']=='subscribe' && $member_info['id'] && is_numeric($member_info['is_follow'])){
            $save_data=$map=array();
            $map['id']=$member_info['id'];
            $save_data['is_follow']=1;
            $save_data['follow_time']=NOW_TIME;
            M('Member')->where($map)->save($save_data);
        }
        if(empty($first)) $first = M('WxFirst')->field('keyword,content')->find(1);
        $firstdata = '';
        if ($first['keyword']) {
            $data['Content'] = $first['keyword'];
            $firstdata = $this->getContent($data);
        }
        if(!$firstdata && $first['content']){
            $firstdata['type']='text';
            $firstdata['content']=$first['content'];
        }
        return $firstdata;
    }
    private function getdefault($data){//获取默认值或者 生活服务
        if(in_array($data['Event'],array('submit_membercard_user_info','user_get_card','user_view_card','user_consume_card')))$this->donation($data);
        if(!$data['Content'])return false;
        if(C('WX_AUTOCHAT')){
        $url="http://we.onexin.com/?mod=dialog&do=talk&title=".urlencode($data['Content']);
        $content=json_decode(curlget($url),true);
        if(in_array($content['result'],array('200','300'))){
            $backdata['type']='text';
            $backdata['content']=$content['message'];
            return $backdata;
        }
        }
        return false;
    }     
    // 卡券相关事件
    private function donation($xml){
        // file_put_contents('uploads/wxcard'.NOW_TIME.'.txt',var_export($xml,1));
        if($xml['Event']=='submit_membercard_user_info'){//会员卡激活
            $Weixin = new \Common\Vendor\WeixinCard();
            $data['code'] = $xml['UserCardCode'];
            $data['card_id'] = $xml["CardId"];
            $u_ap['wxid'] = $xml['FromUserName'];
            $member = M('Member')->where($u_ap)->field('id,usepoints')->find();
            $data['id'] = $member['id'];
            $data['usepoints'] = $member['usepoints'];
            $Weixin->userinfo($data);//获取会员激活信息
        }elseif($xml['IsGiveByFriend']==0 && $xml['Event']=='user_get_card'){//已领取卡券同步到本地卡券中心
            $map = array();
            $map['card_id'] = $xml['CardId'];
            $id = M('Coupons')->where($map)->getfield('id');
            $u_ap['wxid'] = $xml['FromUserName'];
            $uid = M('Member')->where($u_ap)->getfield('id');
            $code = $xml['UserCardCode'];
            $type= M('Coupons')->where($map)->getfield('buy_type');
            $map=array();
            $map['card_id']=$xml['CardId'];
            $map['uid']=$uid;
            $map['code']='';
            $coupons_info=M("CouponsGet")->where($map)->field(true)->find();
            if($coupons_info){
                $data=$map=array();
                $data['code']=$code;
                $map['id']=$coupons_info['id'];
                M("CouponsGet")->where($map)->save($data);
            }
        }elseif($xml['Event'] == 'user_view_card'){
            $where_rs['wxid'] = $xml["FromUserName"];
            $member = M('Member')->where($where_rs)->field('id,code,card_sn,mobile')->find();
            //if(empty($member['card_sn']) && !empty($member['mobile']))$save_data['card_sn'] = $xml['UserCardCode'];
            $save_data['card_id'] = $xml['CardId'];
            $save_data['code'] = $xml['UserCardCode'];
            $save_data['card_time'] = NOW_TIME;
            M('Member')->where($where_rs)->save($save_data);
            // 判断会员卡激活方式
            $where_card['card_id'] = $xml['CardId'];
            $open_card = M('WxMemberCard')->where($where_card)->getfield('open_card');
            if($open_card == 0){
                $Weixin = new \Common\Vendor\WeixinCard();
                $data['code'] = $xml['UserCardCode'];
                $data['card_id'] = $xml["FromUserName"];
                $data['bonus'] = M('Member')->where($where_rs)->getfield('usepoints');
                $data['record_bonus'] = '积分同步';
                $Weixin->updateuser($data);
            }
        }elseif($xml['Event'] == 'user_get_card' && ($xml['IsGiveByFriend'] == '1' || $xml['IsGiveByFriend'] == '0')){//转赠领取事件
            $add_data['card_id'] = $xml["CardId"];//卡券id
            $add_data['code'] = $xml["UserCardCode"];//卡券id
            $where_rs['wxid'] = $xml["FromUserName"];
            $receive_id = M('Member')->where($where_rs)->getfield('id');
			if(empty($receive_id)){
				$member=GetmdataBywx($xml['FromUserName']);
				$receive_id=$member['id'];
			}
            $add_data['receive_id'] = $receive_id;//领取人id
            $add_data['receive_wxid'] = $xml["FromUserName"];//领取人wxid
            if($xml["FriendUserName"] && $xml['IsGiveByFriend'] == '1'){//转赠领取
                $where_s['wxid'] = $xml["FriendUserName"];
                $send_id = M('Member')->where($where_s)->getfield('id');
                $add_data['send_id'] = $send_id;//发券方uid
               //设置转赠人优惠券失效
                $savedata=$map=array();
                $map['card_id']=$add_data['card_id'];
                $map['uid']=$send_id;
                $map['code']=$xml["OldUserCardCode"];//旧卡券号
                M('CouponsGet')->where($map)->delete();
                $from=2;$from_temp='转赠领取';
            }elseif(!$xml["FriendUserName"] && $xml['IsGiveByFriend'] == '0'){//会员领取
                $parent_id = idtoname($receive_id,"Member",'parent_id');
                $add_data['send_id'] = $parent_id;//推荐人id
                $from=1;$from_temp='免费领取';
            }
            $where_r['card_id'] = $xml["CardId"];
            $coupons_id = M('Coupons')->where($where_r)->getfield('id');
            if($receive_id){
                $uid = $receive_id;
            }else{
                $data = GetmdataBywx($xml["FromUserName"]);
                $uid = $data['id'];
            }
            $get_coupons = D('Shop/CouponsGet')->get_coupons($coupons_id,$uid,$add_data['code'],0,$from,$from_temp);
            $add_data['coupons_id'] = $coupons_id;//优惠券表id
            $add_data['add_time'] = $xml['CreateTime'];
            M('CouponsDonation')->add($add_data);
            if(!$receive_id){//新用户奖励
                $TooKeenAward = TooKeenAward('',1,'get_coupon',$send_id);//微信卡券新用户赠领
            }
        }elseif($xml['Event'] == 'user_consume_card'){//核销事件
            $where['code'] = $xml['UserCardCode'];
            $count = M('CouponsDonation')->where($where)->count();
            if($count){
                $save_time['create_time'] = $xml["CreateTime"];
                M('CouponsDonation')->where($where)->save($save_time);
                $send_id = M('CouponsDonation')->where($where)->getfield('send_id');
                $TooKeenAward = TooKeenAward('',1,'cancel_coupon',$send_id);//赠领卡券核销奖励
            }else{
                $add_data['card_id'] = $xml["CardId"];
                $add_data['create_time'] = $xml['CreateTime'];
                $add_data['add_time'] = NOW_TIME;
                M('CouponsDonation')->add($add_data);
            }
        }
    }
}
?>