<?php
/**
 * 微信会员卡
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author zhaoh <1070309178@qq.com>
 */

namespace Common\Vendor;
class WeixinCard{

	/**
	 * 获取保存的accesstoken
	 */
	private function getToken() {
		// $accesstoken = $this->getAcessToken();
		static $stoken = null;
        $accesstoken='';
        if(C('BOUND_STATUS')==2){//扫码授权
            $wx = new \Common\Vendor\Weixinopen;
			$accesstoken=$wx->get_access_token(C('appid'));
        }else{
			$stoken = S('WX_S_TOKEN');
			if (is_array($stoken)) {
				$nowtime = time();
				// 判断缓存里面的TOKEN保存了多久
				$difftime = $nowtime - $stoken ['tokentime'];
				// TOKEN有效时间7200 判断超过7000就重新获取;
				if ($difftime > 7000) {
					// 去微信获取最新ACCESS_TOKEN
					$accesstoken = $this->getAcessToken();
					$stoken ['tokentime'] = time();
					$stoken ['token'] = $accesstoken;
					// 放进缓存
					S('WX_S_TOKEN', $stoken);
				} else {
					$accesstoken = $stoken ['token'];
				}
			} else {
				// 去微信获取最新ACCESS_TOKEN
				$accesstoken = $this->getAcessToken();
				$stoken ['tokentime'] = time();
				$stoken ['token'] = $accesstoken;
				S('WX_S_TOKEN', $stoken); // 放进缓存
			}
		}
		return $accesstoken;
	}

	/**
	 * 重新从微信获取accesstoken
	 */
	private function getAcessToken() {
	   $wx = new \Common\Vendor\Jssdk();
       return $wx->getAccessToken();
	}

