<?php

namespace App\Services\Auth;

use App\Events\LogoutUser;
use App\Exceptions\AlertException;
use App\Models\Appearance\AppearanceModel;
use App\Models\PartnerModel;
use App\Models\User\AuthKey;
use App\Models\User\UserModel;
use App\Services\Service;

class AuthKeyService extends Service
{
    public function bindKey(int $uid, string $key, string $type)
    {
        $m = new AuthKey();
        if ($m->where([['uid', $uid], ['auth_type', $type]])->exists()) {
            throw new AlertException("你已经绑定了该认证方式", 201);
        }
        if ($m->where('auth_key', $key)->exists()) {
            throw new AlertException("已经被绑定，请先解绑", 400);
        }
        $m->fill([
            'uid' => $uid,
            'auth_key' => $key,
            'auth_type' => $type,
        ]);
        if ($m->save()) {
            return true;
        } else {
            throw new AlertException("网络繁忙|E_DB", 500);
        }
    }


    /**
     * 注销用户
     * @param int $uid
     * @return bool
     * @throws \Exception
     */
    public function logout($uid)
    {
        \DB::beginTransaction();
        try {
            AuthKey::where('uid', '=', $uid)->delete();
            // 删除手机号+注销时间
            UserModel::where('uid', $uid)->update(['phone' => null, 'logoff_at' => time()]);
            // 下架卡片
            PartnerModel::where('uid', $uid)->update([
                'check_photo' => -1,
                'photo_1_check' => -1,
                'photo_2_check' => -1,
                'photo_3_check' => -1,
                'photo_4_check' => -1,
                'voice_check' => -1,
                'intro_check' => -1,
                'is_sell' => 0,
                'is_commit_check' => 0,
                'is_recommend' => 0,
                'is_voice_recommend' => 0,
            ]);
            // 解绑openid
            \DB::table('kddx_user_openid')->where('uid', $uid)->update(['uid' => 0]);

            AppearanceModel::where('uid', $uid)->delete();

            \DB::commit();
            // 用户注销事件
            event(new LogoutUser($uid));

            return true;
        } catch (\Exception $exception) {
            \DB::rollBack();
            throw $exception;
        }
    }
}
