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

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

use GuzzleHttp\Client;

use app\common\lib\Aes;
use app\common\lib\Sign;

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

        //使用者不存在,至SSO Server取得
        if(!$user){
            $user_data = [
                'appid' => 'sc',
                'user_id' => $this->uid,
                'timestamp' => time()
            ];
            $sign = Sign::genSign($user_data);
            $user_data['sign'] = $sign;
                
            $client = new Client([
                'base_uri' => 'https://sso.h888.fun/api/v1/'
            ]);

            $response = $client->get('user/getInfo?'.http_build_query($user_data));
            if($response->getStatusCode()!=200){
                return $this->error('get sso user info error!!!');
            }

            $sso_data = json_decode($response->getBody()->getContents(),true)['data'];

            try{
                $sso_data['cus_card']='';
                Db::name('user')
                ->insert($sso_data);
                
                $user=Db::name('user')
                ->where('user_id',$this->uid)
                ->find();        

            }catch(\Exception $e){
                return $this->error('sync sso user info error!!!');
            }    
        }

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

        // $user['level_name'] = Db::name('user_level')->where('agent_id',$user['agent_id'])->where('level_id',$user['level'])->value('name');

        switch($user['level']){
            case 0:
                $user['level_name']='未付費用戶';
                break;
            case 1:
                $user['level_name']='付費用戶';
                break;
            default:
                break;
        }

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

        $user['nc_func'] = explode(',',$user['nc_func']);

        $user['agent_prefix'] = Db::name('agent')->where('id',$user['agent_id'])->value('prefix');

        return $this->Success($user);
    }    

    public function getUserCompany(){
        if(!$this->uid){
            $this->error('用戶ID錯誤');
        }
        
        $result = Db::name('user_company')
        ->where('user_id',$this->uid)
        ->select();

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

    public function addUserCompany(){
        if(!$this->uid){
            $this->error('用戶ID錯誤');
        }

        $ucData = input('post.');
        $ucData['user_id'] = $this->uid;
        unset($ucData['uid']);
        unset($ucData['action']);

        try{
            if(isset($ucData['is_default']) && $ucData['is_default']){

                Db::name('user_company')
                ->where('user_id',$this->uid)
                ->update(['is_default'=>0]);                

                Db::name('user')
                ->where('user_id',$this->uid)
                ->update([
                    'company' => isset($ucData['uc_name'])?$ucData['uc_name']:'',
                    'title' => isset($ucData['uc_title'])?$ucData['uc_title']:'',
                    'tel' => isset($ucData['uc_tel'])?$ucData['uc_tel']:'',
                    'address' => isset($ucData['uc_address'])?$ucData['uc_address']:'',
                    'url' => isset($ucData['uc_url'])?$ucData['uc_url']:'',
                ]);
    
            }
            Db::name('user_company')
            ->insert($ucData);

            $result = Db::name('user_company')
            ->where('user_id',$this->uid)
            ->select();

            return $this->success($result);

        }catch(\Exception $e){
            print_r($e);
            return $this->error('操作錯誤');
        }
    }

    public function setUCDefault(){
        if(!$this->uid){
            $this->error('用戶ID錯誤');
        }

        try{
            Db::name('user_company')
                ->where('user_id',$this->uid)
                ->update(['is_default'=>0]);                

            Db::name('user_company')
                ->where('id',input('id'))
                ->update(['is_default'=>1]);

            $res = Db::name('user_company')
            ->where('id',input('id'))
            ->find();

            Db::name('user')
            ->where('user_id',$this->uid)
            ->update([
                'company' => $res['uc_name'],
                'title' => $res['uc_title'],
                'tel' => $res['uc_tel'],
                'address' => $res['uc_address'],
                'url' => $res['uc_url'],
            ]);

            //更新用戶資料
            $result = Db::name('user_company')
                ->where('user_id',$this->uid)
                ->select();

            return $this->success($result);

        }catch(\Exception $e){
            print_r($e);
            return $this->error('操作錯誤');
        }
    }

    public function updateUserCompany(){
        if(!$this->uid){
            $this->error('用戶ID錯誤');
        }
        $ucData = input('post.');
        unset($ucData['action']);
        unset($ucData['uid']);
        try{

            if(isset($ucData['is_default']) && $ucData['is_default']){
                Db::name('user_company')
                ->where('user_id',$this->uid)
                ->update(['is_default'=>0]);                

                Db::name('user')
                ->where('user_id',$this->uid)
                ->update([
                    'company' => $ucData['uc_name'],
                    'title' => $ucData['uc_title'],
                    'tel' => $ucData['uc_tel'],
                    'address' => $ucData['uc_address'],
                    'url' => $ucData['uc_url'],
                ]);
            }
            
            Db::name('user_company')
                ->where('user_id',$this->uid)
                ->update($ucData);

            $res = Db::name('user_company')
            ->where('id',input('id'))
            ->find();

            //更新用戶資料
            $result = Db::name('user_company')
                ->where('user_id',$this->uid)
                ->select();

            return $this->success($result);

        }catch(\Exception $e){
            print_r($e);
            return $this->error('操作錯誤');
        }
    }

    public function deleteUserCompany(){
        if(!$this->uid){
            $this->error('用戶ID錯誤');
        }

        try{
            Db::name('user_company')
            ->where('id',input('id'))
            ->delete();    

            //更新用戶資料
            $result = Db::name('user_company')
                ->where('user_id',$this->uid)
                ->select();

            if(count($result)==0){
                Db::name('user')
                ->where('user_id',$this->uid)
                ->update([
                    'company' => '',
                    'title' => '',
                    'tel' => '',
                    'address' => '',
                    'url' => '',
                ]);

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

        }catch(\Exception $e){
            return $this->error('操作錯誤');
        }


    }

    public function setUserLevel(){
        $result=Db::name('user')
		->where('user_id',$this->uid)
		->update(['level'=>input('level')]);

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

    public function setUserTpl(){
        try{
            $result=Db::name('user')
            ->where('user_id',$this->uid)
            ->update(['nc_template'=>input('tpl')]);    
        }catch(\Excenption $e){
            return $this->Error('更新失敗');
        }
        		
        return $this->Success($result);
    }        

    public function uploadAvatar(){

		$files = request()->file('file');
		$savename =  \think\facade\Filesystem::disk('public')->putFile( input('user_id'), $files);

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

        
        // Db::name('user')
        // ->where('user_id',input('user_id'))
        // ->update(['avatar'=>$avatar]);

        return $this->Success($avatar);
    }

    public function updateSendCount(){
        $user_id = input('userid');
        
        Db::name('user')
        ->where('user_id',input('userid'))
        ->exp('send_count', 'send_count+1')
        ->update();
        // ->inc('send_count',1);

        return $this->Success('更新成功');
    }

    public function addFavorite(){
        try{
            $is_exist = Db::name('user_favorite')
            ->where('user_id',$this->uid)
            ->where('uf_user_id',input('userid'))
            ->count();

            if(!$is_exist){
                Db::name('user_favorite')
                ->insert(['user_id'=>$this->uid,'uf_user_id'=>input('userid')]);    
            }
            return $this->success('操作成功');
        }catch(\Exception $e){
            return $this->error('操作失敗');
        }
    }

    public function delFavorite(){
        try{
            Db::name('user_favorite')
            ->where('id',input('id'))
            ->delete();

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

    public function uploadConnections(){
        try{
            Db::name('user')
            ->where('user_id',$this->uid)
            ->update(['connections'=>input('uc')]);

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

    public function getFavorite(){
        try{
            $uf = Db::name('user_favorite')
            ->alias('uf')
            ->leftjoin('user u','uf.uf_user_id = u.user_id')
            ->field('uf.id as ufid,u.*')
            ->where('uf.user_id',$this->uid)
            ->select()
            ->toArray();

//             print_r(Db::getLastSql());
// print_r($uf);
// return;
            $aes = new Aes([]);

            foreach($uf as $key=>$val){

                if(strlen($val['uniqid'])>0){
                    $params = urlencode($aes->encrypt('verify_code='.$val['uniqid']));
                }else{
                    $params = urlencode($aes->encrypt('user_id='.$val['user_id']));
                }
        
                $uf[$key]['nfcurl'] = getUrl().'/card/?params='.$params;        

            }   

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

    public function getConnections(){
        try{
            $result = Db::name('user')
            ->where('user_id',$this->uid)
            ->value('connections');

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

}
