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

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

use app\api\validate\User as UserValidate;
use think\exception\ValidateException;


class User extends ApiController
{
    public function list(){


    }    

    public function add(){

        //參數檢查
        try {
            validate(UserValidate::class)->check(input());
        } catch (ValidateException $e) {
            // 驗證失敗 輸出錯誤信息

            // dump($e->getError());
            return $this->Error($e->getError(),501,'參數錯誤');
        }

        $prefix = getPrefixByAppId(input('appid'));
        $data['user_id']=$prefix.input('user_id');
        $data['real_name']=input('name');
        $data['level']=input('level')?input('level'):0;
        $data['overdue_time']=input('overdue_time')?input('overdue_time'):(time()+(60*60*24*7));
        $data['cus_card'] = '';
        $data['create_time'] = date('Y-m-d H:i:s');
        
        //檢查 User ID
        $is_exist = Db::name('user')
        ->where('user_id',$data['user_id'])
        ->count();

        if($is_exist){
            return $this->Error('使用者帳號己存在',502,'請求失敗');
        }


        try{
            //產生暫時編號
            $data['uniqid']='tg'.genUniqid();

            $id = Db::name('user')
            ->insertGetId($data);
    
            $refer_code = encodeRefer($id);
    
            $result = Db::name('user')
            ->where('id',$id)
            ->update(['code'=>$refer_code]);
    
            $qrcodeUrl = genQrCode('https://'.$_SERVER['HTTP_HOST'].'/home/?aid='.$agent['prefix'],$data['user_id'],'refer');

            $nfcUrl = genQrCode('https://'.$_SERVER['HTTP_HOST'].'/card?userid='.$data['user_id'],$data['user_id'],'nfc');
                            
            return $this->Success($data['uniqid']);
    
        }catch(\Exception $e){
            return $this->Error('系統錯誤',500,'新增失敗');
        }

    }    

    public function setLevel(){
        //參數檢查
        try {
            validate(\app\api\validate\UserLevel::class)->check(input());
        } catch (ValidateException $e) {
            return $this->Error($e->getError(),501,'參數錯誤');
        }

        $prefix = getPrefixByAppId(input('appid'));
        $user_id=$prefix.input('user_id');
        $level=input('level')?input('level'):0;
        $overdue_time=input('overdue_time')?input('overdue_time'):(time()+(60*60*24*365));

        try{
            $result=Db::name('user')
            ->where('user_id',$user_id)
            ->update(['level'=>$level,'overdue_time'=>$overdue_time]);
        }catch(\Exception $e){
            return $this->Error('系統錯誤',500,'新增失敗');
        }
		
        return $this->Success('更新成功');
    }        
}
