<?php

namespace plugin\admin\app\controller;

use plugin\admin\app\common\Auth;
use plugin\admin\app\model\Admin as AdminModel;
use plugin\admin\app\model\AdminAccess;
use plugin\admin\app\model\AdminRole;
use support\exception\BusinessException;
use support\Request;
use support\Response;
use Throwable;

/**
 * 管理员列表 
 */
class AdminController extends Crud
{
    /**
     * 不需要鉴权的方法
     * @var array
     */
    protected $noNeedAuth = ['select'];

    /**
     * @var AdminModel
     */
    protected $model = null;

    /**
     * 开启auth数据限制
     * @var string
     */
    protected $dataLimit = 'auth';

    /**
     * 以id为数据限制字段
     * @var string
     */
    protected $dataLimitField = 'id';

    /**
     * 构造函数
     * @return void
     */
    function __construct()
    {
        $this->model = new AdminModel;
    }

    /**
     * 查询
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function select(Request $request): Response
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        $query = $this->doSelect($where, $field, $order);
        if ($format === 'select') {
            return $this->formatSelect($query->select());
        }
        $paginator = $query->paginate($limit);
        $items = $paginator->items();
        $admin_ids = array_column($items, 'id');
        $roles = AdminAccess::whereIn('admin_id', $admin_ids)->select();
        $roles_map = [];
        foreach ($roles as $role) {
            $roles_map[$role['admin_id']][] = $role['role_id'];
        }
        $login_admin_id = admin_id();
        /** @var AdminModel $item */
        foreach ($items as $index => $item) {
            $admin_id = $item->id;
            $items[$index]['roles'] = isset($roles_map[$admin_id]) ? implode(',', $roles_map[$admin_id]) : '';
            $items[$index]['role_name'] = $items[$index]['roles'] ? AdminRole::where('id',$items[$index]['roles'])->value('name') : '';
            $items[$index]['show_toolbar'] = $admin_id != $login_admin_id;
        }
        return json(['code' => 0, 'msg' => 'ok', 'count' => $paginator->total(), 'data' => $items]);
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException|Throwable
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            $data = $this->insertInput($request);
            $data['status'] =   1;
            unset($data['id']);
            $admin_id = $this->doInsert($data);
            $role_ids = $request->post('roles');
            $role_ids = $role_ids ? explode(',', $role_ids) : [];
            if (!$role_ids) {
                return $this->fail('至少选择一个角色组');
            }
            if (!Auth::isSuperAdmin() && array_diff($role_ids, Auth::getScopeRoleIds())) {
                return $this->fail('角色超出权限范围');
            }

            AdminAccess::where('admin_id', $admin_id)->delete();
            foreach ($role_ids as $id) {
                $admin_role = new AdminAccess;
                $admin_role->admin_id = $admin_id;
                $admin_role->role_id = $id;
                $admin_role->save();
            }
            return $this->success( '保存成功', ['id' => $admin_id]);
        }
        return view('admin/update',[
            'row' =>    []
        ]);
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException|Throwable
     */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {

            [$id, $data] = $this->updateInput($request);
            $admin_id = $request->post('id');
            if (!$admin_id) {
                return $this->fail('缺少参数');
            }

            // 不能禁用自己
            if (isset($data['status']) && $data['status'] != 1 && $id == admin_id()) {
                return $this->fail('不能禁用自己');
            }

            // 需要更新角色
            $role_ids = $request->post('roles');
            if ($role_ids !== null) {
                if (!$role_ids) {
                    return $this->fail('至少选择一个角色组');
                }
                $role_ids = explode(',', $role_ids);

                $is_supper_admin = Auth::isSuperAdmin();
                $exist_role_ids = AdminAccess::where('admin_id', $admin_id)->column('role_id');
                $scope_role_ids = Auth::getScopeRoleIds();
                if (!$is_supper_admin && !array_intersect($exist_role_ids, $scope_role_ids)) {
                    return $this->fail('无权限更改该记录');
                }
                if (!$is_supper_admin && array_diff($role_ids, $scope_role_ids)) {
                    return $this->fail('角色超出权限范围');
                }

                // 删除账户角色
                $delete_ids = array_diff($exist_role_ids, $role_ids);
                AdminAccess::whereIn('role_id', $delete_ids)->where('admin_id', $admin_id)->delete();
                // 添加账户角色
                $add_ids = array_diff($role_ids, $exist_role_ids);
                foreach ($add_ids as $role_id) {
                    $admin_role = new AdminAccess;
                    $admin_role->admin_id = $admin_id;
                    $admin_role->role_id = $role_id;
                    $admin_role->save();
                }
            }
            unset($data['roles']);

            $this->doUpdate($id, $data);
            return $this->success('保存成功');
        }
        $ids = Request()->get('ids');
        if($ids){
            $row = $this->model->where('id', $ids)->find();
        }

        return view('admin/update',[
            'row'=> $row
        ]);
    }

    /**
     * 删除
     * @param Request $request
     * @return Response
     */
    public function delete(Request $request): Response
    {
        $primary_key = $this->model->getPk();
        $ids = $request->post('ids');
        if (!$ids) {
            return $this->success("操作成功");
        }
        $ids = (array)$ids;
        if (in_array(admin_id(), $ids)) {
            return $this->fail('不能删除自己');
        }
        if (!Auth::isSuperAdmin() && array_diff($ids, Auth::getScopeAdminIds())) {
            return $this->fail('无数据权限');
        }
        $this->model->whereIn($primary_key, $ids)->each(function (AdminModel $admin) {
            $admin->delete();
        });
        AdminRole::whereIn('admin_id', $ids)->each(function (AdminRole $admin_role) {
            $admin_role->delete();
        });
        return $this->success("操作成功");
    }


}
