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

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

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

class User extends ApiController
{
    public function getInfo()
    {
        $id=$this->request->uid;
        $result=Db::name('user')
        ->where('id',$id)
        ->find();

        if(!$result){
            $result=[];
        }
        // foreach($result as $key=>$val){
        //     // $rtn=Db::name('goods')->where('gc_id',$val['id'])->select()->toArray();
        //     // if($rtn){
        //     //     $result[$key]['goods']=[];
        //     // }
        //     $result[$key]['goods']=Db::name('goods')->where('gc_id',$val['id'])->select()->toArray();
        // }
        return $this->Success($result);
    }

    // 取得會員資料
    public function getUsers(){
        $do=Db::name('user');

        if(!input('search')){
            $result=$do
            ->page(input('current'),input('size'))
            ->order('id','desc')
            ->select()->toArray();
    
            $total=$do
            ->count();    
        }else{
            $result=$do
            ->where('user_id','like','%'.input('search').'%')
            ->page(input('current'),input('size'))
            ->order('id','desc')
            ->select()->toArray();
    
            $total=$do
            ->where('user_id','like','%'.input('search').'%')
            ->count();    
        }

        if(!$result){
            $result=[];
        }

        $aes = new Aes([]);

        foreach($result as $key => $val){
            $result[$key]['level_name']= Db::name('user_level')->where('level_id',$val['level'])->where('agent_id',$val['agent_id'])->value('name');

            if($val['parent_id']>0){
                $result[$key]['parent_name']=Db::name('user')->where('id',$val['parent_id'])->value('real_name');
            }
            if($val['overdue_time']>0){
                $result[$key]['overdue'] = date('Y-m-d',$val['overdue_time']);
            }else{
                $result[$key]['overdue'] = '無限期';
            }
            if(strlen($val['uniqid'])>0){
                $uniqid = $val['uniqid'];
            }else{
                $uniqid = '00000000';
            }
            $params = urlencode($aes->encrypt('user_id='.$val['user_id'].'&verify_code='.$uniqid));
            $result[$key]['nfcurl']= getUrl().'/card/?params='.$params;
        }

        $rtn=[
            'total' => $total,
            'data' => $result
        ];

        return $this->Success($rtn);

    }

    public function getUser(){

        $id=input('id');

        $result=Db::name('user')
        ->where('id',$id)
        ->find();



        if(!$result){
            $result=[];
        }

        $levels=Db::name('user_level')
        ->where('agent_id',$result['agent_id'])
        ->select();

        $result['levels']=$levels;
        

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

    public function addUser(){

        $req=input();
        unset($req['version']);
        unset($req['controller']);
        unset($req['action']);
        $req['user_id'] = 'mc'.uniqid();
        $req['line_id'] = $req['user_id'];
        $req['create_time']=date('Y-m-d H:i:s');
        $req['update_time']=date('Y-m-d H:i:s');

        $result=Db::name('user')
        ->insert($req);

        if(!$result){
            $result=[];
        }

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

    public function updateUser(){

        $req=input();
        unset($req['version']);
        unset($req['controller']);
        unset($req['action']);
        unset($req['levels']);
        unset($req['status']);

        $level_option = Db::name('user_level')
        ->where('agent_id',$req['agent_id'])
        ->where('level_id',$req['level'])
        ->find();

        $req['nc_type']=$level_option['nc_type'];
        $req['nc_func']=$level_option['nc_func'];

        $req['update_time']=date('Y-m-d H:i:s');

        $result=Db::name('user')
        ->where('id',$req['id'])
        ->update($req);

        Vcard::genVcf(input('user_id'));

        if(!$result){
            $result=[];
        }

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

    public function deleteUser(){
        $id=input('id');

        $result=Db::name('user')
        ->where('id',$id)
        ->delete();

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

    public function updateStatus(){
        $id=input('id');
        $status=input('status');

        $result=Db::name('user')
        ->where('id',$id)
        ->update(['status'=>$status]);

        if(!$result){
            $result=[];
        }

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

    public function getUserCard(){

        $id=input('id');

        $result=Db::name('user_card')
        ->field('id,type,title,content,nfc_show,sort_id')
        ->where('user_id',$id)
        ->order('sort_id')
        ->select();


        if(!$result){
            $result=[];
        }

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

    public function uploadAvatar(){
		$files = request()->file('avatar');
		$savename =  \think\facade\Filesystem::disk('public')->putFile( input('id'), $files);

		$avatar = getUrl().'/storage/'.$savename;
        
        return $this->Success($avatar);        
    }

    public function updateUserCard(){
        $user_id=input('id');
        $cards=input('cards');

        Db::name('user_card')
        ->where('user_id',$user_id)
        ->delete();

        foreach($cards as $key => $val){
            $nfc_show = $val['nfc_show']?1:0;

            Db::name('user_card')
            ->insert([
                'user_id' => $user_id,
                'type' => $val['type'],
                'title' => $val['title'],
                'content' => $val['content'],
                'nfc_show' => $nfc_show,
                'sort_id' => $key,
                'create_time' => time()
            ]);
        }

        // if(!$result){
        //     $result=[];
        // }

        return $this->success(['code'=>200]);
    }

    public function updateVerifyCode(){
        $id=input('id');
        $uniqid=strtoupper(input('code'));

        $result=Db::name('user')
        ->where('id',$id)
        ->update(['uniqid'=>$uniqid]);

        return $this->success('設定成功');
    }

    // 取得預開卡資料
    public function getPrecard(){
        $do=Db::name('precard');

        if(!input('search')){
            $result=$do
            ->page(input('current'),input('size'))
            ->order('id','desc')
            ->select()->toArray();
    
            $total=$do
            ->count();    
        }else{
            $result=$do
            ->where('user_id','like','%'.input('search').'%')
            ->page(input('current'),input('size'))
            ->order('id','desc')
            ->select()->toArray();
    
            $total=$do
            ->where('user_id','like','%'.input('search').'%')
            ->count();    
        }

        if(!$result){
            $result=[];
        }

        foreach($result as $key => $val){
            $aes = new Aes([]);
            $nfc_url = 'user_id='.$val['user_id'].'&verify_code='.$val['verify_code'];            
            $result[$key]['params'] = getUrl().'/card/'.urlencode($aes->encrypt($nfc_url));
        }

        $rtn=[
            'total' => $total,
            'data' => $result
        ];

        return $this->Success($rtn);

    }

    
}
