<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// +----------------------------------------------------------------------
namespace app\web\controller;
use service\DistributorService;
use service\UserService;
use think\Db;
use app\common\plugin\Jwt;
use app\common\plugin\WxBizDataCrypt;
use app\common\plugin\Jssdk;


//wx类
class WxController extends MainController
{
	public $app_id,$app_secret,$accessToken;//公众号

	public function __construct()
	{
		parent::__construct();
		$wxconfig=config()['config']['wxconfig'];
		$this->app_id=$wxconfig['appid'];
		$this->app_secret=$wxconfig['secret'];
	}

	public function login(){
		//微信小程序
		$code = input("code", '', 'htmlspecialchars_decode');

		$avatar=$this->request->param('avatar','');
		$wx_nickname=$this->request->param('nickname','匿名用户');

		$url = 'https://qyapi.weixin.qq.com/cgi-bin/miniprogram/jscode2session?access_token='.$this->getAccess_token().'&js_code='.$code.'&grant_type=authorization_code';
		//通过code换取openid session _key
		$res = $this->curl_get($url);
		if(!$res)
			$this->api_return_json(['msg'=>'请求微信服务器失败']);
		$res=(array)$res;
		if (!isset($res['session_key'])) {
			$this->api_return_json(['msg'=>'requestTokenFailed']);
		}
		$user_data['wx_openid']=$res['userid'];
		$user_data['corpid']=$res['corpid'];
		$user_data['reg_time'] = time();
		$user_data['ip']=ip2long($this->ip);
		$rand_str = md5($user_data['reg_time']);
		$user_data['username'] = 'wx' . $user_data['reg_time'] . substr($rand_str, 0, 4);
		$user_data['major']=$this->major;

		if(!empty($avatar)){
			$user_data['avatar'] =$avatar;
			$user_data['wx_nickname']=$wx_nickname;
		}
//		$res['userid']='1254565412212';$user_data=array();//测试数据
		$user= Db::name('wx_user')->where('wx_openid',$res['userid'])->find();
		if(empty($user)){
			$user_id=Db::name('wx_user')->insertGetId($user_data);
		}else{
			$user_id=$user['user_id'];
			$update_date=array('ip'=>ip2long($this->ip),'major'=>$this->major);
			if(!empty($avatar)&&!empty($wx_nickname)){
				$update_date['avatar']=$avatar;
				$update_date['wx_nickname']=$wx_nickname;
			}
			db('wx_user')->where('user_id',$user['user_id'])->update($update_date);
		}
		$token=JWT::getToken($user_id,$this->major);
//
//        $distributor_id=$this->request->get('distributor_id');
//        $app_id=$this->request->get('app_id');
//        if(!empty($distributor_id)){
//        $distributor=DistributorService::getOne([['id','=',$distributor_id],['status','=',1]]);
//        $result=UserService::update([['user_id','=',$user_id]],['distributor_bind_id'=>$distributor_id]);
//        $distributor->setInc('share_num');
//        }
//        if(!empty($app_id)){
//            $distributor=DistributorService::getOne([['app_id','=',$distributor_id],['status','=',1]]);
//            $result=UserService::update([['user_id','=',$user_id]],['distributor_bind_id'=>$distributor['id']]);
//            $distributor->setInc('share_num');
//        }



        $this->api_return_json(array('user_data'=>$user_data,'session_id'=>$token,'is_audit'=>config('config.is_audit')),1);
	}

