<?php

namespace app\appapi\controller\v1;

use app\appapi\ApiController;

use think\facade\Db;

use app\service\Sso;

class User extends ApiController
{
    public function getUserInfo()
    {

        $data = input();

        //使用者不存在,至SSO Server取得
        if(env('app.app_sso_login')==true){
            $user = Db::name('users')
            ->field('user_id,sso_user_id,headimg,user_money,frozen_money,reg_time,mobile_phone,email,real_name,refer_code,parent_id,is_validated,is_slash,is_resale')
            ->where('sso_user_id', $this->uid)
            ->find();

            if (!$user) {
                $user_data = [
                    'user_id' => $this->uid,
                ];
    
                $sso = Sso::getUserInfo($user_data);
    
                if (!$sso['code'] == 200) {
                    return $this->error('get sso user info error!!!');
                }
    
                $sso_data = $sso['data'];
    
                $is_slash = 0;
                
                if(!empty($sso_data['user_app'])){
                    foreach ($sso_data['user_app'] as $value) {
                        if($value['app']=='card'){
                            if($value['status']==1){
                                $is_slash = 1;
                            }
                            break;
                        }
                    }    
                }
    
                try {
    
                    $data = [
                        'sso_user_id' => $sso_data['user_id'],
                        'user_name' => $sso_data['phone'],
                        'headimg' => $sso_data['avatar'],
                        'reg_time' => time(),
                        'mobile_phone' => $sso_data['phone'],
                        'real_name' => $sso_data['real_name'],
                        'line_id' => $sso_data['line_id'],
                        'line_name' => $sso_data['line_name'],
                        'line_picture' => $sso_data['line_picture'],
                        'refer_code' => $sso_data['code'],
                        'parent_id' => $sso_data['parent_id'],
                        'is_slash' => $is_slash,
                    ];
    
                    Db::name('users')
                        ->insert($data);
    
                    $user = Db::name('users')
                        ->field('user_id,sso_user_id,headimg,user_money,frozen_money,reg_time,mobile_phone,real_name,refer_code,parent_id')
                        ->where('sso_user_id', $this->uid)
                        ->find();
                } catch (\Exception $e) {
    
                    return $this->error('sync sso user info error!!!');
                }
            }    
        }else{
            $user = Db::name('users')
            ->field('user_id,sso_user_id,headimg,user_money,frozen_money,reg_time,mobile_phone,email,real_name,refer_code,parent_id,is_validated,is_slash,is_resale')
            ->where('user_id', $this->uid)
            ->find();

            if(!$user)
                return $this->error('請登入後再操作');
        }

        //推薦人
        $user['parent_name'] = Db::name('users')->where('sso_user_id', $user['parent_id'])->value('sso_user_id');
        //推薦連結
        $user['refer_url'] = getUrl() . '/m/?refer=' . $user['refer_code'];
        //推薦人數
        $user['refer_num'] = Db::name('users')->where('parent_id', $this->uid)->count();

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

    public function updateUserInfo()
    {
        $data = input('post.');

        $user = Db::name('users')
            ->where('sso_user_id', $this->uid)
            ->update($data);

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

    public function getBank()
    {
        //取得用戶銀行資料
        $bank = Db::name('user_bank')
            ->field('bank_name,bank_code,bank_account')
            ->where('user_id', $this->user_id)
            ->find();

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

    public function updateBank()
    {
        $data = input('post.');
        if (empty($data['bank_name']) || empty($data['bank_code']) || empty($data['bank_account'])) {
            return $this->Error('參數錯誤');
        }
        //如果存在用戶銀行帳戶就更新，不存在就新增
        $bank = Db::name('user_bank')
            ->where('user_id', $this->user_id)
            ->find();
        try {
            if ($bank) {
                $res = Db::name('user_bank')
                    ->where('user_id', $this->user_id)
                    ->update($data);
            } else {
                $data['user_id'] = $this->user_id;
                $res = Db::name('user_bank')
                    ->insert($data);
            }
        } catch (\Exception $e) {
            return $this->Error($e->getMessage());
        }
        return $this->Success('更新成功');
    }


    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 setAuthUser()
    {
        $rule = [
            'user_id' => [
                'require' => 'require'
            ],
            'a_hour' => [
                'require' => 'require',
                'min' => 1,
                'max' => 24
            ]
        ];

        $msg = [
            'user_id' => [
                'require' => '客戶ID不得為空'
            ],
            'a_hour' => [
                'require' => '授權時數不得為空',
                'min' => '授權時數最少1小時',
                'max' => '授權時數最多24小時'
            ]
        ];

        $result = $this->validate(input(), $rule, $msg);

        if (!$result) {
            return $this->Success($validate->getError());
        }

        $auth_time = time() + input('a_hour') * 60 * 60;

        $res = Db::name('user_auth')->insert([
            'user_id' => input('uid'),
            'auth_user_id' => input('user_id'),
            'auth_time' => $auth_time
        ]);
        return $this->Success('更新成功');
    }

    public function getAuthUsers()
    {
        $result = Db::name('user_auth')
            ->where('user_id', getIdBySsoId(input('uid')))
            ->where('auth_time', '>', time())
            ->order('id', 'desc')
            ->select()
            ->toArray();


        $authList = [];

        foreach ($result as $key => $val) {
            $authList[$key]['id'] = $val['id'];
            $authList[$key]['user_id'] = $val['auth_user_id'];
            $authList[$key]['auth_time'] = date('Y-m-d h:i:s', $val['auth_time']);
        }

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

    public function delAuthUser()
    {

        $id = input('id');

        try {

            $rtn = Db::name('user_auth')
                ->where('id', $id)
                ->delete();

            return $this->Success('刪除成功');
        } catch (\Exception $e) {
            return $this->Error('刪除失敗');
        }
    }

    public function getAuthList()
    {
        $result = Db::name('user_auth')
            ->where('auth_user_id', input('uid'))
            ->where('auth_time', '>', time())
            ->order('id', 'desc')
            ->select()
            ->toArray();

        $authList = [];

        foreach ($result as $key => $val) {
            $authList[$key]['id'] = $val['id'];
            $authList[$key]['user_id'] = $val['user_id'];
            $authList[$key]['auth_time'] = date('Y-m-d h:i:s', $val['auth_time']);
        }

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

    public function addUserAddress()
    {
        $user_address = [
            'user_id' => $this->user_id,
            'address_name' => input('name'),
            'consignee' => input('consignee'),
            'tel' => input('tel'),
            'zipcode' => input('zipcode'),
            'city' => input('city'),
            'district' => input('district'),
            'address' => input('address'),
            'is_default' => input('is_default') ? 1 : 0,
        ];

        try {
            if (input('is_default') == 1) {
                Db::name('user_address')
                    ->where('user_id', getIdBySsoId($this->uid))
                    ->update(['is_default' => 0]);
            }

            Db::name('user_address')
                ->insert($user_address);

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

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

    public function delUserAddress()
    {
        try {
            $result = Db::name('user_address')
                ->where('address_id', input('id'))
                ->delete();

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


    public function getUserAddress()
    {
        try {
            $result = Db::name('user_address')
                ->where('user_id', getIdBySsoId($this->uid))
                ->select();

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

    public function setUserAddressDefault()
    {
        try {
            Db::name('user_address')
                ->where('user_id', $this->user_id)
                ->update(['is_default' => 0]);

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

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

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

    public function getUserDefaultAddress()
    {
        try {
            $result = Db::name('user_address')
                ->where('user_id', getIdBySsoId($this->uid))
                ->where('is_default', 1)
                ->find();
            if (!$result) {
                return $this->success('沒有預設地址', 201);
            }
            return $this->Success($result);
        } catch (\Exception $e) {
            return $this->Error('操作失敗');
        }
    }

    public function getUserOrders()
    {

        $orders = Db::name('order_info')
            ->where('user_id', $this->uid)
            ->select()
            ->order('order_id', 'desc')
            ->toArray();

        foreach ($orders as $key => $val) {
            $orders[$key]['goods_num'] = Db::name('order_goods')->where('order_id', $val['order_id'])->count();
        }

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


    public function getUserAccounts()
    {
        //取得user_account table的資料
        if (!$this->uid) {
            return $this->Error('請先登入', 401);
        }

        $page = input('page') ? intval(input('page')) : 0;

        $user_accounts = Db::name('user_account')
            ->where('user_id', $this->user_id)
            ->order('id', 'desc')
            ->limit((($page - 1) * 10), 10)
            ->select()
            ->toArray();

        //foreach user_accounts table的資料,修改值
        foreach ($user_accounts as $key => $val) {

            $user_accounts[$key]['add_time'] = date('Y-m-d H:i:s', $val['add_time']);
            switch ($val['process_type']) {
                case 0:
                    $user_accounts[$key]['process_type'] = '充值';
                    break;
                case 1:
                    $user_accounts[$key]['process_type'] = '取款';
                    break;
                default:
                    $user_accounts[$key]['process_type'] = '未知';
                    break;
            }

            switch ($val['is_paid']) {
                case 0:
                    $user_accounts[$key]['is_paid'] = '未支付';
                    break;
                case 1:
                    $user_accounts[$key]['is_paid'] = '已支付';
                    break;
                case 2:
                    $user_accounts[$key]['is_paid'] = '已取消';
                    break;
                default:
                    $user_accounts[$key]['is_paid'] = '未知';
                    break;
            }
        }

        $result = [
            'total' =>  Db::name('user_account')
                ->where('user_id', $this->user_id)
                ->count(),
            'page' => $page,
            'data' => $user_accounts
        ];

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

    public function addUserAccount()
    {
        $data = input('post.');
        $ua_data = [
            'user_id' => $this->user_id,
            'amount' => input('amount'),
            'process_type' => 1,
            'add_time' => time(),
            'user_note' => isset($data['user_note']) ? input('user_note') : '',
            'is_paid' => 0
        ];

        try {
            Db::name('user_account')->insert($ua_data);
            //取得user_account table的資料
            $user_accounts = Db::name('user_account')
                ->where('user_id', $this->user_id)
                ->order('id', 'desc')
                ->select()
                ->toArray();

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

                $user_accounts[$key]['add_time'] = date('Y-m-d H:i:s', $val['add_time']);
                switch ($val['process_type']) {
                    case 0:
                        $user_accounts[$key]['process_type'] = '充值';
                        break;
                    case 1:
                        $user_accounts[$key]['process_type'] = '取款';
                        break;
                    default:
                        $user_accounts[$key]['process_type'] = '未知';
                        break;
                }

                switch ($val['is_paid']) {
                    case 0:
                        $user_accounts[$key]['is_paid'] = '未支付';
                        break;
                    case 1:
                        $user_accounts[$key]['is_paid'] = '已支付';
                        break;
                    case 2:
                        $user_accounts[$key]['is_paid'] = '已取消';
                        break;
                    default:
                        $user_accounts[$key]['is_paid'] = '未知';
                        break;
                }
            }

            return $this->Success($user_accounts);
        } catch (\Exception $e) {
            print_r($e->getMessage());
            return $this->Error('操作失敗');
        }
    }

    public function delUserAccount()
    {
        $id = input('id');
        if (empty($id)) {
            return $this->Error('操作失敗');
        }
        //將user_account table的資料is_paid改為2
        try {
            Db::name('user_account')
                ->where('id', $id)
                ->update(['is_paid' => 2]);
        } catch (\Exception $e) {
            return $this->Error('操作失敗');
        }

        return $this->Success('操作成功');
    }

    public function getUserAccInfo()
    {
        //在users table取得user_id的資料
        $user = Db::name('users')
            ->field('user_money, frozen_money')
            ->where('user_id', $this->user_id)
            ->find();

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

    public function getShareInfo()
    {
        $level = $this->countLevelMembers($this->uid);

        $share_member_obj = Db::name('users')
            ->field('user_money, frozen_money')
            ->where('parent_id', $this->uid);

        $share_member_num = $share_member_obj->count();

        if (isset($level[1]) && $level[1] > 0) {
            $tran_rate = round($level[1] / $share_member_num, 2) * 100;
        } else {
            $tran_rate = 0;
        }

        $result = [
            'l1_num' => isset($level[1]) ? $level[1] : 0,
            'share_num' => $share_member_num,
            'tran_rate' => $tran_rate,
            'l2_num' => isset($level[2]) ? $level[2] : 0,
            'l3_num' => isset($level[3]) ? $level[3] : 0,
            'l4_num' => isset($level[4]) ? $level[4] : 0,
        ];

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

    public function updateUserResale()
    {
        $user = Db::name('users')
            ->where('sso_user_id', $this->uid)
            ->update(['is_resale' => 1]);

        return $this->Success('申請成功');
    }

    public function getRecommandList()
    {
        $page = input('page') ? intval(input('page')) : 0;

        $users = Db::name('users')
            ->where('parent_id', $this->uid)
            ->order('reg_time', 'desc')
            ->field('sso_user_id, real_name, is_validated,is_slash,is_resale')
            ->limit((($page - 1) * 10), 10)
            ->select()
            ->toArray();

        foreach ($users as $key => $val) {
            $users[$key]['is_slash'] = $val['is_slash'] == 1 ? 'Slash客戶' : '一般客戶';
            //real_name 只顯示頭尾,中間加*
            if(mb_strlen($val['real_name'],"utf-8")>2){
                $users[$key]['real_name'] = mb_substr($val['real_name'], 0, 1, 'utf-8') . str_repeat('*', mb_strlen($val['real_name'], 'utf-8') - 2) . mb_substr($val['real_name'], -1, 1, 'utf-8');
            }elseif(mb_strlen($val['real_name'],"utf-8")>1){
                $users[$key]['real_name'] = mb_substr($val['real_name'], 0, 1, 'utf-8') .'*';
            }else{
                $users[$key]['real_name'] = $val['real_name'];
            }
        }

        $result = [
            'total' =>  Db::name('users')
                ->where('parent_id', $this->uid)
                ->count(),
            'page' => $page,
            'data' => $users
        ];

        return $this->Success($result);
    }
    /*
    *   計算下線人數
    */
    private function countLevelMembers($users, $deep = 1)
    {
        $level = array();

        if ($deep > 3) {
            return 0;
        }

        if (!is_array($users)) {
            $users = [$users];
        }

        $userDo = Db::name('users')
            ->whereIn('parent_id', $users)
            ->where('is_validated', 1);

        $level_num = $userDo->count();

        if ($level_num > 0) {
            $level[$deep] = $level_num;
        }

        if ($level_num > 0) {
            $user_list = $userDo->column('sso_user_id');
            $rtn = $this->countLevelMembers($user_list, $deep + 1);
            if ($rtn) {
                $level = $level + $rtn;
            }
        }

        return $level;
    }
}
