<?php

namespace App\Http\Controllers;

use App\Http\Requests\CreateAdminInput;
use App\Http\Requests\UpdateAdminNickname;
use App\Http\Requests\UpdateAdminPassword;
use App\Models\Admin;
use App\Models\AdminAccount;
use App\Models\AdminAuth;
use App\Models\AdminToken;
use App\Models\Auth;
use Illuminate\Support\Str;
use Yo;
use Login;

class AdminController extends Controller
{
  public function delete()
  {
    Login::admin([6]);
    $ids = request()->post('ids');
    $super_admin_count = Admin::whereIn('id', $ids)->where('admin_auth_id', -1)->where('del', 2)->count();
    if ($super_admin_count > 0) Yo::error_echo(100018);
    Admin::whereIn('id', $ids)->update([
      'del' => 1
    ]);
    AdminAccount::whereIn('admin_id', $ids)->where('del', 2)->update([
      'del' => 1
    ]);
    return Yo::delete_echo($ids);
  }

  public function update(UpdateAdminNickname $request)
  {
    Login::admin([6]);
    $admin_id = $request->post('admin_id');
    $nickname = $request->post('nickname');
    $status = $request->post('status');
    $admin_auth_id = $request->post('admin_auth_id');
    $admin = Admin::find($admin_id);
    if (!$admin) Yo::error_echo(100000, ['管理员']);
    if ($admin->admin_auth_id != -1 && $admin_auth_id == -1) Yo::error_echo(100018);
    if ($admin->admin_auth_id == -1 && $admin_auth_id != -1) Yo::error_echo(100018);
    if ($admin->admin_auth_id == -1 && $status == 2) Yo::error_echo(100018);
    $admin->nickname = $nickname;
    $admin->admin_auth_id = $admin_auth_id;
    $admin->status = $status;
    $admin->save();
    return Yo::update_echo($admin->id);
  }

  public function create(CreateAdminInput $request)
  {
    Login::admin([6]);
    $nickname = $request->post('nickname');
    $account = $request->post('account');
    $password = $request->post('password');
    $admin_auth_id = request()->post('admin_auth_id');
    if ($admin_auth_id == -1) Yo::error_echo(100018);
    $admin_account_check = AdminAccount::select('id')
      ->where('account', $account)
      ->where('type', 1)
      ->where('del', 2)
      ->first();
    if ($admin_account_check) Yo::error_echo(100017);
    $admin = new Admin();
    $admin->nickname = $nickname;
    $admin->admin_auth_id = $admin_auth_id;
    $admin->save();
    $admin_account = new AdminAccount();
    $admin_account->admin_id = $admin->id;
    $admin_account->account = $account;
    $admin_account->secret = bcrypt($password);
    $admin_account->type = 1;
    $admin_account->save();
    return Yo::create_echo($admin->id);
  }

  public function list()
  {
    Login::admin([6]);
    $status = request()->post('status');
    $search = request()->post('search');
    $admin_list = Admin::select('*')
      ->selectRaw("IFNULL((select name from admin_auths where admins.admin_auth_id = admin_auths.id),'') as admin_auth_name")
      ->selectRaw("IFNULL((select account from admin_accounts where admins.id = admin_accounts.admin_id and del = 2),'') as account")
      ->selectRaw("IFNULL((select id from admin_accounts where admins.id = admin_accounts.admin_id and del = 2),'') as account_id")
      ->where(function ($query) use ($status) {
        if ($status != 0) $query->where('status', $status);
      })
      ->where(function ($query) use ($search) {
        if ($search != '') $query->where('nickname', 'like', "%$search%");
      })
      ->where('del', 2)
      ->paginate(15);
    return Yo::echo($admin_list);
  }

  public function edit_password(UpdateAdminPassword $request)
  {
    Login::admin([6]);
    $account_id = request()->post('account_id');
    $password = $request->post('password');
    $admin_account = AdminAccount::where('id', $account_id)->first();
    if (!$admin_account) Yo::error_echo(100002);
    $admin_account->secret = bcrypt($password);
    $admin_account->save();
    return Yo::update_echo(Login::$info->id);
  }