	/**
	 * 卡券基本数据
	 * @param  string $data 卡券基本数据
	 * @param  string $status 1修改会员卡
	 */
	private function baseinfo($data,$status){
	       if(empty($data['logo_url']))$data['logo_url']=C('WEB_SMALL_LOGO');
			$url = $this->uploadimg($data['logo_url']);
			$return_data['logo_url'] = $url;//商户LOGO
			if($status != 1)$return_data['brand_name'] = C('WEB_SITE_NAME');//商户名字
			$return_data['code_type'] = CODE_TYPE_QRCODE;//code码展示类型			
			$return_data['title'] = $data['title'];//券名
			$return_data['color'] = $data['color'];//券颜色
			$return_data['notice'] = $data['notice'];//使用提醒
			// $return_data['description'] = str_replace(PHP_EOL,'',C('CARD_EXPLAIN'));//卡券使用说明
			$return_data['description'] = $this->xuzhi();//卡券使用说明
			$return_data['date_info']['type'] = 'DATE_TYPE_PERMANENT';//有效期 永久有效
			if($status != 1)$return_data['sku']['quantity'] = 100000000;//卡券库存的数量
			$return_data['custom_url'] = "http://".$_SERVER['HTTP_HOST']."/index.php/mobile/member/index.html";//自定义跳转的URL
			$return_data['custom_url_name'] = '会员中心';//自定义跳转外链的入口名字
			$return_data['promotion_url'] = "http://".$_SERVER['HTTP_HOST']."/index.php/mobile/my_money/integral.html";//自定义跳转的URL
			$return_data['promotion_url_name'] = '我的积分';//自定义跳转外链的入口名字
			$return_data['get_limit'] = 1;//每人可领券的数量限制，建议会员卡每人限领一张
			$return_data['can_share'] = false;//卡券领取页面是否可分享，默认为true
			$return_data['can_give_friend'] = false;//卡券是否可转赠,默认为true
			if($data['is_show'] == 1){
				$return_data['location_id_list'] = $data['location_id_lists'];//会员卡所属门店
			}else{
				$return_data['use_all_locations'] = true;//适用全部门店
			}
			$return_data['service_phone'] = $data['service_phone'];//客服电话
			return $return_data;
	}
	private function card($card_type,$base_info,$postdata){
		$card_types = Array("MEMBER_CARD");
		$return_data['card_type'] = $card_type;
		switch ($card_type)
		{
			case $card_types[0]:
				// $url = $this->uploadimg($postdata['background_pic_url']);
				// $return_data['member_card']["background_pic_url"] ='';//会员卡背景
				$return_data['member_card']["base_info"] = $base_info;
				$return_data['member_card']["supply_bonus"] = true;
				$return_data['member_card']["supply_balance"] = false;				
				$return_data['member_card']["wx_activate"] = true;//会员卡支持一键开卡
				$return_data['member_card']["prerogative"] = $this->tequan();//会员卡特权说明
                if(empty($return_data['member_card']["prerogative"]))$return_data['member_card']['prerogative']=$base_info['title'];
				// 手动激活
				// $return_data['member_card']["auto_activate"] = false;
				$return_data['member_card']["activate_url"] = "http://".$_SERVER['HTTP_HOST']."/index.php/mobile/member/wx_phone.html";						
				$return_data['member_card']["custom_field1"]["name"] = "余额";//$_SERVER['HTTP_HOST']			
				$return_data['member_card']["custom_field1"]["url"] = "http://".$_SERVER['HTTP_HOST']."/index.php/mobile/capital/index.html";
				// $return_data['member_card']["custom_field2"]["name"] = "积分";				
				$return_data['member_card']["custom_field2"]["url"] = "http://".$_SERVER['HTTP_HOST']."/index.php/mobile/my_money/integral.html";			
				$return_data['member_card']["custom_field3"]["name"] = "优惠券";				
				$return_data['member_card']["custom_field3"]["url"] = "http://".$_SERVER['HTTP_HOST']."/index.php/mobile/collection/get_coupons.html";
				break;
			default:
				exit("CardType Error");
		}
		return $return_data;
	}
	/**
	 * 添加会员卡
	 */
	public function add_coupon($postdata){
		$wmc=M('WxMemberCard');
		$baseinfo = $this->baseinfo($postdata,0);
		$postdata["code_type"] = "CODE_TYPE_ONLY_QRCODE";//二维码
		$postdata['add_time']=time();
		$postdata['status'] = 1;
		$postdata['card_type'] = 'MEMBER_CARD';
        
        $wx_card = M('Config')->field('value')->where("name='WX_CARD'")->count();
        if(empty($wx_card)){
            $data['value'] = serialize($postdata);
            $data['name'] = 'WX_CARD';
			$data['title'] = '微信会员卡';
			$save = M('Config')->add($data);
        }
        if(empty($baseinfo['logo_url'])){
            $return['status'] = 0;
			$return['msg'] = '商家LOGO获取失败';return $return;
        }
		$card = $this->card($postdata['card_type'],$baseinfo,$postdata);
		$access_token = $this->getToken();
		$url = "https://api.weixin.qq.com/card/create?access_token=".$access_token;
		$post = array(
			'card'=>$card
		);
		$post = json_encode($post, JSON_UNESCAPED_UNICODE);
		$coupon = curlinit($url,$post);
		$return['data'] = $coupon;
		if($coupon['errcode'] == 0){
			$postdata['card_id'] = $coupon['card_id'];
			// $this->activateuserform($coupon['card_id']);
			$data['value'] = serialize($postdata);
			$save = M('Config')->where("name='WX_CARD'")->save($data);
			$return['status'] = 1;
			$return['msg'] = '添加成功';
		}else{
		    $data['value'] = serialize($postdata);
			$save = M('Config')->where("name='WX_CARD'")->save($data);
			$return['status'] = 0;
			$return['msg'] = '微信会员卡添加失败'.$coupon['errmsg'];
		}
		return $return;
	}
	// 设置开卡字段接口
	public function activateuserform($card_id){
		$post['card_id'] = $card_id;
		$ziduan = array("USER_FORM_INFO_FLAG_MOBILE","USER_FORM_INFO_FLAG_SEX","USER_FORM_INFO_FLAG_NAME","USER_FORM_INFO_FLAG_BIRTHDAY","USER_FORM_INFO_FLAG_IDCARD");
		$post['required_form']['common_field_id_list'] = $ziduan;
		$access_token = $this->getToken();
		$url = "https://api.weixin.qq.com/card/membercard/activateuserform/set?access_token=".$access_token;
		$post = json_encode($post, JSON_UNESCAPED_UNICODE);
		$datas = curlget($url,  $post,'POST', array("Content-type: text/html; charset=utf-8"), true);
		$coupon = json_decode($datas,true);
	}
	/**
	 * 拉取会员信息接口
	 * @param  string $data.card_id 会员卡id
	 * @param  string $data.code 会员卡号
	 */
	function userinfo($data){
		$post['card_id'] = $data['card_id'];
		$post['code'] = $data['code'];
		$access_token = $this->getToken();
		$url = "https://api.weixin.qq.com/card/membercard/userinfo/get?access_token=".$access_token;
		$post = json_encode($post, JSON_UNESCAPED_UNICODE);
		$datas = curlget($url,  $post,'POST', array("Content-type: text/html; charset=utf-8"), true);
		$coupon = json_decode($datas,true);
		$data['mobile'] = $coupon['user_info']['common_field_list']['0']['value'];
		$data['sex'] = $coupon['user_info']['common_field_list']['1']['value'] == '男'?1:2;
		$data['birthday'] = $coupon['user_info']['common_field_list']['2']['value'];
		$data['IDcard'] = $coupon['user_info']['common_field_list']['3']['value'];
		$data['real_name'] = $coupon['user_info']['common_field_list']['4']['value'];
		$this->membercard($data,'初始积分同步');
		$return['status'] = 1;
		return $return;
	}
	/**
	 * 手动激活会员卡
	 * @param  string $phone 会员手机号
	 * @param  string $explain 积分变换说明
	 */
	public function membercard($data,$explain=''){
		$map =$save_data= array();
		$map['id'] = $data['id'];
		$member = M('Member')->where($map)->field('id,username,usepoints,code,is_tmp,card_sn,card_status')->find();
		$data['code'] = $member['code'];
        if(empty($member['code'])){
			$return['status'] = 0;
			$return['msg'] = '请先领取会员卡';
			return $return;
		}
		if(!empty($member['card_sn']) && $member['card_status']==1){
			$return['status'] = 0;
			$return['msg'] = '您已经领取过会员卡了';
			return $return;
		}        
		// if($member['is_tmp'] == 0){
		// 	$return['status'] = 0;
		// 	$return['msg'] = '已激活，不可重复激活';
		// 	return $return;
		// }
        
        $where['id'] = $data['id'];
		$save_data['card_sn'] = $data['code'];
		$save_data['card_status'] = 1;
		$save_data['is_tmp'] = 0;
		$save_data['mobile'] = $data['mobile'];
		$save_data['sex'] = $data['sex'];
		$save_data['birthday'] = $data['birthday'];
		$save_data['idcard'] = $data['idcard'];
		$save_data['province'] = $data['province'];
		$save_data['city_id'] = $data['city_id'];
		$save_data['district'] = $data['district'];
		$save_data['real_name'] = $data['real_name'];
		if($data['username'] && empty($member['username']))$save_data['username'] = $data['username'];

		$con_where = array();
        $con_where['name'] = 'MEMBERATTRIBUTE';
        $con_have = M("Config")->where($con_where)->field("id,name,value")->find();
        if($con_have){
            $con_data = unserialize($con_have['value']);
            if($con_data['real_name']['is_member']){
                if(empty($data['real_name'])){
                	$return['status'] = 0;
                    $return['msg']='真实姓名不能为空';
                    return $return;
                }
            }
            if($con_data['birthday']['is_member']){
                if(empty($data['birthday'])){
                	$return['status'] = 0;
                    $return['msg']='生日不能为空';
                    return $return;
                }
            }
            if($con_data['sex']['is_member']){
                if(empty($data['sex'])){
                	$return['status'] = 0;
                    $return['msg']='性别不能为空';
                    return $return;
                }
            }
            if($con_data['address']['is_member']){
                if(empty($data['province'])){
                	$return['status'] = 0;
                    $return['msg']='请选择地区';
                    return $return;
                }
            }
        }
        
		if($data['ref_mobile']){
			$map = array();
			$map['mobile'] = $data['ref_mobile'];
			$save_data['parent_id'] = M('Member')->where($map)->getField('id');
			if($data['id'] == $save_data['parent_id']){
				$save_data['parent_id'] = 0;
				$return['status'] = 0;
				$return['msg'] = '该推荐人不能是自己';
				return $return;
			}
			if(!$save_data['parent_id']){
				$return['status'] = 0;
				$return['msg'] = '该推荐人不存在';
				return $return;
			}else{
				TooKeenAward(0,1,'register',$save_data['parent_id']);//拓客奖励（新增会员注册奖励）
				$datasave['to'] = $data['ref_mobile'];
				$datasave['mobile'] = $data['mobile'];
				$datasave['time'] = date('Y-m-d H:i:s',NOW_TIME);
				sendbytheme($datasave,'TO_REGISTER_CODE');//发送信息给推荐人
			}
		}
        if(empty($explain)){$explain='积分同步';}
		$post['code'] = $member['code'];//code
		$post['init_bonus'] = $member['usepoints'];//初始积分不填为0
		$post['init_bonus_record'] = $explain;//积分变动说明
		$access_token = $this->getToken();
		$return['msg'] = $access_token;
		$url = "https://api.weixin.qq.com/card/membercard/activate?access_token=".$access_token;
		$post = json_encode($post, JSON_UNESCAPED_UNICODE);
		$datas = curlget($url,  $post,'POST', array("Content-type: text/html; charset=utf-8"), true);
		$coupon = json_decode($datas,true);
		if($coupon['errcode'] == 0){
			$registered['to'] = $data['mobile'];
			$registered['mobile'] = $data['mobile'];
			$registered['time'] = date('Y-m-d H:i:s',NOW_TIME);
			sendbytheme($registered,'MEMBER_REGISTERED');//会员注册成功提醒
			
			if($data['name']){
                $wherec = $data_con = $map_con = array();
                $map_con['name'] = 'ATTRIBUTE';
                $c_have = M("Config")->where($map_con)->getField("value");
                $c_list = json_decode($c_have,true);
                
                $wherec['uid'] = $data['id'];
                foreach ($data['name'] as $key => $value) {
                    if($value){
                        $wherec['aid'] = $key;
                        $have = M("MemberAttribute")->where($wherec)->count();
                        $value = ltrim($value, ",");
                        if($c_list[$key]['type'] == 'date'){
                            $value = strtotime($value);
                        }
                        if($have){
                            $save_datac = array();
                            $save_datac['content'] = $value;
                            M("MemberAttribute")->where($wherec)->save($save_datac);
                        }else{
                            $add_data = array();
                            $add_data['uid'] = $data['id'];
                            $add_data['aid'] = $key;
                            $add_data['content'] = $value;
                            M("MemberAttribute")->add($add_data);
                        }
                    }
                }unset($key,$value);
            }
            unset($data['name']);
			M('Member')->where($where)->save($save_data);
			// 激活会员卡赠送积分
			$usepoints=C('CARD_INTEGRAL');
			if($usepoints>0){
				account_change($member['id'],$usepoints,4,5,'领卡赠积分');
			}
			$return['status'] = 1;
			$return['msg'] = '激活成功';
		}else{
			$return['status'] = 0;
			$return['msg'] = $coupon;
		}
		return $return;
	}
	/**
	 * 更新会员卡数据
	 */
	public function updateuser($data){
	    if(empty($data['record_bonus']))$data['record_bonus']='积分变更';
		$post['code'] = $data['code'];//code
		$post['card_id'] = $data['card_id'];//卡券ID
		$post['bonus'] = $data['bonus'];//设置的积分全量值，传入的数值会直接显示
		$post['record_bonus'] = $data['record_bonus'];//自定义积分记录，不超过14个汉字
		if($data['add_bonus'])$post['add_bonus'] = $data['add_bonus'];//自定义积分记录，不超过14个汉字
		$access_token = $this->getToken();
		$url = "https://api.weixin.qq.com/card/membercard/updateuser?access_token=".$access_token;
		$post = json_encode($post, JSON_UNESCAPED_UNICODE);
		$datas = curlget($url,  $post,'POST', array("Content-type: text/html; charset=utf-8"), true);
        $coupon = json_decode($datas,true);
		if($coupon['errcode'] == 0){
			$return['status'] = 1;
		}else{
			$return['status'] = 0;
			$return['msg'] = '更新会员卡信息失败';
		}
	}

