<?php
namespace app\appapi\controller\v1;

use app\appapi\ApiController;
use think\facade\Db;

use app\common\lib\Aes;
use app\common\lib\Vcard;


class Card extends ApiController
{
	/**
	* 檢查nfc用户
	*
	* @author wayne <wwayne.hsu@gmail.com>
	*
	* @param string  token  加密參數
	*
	* @return json
	*/
	public function checkUser(){
		$token = input('token');

		if(!$token){
			return $this->error('參數錯誤');
		}

		$aes = new Aes([]);
		parse_str($aes->descrypt($token),$params);

		if(!isset($params['verify_code'])){
			if(!isset($params['user_id'])){
				return $this->error('參數錯誤');
			}
			$user_id = $params['user_id'];
		}else{
			if(strlen($params['verify_code'])>0){
				$user_id = getUseridByCuid(strtoupper($params['verify_code']));
			}else{
				return $this->error('參數錯誤');
			}
		}


		if($user_id){
			Db::name('user')
			->where('user_id',$user_id)
			->inc('nfc_count')
			->update();

			return $this->success($user_id);
		}

		//檢查是否為預開卡會員
		$is_precard=Db::name('precard')
		->where('verify_code',strtoupper($params['verify_code']))
		->count();


		if($is_precard){
			return $this->success(['verify'=>strtoupper($params['verify_code'])],201);
		}

		return $this->error('請求錯誤');
	}

    public function getCard(){
        $do=Db::name('user');

		if(input('userid')){
			$do->where('user_id',input('userid'));
		}elseif(input('line_id')){
			$do->where('line_id',input('line_id'));
		}else{
			return $this->error('查無會員資料');
		}

		
		$user = $do->find();
		if(!$user){
			return $this->error('查無會員資料');
		}

		$aes = new Aes([]);

        if(strlen($user['uniqid'])>0){
            $params = urlencode($aes->encrypt('verify_code='.$user['uniqid']));
        }else{
            $params = urlencode($aes->encrypt('user_id='.$user['user_id']));
        }

        $user['nfcurl'] = getUrl().'/card/?params='.$params;


		$result = [
			"address" => $user['address']?$user['address']:' ', 
			"company" => $user['company']?$user['company']:' ', 
			"email" => $user['email']?$user['email']:' ',
			"logo" => "https://i.imgur.com/GclvYFK.png", 
			"maps" => "https://www.google.com/maps/search/?api=1&query_place_id=ChIJAaZEqCYWaTQRMv6fuIsJEuo&query=%E5%BE%AE%E7%A8%8B%E5%BC%8F%E8%B3%87%E8%A8%8A&openExternalBrowser=1", 
		 	"name" => $user['real_name']?$user['real_name']:' ',
			"phone" => $user['phone']?$user['phone']:' ', 
			"tel" => $user['tel']?$user['tel']:' ', 
			"title" => $user['title']?$user['title']:' ', 
			"url" => $user['url']?$user['url']:' ',
			"line" => $user['line']?$user['line']:'',
			"facebook" => $user['facebook']?$user['facebook']:'',
			"youtube" => $user['youtube']?$user['youtube']:'',
			"ig" => $user['ig']?$user['ig']:'',
			"level" => $user['level']?$user['level']:0,
			"user_id" => $user['user_id']?$user['user_id']:'',
			"line_picture" => $user['line_picture']?$user['line_picture']:'',
			"avatar" => $user['avatar']?$user['avatar']:'',
			"card_title" => $user['card_title']?$user['card_title']:'',
			"has_cuscard" => strlen($user['cus_card'])?1:0,
			"nc_type" => $user['nc_type']?$user['nc_type']:0,
			"nc_func" => explode(',',$user['nc_func']),
			"nc_template" => $user['nc_template'],
			"mark" => nl2br($user['mark']),
			"nfcurl" => $user['nfcurl'],
			"show_cus" => $user['show_cus'],
			"nfc_addon" => json_decode($user['nfc_addon'])
		]; 
				  
		
        return $this->Success($result);
    }    

	public function getCusCard(){
		$data=input();
        unset($data['version']);
        unset($data['controller']);
        unset($data['action']);

		try{

			$do=Db::name('user');
			if(input('userid')){
				$do->where('user_id',input('userid'));
			}elseif(input('line_id')){
				$do->where('line_id',input('line_id'));
			}else{
				return $this->error('查無會員資料');
			}
	
			$card = $do->field('cus_card,card_title')
			->find();
	

		}catch(Exception $e){
			return $this->error('操作失敗');
		}
		return $this->success($card);		
	}

	public function getVipCard(){
		$data=input();
        unset($data['version']);
        unset($data['controller']);
        unset($data['action']);

		try{
			$do=Db::name('user_card');
			if(input('userid')){
				$id = getIdByUid(input('userid'));
			}elseif(input('line_id')){
				$id = getIdByUid(input('lineid'));
			}else{
				return $this->error('查無會員資料');
			}
			$do->where('user_id',$id);
			$card = $do->field('*')
			->select();
	
		}catch(Exception $e){
			return $this->error('操作失敗');
		}
		return $this->success($card);		
	}

	public function updateCard(){
		$data=input();
		unset($data['uid']);
		unset($data['version']);
        unset($data['controller']);
		unset($data['action']);
		unset($data['nfcurl']);
		unset($data['agent_prefix']);
		unset($data['level_name']);
		unset($data['addon']);
		unset($data['delete_time']);

		if(!empty(input('addon'))){
			$data['nfc_addon']=json_encode(input('addon'));
		}else{
			$data['nfc_addon']='';
		}

		try{
			Db::name('user')
			->where('user_id',$data['user_id'])
			->update($data);
			
			Vcard::genVcf($data['user_id']);


		}catch(Exception $e){
			return $this->error('操作失敗');
		}
		return $this->success(['code'=>200]);		
	}

	public function updateCusCard(){
		
		$data=input();
        unset($data['version']);
        unset($data['controller']);
        unset($data['action']);

		$data['show_cus'] = input('show_cus')?1:0;

		try{
			Db::name('user')
			->where('user_id',$data['user_id'])
			->update(['card_title'=>$data['card_title'],'show_cus'=>$data['show_cus'],'cus_card'=>$data['cus_card']]);

		}catch(Exception $e){
			return $this->error('操作失敗');
		}
		return $this->success(['code'=>200]);		
	}


	public function uploadFile(){
		// print_r(input());
		$files = request()->file('file');

		$savename =  \think\facade\Filesystem::disk('public')->putFile( 'card', $files);;

		$image_url = getUrl().'/storage/'.$savename;

		return $this->success($image_url);
	}

}