  public function change_password(UpdateAdminPassword $request)
  {
    Login::admin();
    $account_id = request()->post('account_id');
    $password = $request->post('password');
    $old_password = request()->post('old_password');
    $admin_account = AdminAccount::where('id', $account_id)->where('admin_id', Login::$info->id)->first();
    if (!$admin_account) Yo::error_echo(100002);
    if (!password_verify($old_password, $admin_account->secret)) Yo::error_echo(100010);
    if ($old_password === $password) Yo::error_echo(100009);
    $admin_account->secret = bcrypt($password);
    $admin_account->save();
    return Yo::update_echo(Login::$info->id);
  }

  public function change_nickname(UpdateAdminNickname $request)
  {
    Login::admin();
    $nickname = $request->post('nickname');
    Admin::where('id', Login::$info->id)->update([
      'nickname' => $nickname
    ]);
    return Yo::update_echo(Login::$info->id);
  }

  public function menu()
  {
    Login::admin();
    $menu_group = Auth::select('id', 'name', 'title', 'icon', 'status')
      ->where('type', 1)->where('show', 1)->where('del', 2)
      ->orderBy('order', 'desc')->get();
    $list = [];
    foreach ($menu_group as $item) {
      switch (Login::$info->admin_auth_id) {
        case -1:
          $auth_list = Auth::select('id', 'name', 'title', 'icon', 'status')->where('pid', $item->id)
            ->where('type', 2)->where('show', 1)->where('del', 2)
            ->orderBy('order', 'desc')->get();
          break;
        case 0:
          $auth_list = Auth::select('id', 'name', 'title', 'icon', 'status')->where('pid', $item->id)
            ->where('type', 2)->where('check_type', 1)->where('show', 1)->where('del', 2)
            ->orderBy('order', 'desc')->get();
          break;
        default:
          $admin_auth = AdminAuth::find(Login::$info->admin_auth_id);
          $auth_ids = json_decode($admin_auth->auth_ids, true);
          $auth_list = Auth::select('id', 'name', 'title', 'icon', 'status')
            ->where(function ($query) use ($auth_ids, $item) {
              $query->whereIn('id', $auth_ids)->where('pid', $item->id)->where('type', 2)->where('check_type', 2)->where('show', 1)->where('del', 2);
            })
            ->orWhere(function ($query) use ($auth_ids, $item) {
              $query->where('type', 2)->where('pid', $item->id)->where('check_type', 1)->where('show', 1)->where('del', 2);
            })
            ->orderBy('order', 'desc')->get();
      }
      if (count($auth_list) !== 0) $list[] = [
        "id" => $item->id,
        "name" => $item->name,
        "title" => $item->title,
        "icon" => $item->icon,
        "status" => $item->status,
        "children" => $auth_list
      ];
    }
    return Yo::echo([
      'list' => $list
    ]);
  }

  public function info()
  {
    Login::admin();
    $admin_account = AdminAccount::where('admin_id', Login::$info->id)
      ->where('type', 1)
      ->where('del', 2)
      ->first();
    return Yo::echo([
      'info' => [
        'id' => Login::$info->id,
        'account' => $admin_account ? $admin_account->account : '',
        'account_id' => $admin_account ? $admin_account->id : 0,
        'nickname' => Login::$info->nickname,
      ]
    ]);
  }

  public function status()
  {
    Login::admin();
    return Yo::echo();
  }

  public function create_token($admin, $type): string
  {
    if ($admin->status != 1 || $admin->del != 2) Yo::error_echo(100002);
    $token = Str::orderedUuid();
    $admin_token = new AdminToken();
    $admin_token->admin_id = $admin->id;
    $admin_token->token = $token;
    $admin_token->type = $type;
    $admin_token->del = 2;
    $admin_token->save();
    return $token;
  }

  public function login()
  {
    $account = request()->post('account');
    $password = request()->post('password');
    $type = 1;
    $admin_account = AdminAccount::where('account', $account)
      ->where('type', 1)
      ->where('del', 2)
      ->first();
    if (!$admin_account) Yo::error_echo(100004);
    if (!password_verify($password, $admin_account->secret)) Yo::error_echo(100004);
    $admin = Admin::where('id', $admin_account->admin_id)
      ->where('status', 1)
      ->where('del', 2)
      ->first();
    if (!$admin) Yo::error_echo(100002);
    Login::$info = $admin;
    Login::$login_type = $type;
    $auth_check_res = Login::check_admin_auth([2]);
    if ($auth_check_res !== 0) Yo::error_echo($auth_check_res);
    $token = $this->create_token($admin, $type);
    return Yo::echo([
      'token' => $token
    ]);
  }
}