	public function getRunData(){
		$code = $this->request->param('code');
		$encryptedData = $this->request->param('encryptedData');
		$iv = $this->request->param('iv');
		if(!isset($code)||empty($code)){
			$this->api_return_json(array('msg'=>'code异常'));
		}
		if(!isset($encryptedData)||empty($encryptedData)){
			$this->api_return_json(array('msg'=>'encryptedData异常'));
		}
		if(!isset($iv)||empty($iv)){
			$this->api_return_json(array('msg'=>'iv异常'));
		}
		$url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $this->app_id . '&secret=' . $this->app_secret . '&js_code='.$code.'&grant_type=authorization_code';
		//通过code换取openid session _key
		$res = $this->curl_get($url);
		if(!$res)
			$this->api_return_json(['msg'=>'请求微信服务器失败']);
		$res=(array)$res;
		if (!isset($res['session_key'])) {
			$this->api_return_json(['msg'=>'requestTokenFailed']);
		}

		$pc=new WXBizDataCrypt($this->app_id, $res['session_key']);
		$errCode = $pc->decryptData($encryptedData, $iv, $data);
		if ($errCode == 0||true) {
			$res = json_decode($data, true);
			$stepInfoList=$res['stepInfoList'];
			$time=array();
			$data=array();
			foreach ($stepInfoList as &$val){
				$val['timestamp']=date('Y-m-d',$val['timestamp']);
				array_push($time, $val['timestamp']);
				array_push($data, $val['step']);
			}
			$result=array('time'=>$time,'data'=>$data);
			$this->api_return_json(array('stepInfoList'=>$result),1);

		} else {
			$this->api_return_json(array('msg'=>'解密失败'));
		}
	}

	public function getPhone(){
		$code = $this->request->param('code');
		$encryptedData = $this->request->param('encryptedData');
		$iv = $this->request->param('iv');
		if(!isset($code)||empty($code)){
			$this->api_return_json(array('msg'=>'code异常'));
		}
		if(!isset($encryptedData)||empty($encryptedData)){
			$this->api_return_json(array('msg'=>'encryptedData异常'));
		}
		if(!isset($iv)||empty($iv)){
			$this->api_return_json(array('msg'=>'iv异常'));
		}

		$url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $this->app_id . '&secret=' . $this->app_secret . '&js_code='.$code.'&grant_type=authorization_code';
		//通过code换取openid session _key
		$res = $this->curl_get($url);
		if(!$res)
			$this->api_return_json(['msg'=>'请求微信服务器失败']);
		$res=(array)$res;
		if (!isset($res['session_key'])) {
			$this->api_return_json(['msg'=>'requestTokenFailed']);
		}

		$pc=new WXBizDataCrypt($this->app_id, $res['session_key']);
		$errCode = $pc->decryptData($encryptedData, $iv, $data);
		if ($errCode == 0||true) {
			$res = json_decode($data, true);
			if(!isset($res['phoneNumber'])||empty($res['phoneNumber'])){
				$this->api_return_json(array('msg'=>'手机号获取失败'));
			}
			//查询该小程序用户是否已经存在
			$user=Db::name('wx_user')->where('user_id',$this->userid)->find();
			if ($user) {
				//存在就更新登录时间，检查是否登录过期
				db('wx_user')->where('user_id',$this->userid)->update(array('phone'=>$res['phoneNumber'],'is_tied'=>1));
				$this->api_return_json(array('phone'=>$res['phoneNumber']),1);
			}
			$this->api_return_json(array('msg'=>'用户不存在'));
		} else {
			$this->api_return_json(array('msg'=>'解密失败'));
		}
	}