	/**
	 * 修改会员卡
	 */
	public function card_update($postdata){
		if($postdata['open']){
			$baseinfo = $this->baseinfo($postdata,1);
			$postdata['card_type'] = 'MEMBER_CARD';
			$card = $this->card($postdata['card_type'],$baseinfo,$postdata);
			unset($card['card_type']);
			$access_token = $this->getToken();
			$url = "https://api.weixin.qq.com/card/update?access_token=".$access_token;
			$post = array(
				'card_id'=>$postdata['card_id'],
				'member_card'=>$card['member_card']
			);
			$post = json_encode($post, JSON_UNESCAPED_UNICODE);
			$coupon = curlinit($url,$post);
			$return['coupon'] = $coupon;
		}else{
			$coupon['errcode'] = 0;
		}
		if($coupon['errcode'] == 0){
			$data['value'] = serialize($postdata);
			$wx_card = M('Config')->field('value')->where("name='WX_CARD'")->find();
			if(empty($wx_card)){
				$data['name'] = 'WX_CARD';
				$save = M('Config')->add($data);
			}else{
				$save = M('Config')->where("name='WX_CARD'")->save($data);
			}
		}else{
			$return['status'] = 0;
			$return['msg'] = '编辑会员卡信息失败';
		}
		if($save || $save == 0){
			$return['status'] = 1;
			$return['msg'] = '编辑成功';
		}else{
			$return['status'] = 0;
			$return['msg'] = '编辑失败';
		}
		$return['data'] = $postdata;
		return $return;
	}
    
	/**
	 * 查询会员卡
	 */
	public function get_card_info($postdata){
	   $return=array('status'=>0,'msg'=>'');
		if($postdata['card_id']){
			$access_token = $this->getToken();
			$url = "https://api.weixin.qq.com/card/get?access_token=".$access_token;
			$post = array(
				'card_id'=>$postdata['card_id']
			);
			$post = json_encode($post, JSON_UNESCAPED_UNICODE);
			$coupon = curlinit($url,$post);
		}else{
			$coupon['errcode'] = 11;
		}
		if($coupon['errcode'] == 0){
		    $info=$coupon['card'];
			$return['status'] = 1;
		}else{
			$return['msg'] = '获取会员卡信息失败';
		}
		$return['data'] = $info;
		return $return;
	}
	/**
	 * 上传图片信息
	 */
	public function uploadimg($wx_url){
	    if(str_exists($wx_url,'http')){
    	    $yuan_img = file_get_contents($wx_url);
    		$linshiimg = ROOT_PATH."/uploads/thumb/".randStr(8,'1234567890').".jpg";//临时图片;
    		file_put_contents($linshiimg,$yuan_img);
	    }else{
	       $linshiimg =$wx_url;
	    }		
		$url=format_url($linshiimg,2);
		$data = str_replace("\\","/",$url);
		$access_token = $this->getToken();
		//1.创建一个新cURL资源
		$ch = curl_init();
		//2.设置URL和相应的选项
		$curl = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=".$access_token;
		$data = array('media'=>'@'.$data); 
		curl_setopt($ch, CURLOPT_URL, $curl);
		//启用时会将头文件的信息作为数据流输出。        
	    curl_setopt($ch, CURLOPT_HEADER, false);
	    //将curl_exec()获取的信息以字符串返回，而不是直接输出。
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);  
	    //FALSE 禁止 cURL 验证对等证书（peer's certificate）。    
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);      
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true);  //验证主机 
         //发送 POST 请求    
        curl_setopt($ch, CURLOPT_POST, true);     
        //全部数据使用HTTP协议中的 "POST" 操作来发送。          
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        //3.抓取URL并把它传递给浏览器    
    	$content = curl_exec($ch); 
    	//4.关闭cURL资源，并且释放系统资源    
    	curl_close($ch); 
    	$res = json_decode($content,true);
    	if($res){
    		unlink($linshiimg);
    	}
    	return $res['url'];

	}
	/**
	 * 使用须知处理
	 */
	public function xuzhi(){
		// 会员等级
		$map['status'] = 1;
		$member_rank = M('MemberRank')->where($map)->field('name,max_points,goods_price')->select();
		foreach ($member_rank as $k => $v) {
			$html = '等级'.$v['name'].'累计消费'.$v['max_points'].'折扣'.floatval($v['goods_price']).'%'."\n".$html;
		}
		if(C('GRADE_CHOICES') == 1){
			$lei = "累计消费";
		}else{
			$lei = "累计充值";
		}
		$html = '会员等级方案'."\n".$html.'积分功能'."\n".'积分换算比例'.C('WEB_INTEGRAL_RATIO')."  每100积分可抵多少元现金"."\n".'积分支付比例'.C('INTGRAL_PAY_RATIO')."  每100元商品最多可以使用多少元积分"."\n".'每日签到赠积分'.C('LOGIN_GAIN_SELL_INTEGRAL')."\n".'领卡赠积分'.C('CARD_INTEGRAL')."\n".'等级晋升赠积分'.C('RANK_PROMOTION_INTEGRAL')."\n".'购物赠积分设置'.C('SALES_GAIN_SELL_INTEGRAL_RATE')."\n".'会员升级'.$lei."\n".'充值赠积分设置'.C('RECHARGE_SELL_INTEGRAL_RATE')."\n";
		return $html;
	}
	/**
	 * 会员特权
	 */
	public function tequan(){
		$m_rule = M('ManypointsRule')->where()->field('name,rank_limit')->select();
		foreach ($m_rule as $k => $v) {
			if($v['rank_limit'] == 0){
				$rank_limit = '不限制';
			}else{
				$rank_limit = idtoname($v['rank_limit'],'MemberRank','name');
			}
			$html .= $rank_limit.'等级'.$v['name']."\n";
		}
		return $html;
	}
	/**
	 * 获取小程序开卡组件必要参数
	 */
	public function get_wxsmall_param(){
		//微信卡券更新
		$Weixin = new \Common\Vendor\WeixinCoupon();
		$map['name'] = 'WX_CARD';
        $config = M('Config')->where($map)->getField('value');
        $config = unserialize($config);
        $card_id = $config['card_id'];
        $AddCartParam = $Weixin->AddCartParam($card_id);
        if($AddCartParam){
            $return['data']['cardId'] = $AddCartParam['cardId'];
            $return['data']['cardExt'] = json_encode($AddCartParam['cardExt']);
        }
        //微信卡券更新end
		return $return;
	}
	/**
	 * 解析小程序会员卡激活时所必须的参数code
	 */
	public function card_code_decrypt($code){
		$return = array('status'=>3);
		if(empty($code)){
			return $return;
		}
		$access_token = $this->getToken();
		$url = "https://api.weixin.qq.com/card/code/decrypt?access_token=".$access_token;
		$post = array(
			'encrypt_code'=>$code,
		);
		$post = json_encode($post, JSON_UNESCAPED_UNICODE);
		$result = curlinit($url,$post);
		if($result['errcode']==0&&$result['errmsg']=='ok'){
			$return['status'] = 1;
			$return['code'] = $result['code'];
		}
		return $return;
	}
}
?>