	//小程序卡券
	function cardCreate(){
		$jssdk=new Jssdk();
		$token=$jssdk->getAccessToken();//测试公众号的token
		$package=$jssdk->GetSignPackage();//测试公众号的token
		$url='https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token='.$token;
		//log图
		$data=array('buffer'=>new \CURLFile(realpath(CMF_ROOT.'public/static/images/headicon.png')));
		$image_url_log=$this->curl_post($url, $data);
		$image_url_log=json_decode($image_url_log)->url;

		//某一测试素材图
		$data=array('buffer'=>new \CURLFile(realpath(CMF_ROOT.'public/static/images/bg.jpg')));
		$image_url_one=$this->curl_post($url, $data);
		$image_url_one=json_decode($image_url_one)->url;
		//起止截至时间
		$begin_timestamp=time()-30;
		$end_timestamp=time()+30*24*3600;
		//创建卡券json数据 团购券
		$type='member_card';
		switch ($type){
			case 'groupon':
				$des='"deal_detail":"以下锅底2选1（有菌王锅、麻辣锅、大骨锅、番茄锅、清补 凉锅、酸菜鱼锅可选）：\n大锅1份 12元\n小锅2份 16元 "';
				$memdes='';
				break;
			case 'cash':
				$des='"least_cost": 1000,"reduce_cost": 100';
				$memdes='';
				break;
			case 'discount':
				$des='"discount": 30';
				$memdes='';
				break;
			case 'gift':
				$des='"gift":"可兑换白色bra一个"';
				$memdes='';
				break;
			case 'general_coupon':
				$des='"default_detail":"优惠券专用，填写优惠详情"';
				$memdes='';
				break;
			case 'member_card':
				$des='"discount": 10';
				$memdes='"supply_bonus": true,
			            "supply_balance": false,
			            "prerogative": "test_prerogative",
			            "auto_activate": true,
			            "custom_field1": {
			                "name_type": "FIELD_NAME_TYPE_LEVEL",
			                "url": "http://www.qq.com"
			            },
			            "activate_url": "http://www.qq.com",
			            "custom_cell1": {
			                "name": "使用入口2",
			                "tips": "激活后显示",
			                "url": "http://www.qq.com"
			            },
			            "bonus_rule": {
			                "cost_money_unit": 100,
			                "increase_bonus": 1,
			                "max_increase_bonus": 200,
			                "init_increase_bonus": 10,
			                "cost_bonus_unit": 5,
			                "reduce_money": 100,
			                "least_money_to_use_bonus": 1000,
			                "max_reduce_bonus": 50
			            },';
				break;
			default:
				$des='';
				$memdes='';
				break;
		}

		$card_res=$this->card_type($type);
		$card_type=$card_res['card_type'];
		$card_name=$card_res['card_name'];
		$data='{
    		"card": {
	    		"card_type": "'.$card_type.'",
	    		"'.$card_name.'": {
		    		"base_info": {
			    		"logo_url":  "'.$image_url_log.'",
			    		"brand_name": "微信餐厅",
			    		"code_type": "CODE_TYPE_TEXT",
			    		"title": "132元双人火锅套餐",
			    		"color": "Color010",
			    		"notice": "使用时向服务员出示此券",
			    		"service_phone": "020-88888888",
			    		"description": "不可与其他优惠同享\n如需团购券发票，请在消费时向商户提出\n店内均可使用，仅限堂食",
			    		"date_info": {
				    		"type": "DATE_TYPE_FIX_TIME_RANGE",
				    		"begin_timestamp": "'.$begin_timestamp.'",
				    		"end_timestamp": "'.$end_timestamp.'"
			    		},
				    	"sku": {
				    		"quantity": 500000
				    	},
				    	"use_limit":100,
				    	"get_limit": 3,
				    	"use_custom_code": false,
				    	"bind_openid": false,
				    	"can_share": true,
				    	"can_give_friend": true,
				    	"location_id_list": [
					    	123,
					    	12321,
					    	345345
				    	],
				    	"center_title": "云货舱",
				    	"center_sub_title": "立享优惠",
				    	"center_app_brand_user_name": "gh_83c581f00e36@app",
				    	"center_app_brand_pass":"pages/template/tabbar/tabbar",
				    	"custom_url_name": "立即使用",
				    	"custom_app_brand_user_name": "gh_83c581f00e36@app",
				    	"custom_app_brand_pass":"pages/template/tabbar/tabbar",
				    	"custom_url_sub_title": "前往使用",
				    	"promotion_url_name": "更多优惠",
				    	"promotion_url": "http://www.qq.com",
				    	"source": "大众点评"
	    			},
	    			"advanced_info": {
			    		"use_condition": {
			    		"accept_category": "鞋类",
			    		"reject_category": "阿迪达斯",
			    		"can_use_with_other_discount": true
			    		},
			    		"abstract": {
			    		"abstract": "微信餐厅推出多种新季菜品，期待您的光临",
			    		"icon_url_list": [
			    		"'.$image_url_log.'"
			    				]
			    		},
			    		"text_image_list": [
			    		{
			    			"image_url": "'.$image_url_one.'",
			    			"text": "此菜品精选食材，以独特的烹饪方法，最大程度地刺激食 客的味蕾"
			    		},
			    		{
			    			"image_url": "'.$image_url_one.'",
			    			"text": "此菜品迎合大众口味，老少皆宜，营养均衡"
			    		}
			    		],
			    		"time_limit": [
				    		{
				    			"type": "MONDAY",
				    			"begin_hour":0,
				    			"end_hour":10,
				    			"begin_minute":10,
				    			"end_minute":59
				    		},
				    		{
				    			"type": "HOLIDAY"
				    		}
			    		],
		    			"business_service": [
				    		"BIZ_SERVICE_FREE_WIFI",
				    		"BIZ_SERVICE_WITH_PET",
				    		"BIZ_SERVICE_FREE_PARK",
				    		"BIZ_SERVICE_DELIVER"
		    			]
		    		},'.$memdes.'
	    			'.$des.'
	    		}
	    	}
	    }';
		$url='https://api.weixin.qq.com/card/create?access_token='.$token;
		$res=$this->curl_post($url, $data);
		$card_id=json_decode($res)->card_id;
		$ret=array();
		$ret['cardId']=$card_id;
		$ret['time']=time();
		//$arr['code'] = 1434008071;
    	$arr['timestamp'] = $ret['time'];
   	 	$arr['ticket'] = $package['ticket'];
    	$arr['nonce_str'] = '123';
    	$arr['card_id'] = $card_id;

	    sort($arr,SORT_STRING);

	    $str = '';
	    foreach ($arr as $v) {
	        $str .= $v;
	    }

    	$sign = sha1($str);
		$ret['signature']=$sign;
		$ret['ticket']=$package['ticket'];
		$this->api_return_json(array('url'=>$ret),1);
		$url='https://api.weixin.qq.com/card/qrcode/create?access_token='.$token;
		$data='{
			"action_name": "QR_CARD",
			"expire_seconds": 1800,
			"action_info": {
			"card": {
			"card_id": "'.$card_id.'",
			"is_unique_code": false ,
			"outer_str":"12b"
			  }
			 }
			}';
		$res=$this->curl_post($url, $data);
		$show_qrcode_url=json_decode($res)->show_qrcode_url;
		//设置体验白名单，用于开发者调试用
		$url='https://api.weixin.qq.com/card/testwhitelist/set?access_token='.$token;
		$data='{
		  "username": [
		      "fcy736337824",
		      "empcity"
		  ]
		 }';
		$this->curl_post($url, $data);
		//白名单ending...
		if(!isset($show_qrcode_url)||empty($show_qrcode_url)){
			exit('二维码生成失败');
		}
		$this->api_return_json(array('url'=>$show_qrcode_url),1);
	}

	function card_type($type){
		//团购券
		$data=array('groupon'=>array('card_type'=>'GROUPON','card_name'=>'groupon'),
				'cash'=>array('card_type'=>'CASH','card_name'=>'cash'),
				'discount'=>array('card_type'=>'DISCOUNT','card_name'=>'discount'),
				'gift'=>array('card_type'=>'GIFT','card_name'=>'gift'),
				'general_coupon'=>array('card_type'=>'GENERAL_COUPON','card_name'=>'general_coupon'),
				'member_card'=>array('card_type'=>'MEMBER_CARD','card_name'=>'member_card')
		);
		return $data[$type];
	}
}
