<?php

declare(strict_types=1);

namespace app\admin\controller\auth;

use Throwable;
use ba\Tree;
use support\think\Db;
use support\validation\Validator;
use support\validation\ValidationException;
use app\admin\model\AdminRule;
use app\admin\model\AdminGroup;
use app\common\controller\Backend;
use support\Response;
use Webman\Http\Request;

class Group extends Backend
{
    protected string $authMethod = 'allAuthAndOthers';

    protected ?object $model = null;

    protected string|array $preExcludeFields = ['create_time', 'update_time'];

    protected string|array $quickSearchField = 'name';

    protected Tree $tree;

    protected array $initValue = [];

    protected string $keyword = '';

    protected bool $assembleTree = true;

    protected array $adminGroups = [];

    protected function initController(Request $request): ?Response
    {
        $this->model = new AdminGroup();
        $this->tree  = Tree::instance();

        $isTree          = $request->get('isTree') ?? $request->post('isTree') ?? true;
        $initValue       = $request->get('initValue') ?? $request->post('initValue') ?? [];
        $this->initValue = is_array($initValue) ? array_filter($initValue) : [];
        $this->keyword   = $request->get('quickSearch') ?? $request->post('quickSearch') ?? '';

        $this->assembleTree = $isTree && !$this->initValue;

        $this->adminGroups = Db::name('admin_group_access')->where('uid', $this->auth->id)->column('group_id');
        return null;
    }

    public function index(Request $request): Response
    {
        $response = $this->initializeBackend($request);
        if ($response !== null) return $response;

        if ($request->get('select') ?? $request->post('select')) {
            return $this->select($request);
        }

        return $this->success('', [
            'list'   => $this->getGroups($request),
            'group'  => $this->adminGroups,
            'remark' => get_route_remark(),
        ]);
    }

    public function add(Request $request): Response
    {
        $response = $this->initializeBackend($request);
        if ($response !== null) return $response;

        if ($request->method() === 'POST') {
            $data = $request->post();
            if (!$data) {
                return $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            $rulesRes = $this->handleRules($data);
            if ($rulesRes instanceof Response) return $rulesRes;

            $result = false;
            $this->model->startTrans();
            try {
                if ($this->modelValidate) {
                    try {
                        $rules = [
                            'name'  => 'required|string',
                            'rules' => 'required',
                        ];
                        $messages = [
                            'rules.required' => __('Please select rules'),
                        ];
                        Validator::make($data, $rules, $messages)->validate();
                    } catch (ValidationException $e) {
                        throw $e;
                    }
                }
                $result = $this->model->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                return $this->error($e->getMessage());
            }
            if ($result !== false) {
                return $this->success(__('Added successfully'));
            }
            return $this->error(__('No rows were added'));
        }

        return $this->error(__('Parameter error'));
    }

    public function edit(Request $request): Response
    {
        $response = $this->initializeBackend($request);
        if ($response !== null) return $response;

        $pk  = $this->model->getPk();
        $id  = $request->get($pk) ?? $request->post($pk);
        $row = $this->model->find($id);
        if (!$row) {
            return $this->error(__('Record not found'));
        }

        $authRes = $this->checkAuth($id);
        if ($authRes !== null) return $authRes;

        if ($request->method() === 'POST') {
            $data = $request->post();
            if (!$data) {
                return $this->error(__('Parameter %s can not be empty', ['']));
            }

            $adminGroup = Db::name('admin_group_access')->where('uid', $this->auth->id)->column('group_id');
            if (in_array($data['id'], $adminGroup)) {
                return $this->error(__('You cannot modify your own management group!'));
            }

            $data = $this->excludeFields($data);
            $rulesRes = $this->handleRules($data);
            if ($rulesRes instanceof Response) return $rulesRes;

            $result = false;
            $this->model->startTrans();
            try {
                if ($this->modelValidate) {
                    try {
                        $rules = [
                            'name'  => 'required|string',
                            'rules' => 'required',
                        ];
                        $messages = [
                            'rules.required' => __('Please select rules'),
                        ];
                        Validator::make($data, $rules, $messages)->validate();
                    } catch (ValidationException $e) {
                        throw $e;
                    }
                }
                $result = $row->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                return $this->error($e->getMessage());
            }
            if ($result !== false) {
                return $this->success(__('Update successful'));
            }
            return $this->error(__('No rows updated'));
        }

        $pidArr = AdminRule::field('pid')
            ->distinct()
            ->where('id', 'in', $row->rules)
            ->select()
            ->toArray();
        $rules  = $row->rules ? explode(',', $row->rules) : [];
        foreach ($pidArr as $item) {
            $ruKey = array_search($item['pid'], $rules);
            if ($ruKey !== false) {
                unset($rules[$ruKey]);
            }
        }
        $rowData = $row->toArray();
        $rowData['rules'] = array_values($rules);
        return $this->success('', [
            'row' => $rowData
        ]);
    }

    public function del(Request $request): Response
    {
        $response = $this->initializeBackend($request);
        if ($response !== null) return $response;

        $ids  = $request->get('ids') ?? $request->post('ids') ?? [];
        $ids  = is_array($ids) ? $ids : [];
        $data = $this->model->where($this->model->getPk(), 'in', $ids)->select();
        foreach ($data as $v) {
            $authRes = $this->checkAuth($v->id);
            if ($authRes !== null) return $authRes;
        }
        $subData = $this->model->where('pid', 'in', $ids)->column('pid', 'id');
        foreach ($subData as $key => $subDatum) {
            if (!in_array($key, $ids)) {
                return $this->error(__('Please delete the child element first, or use batch deletion'));
            }
        }

        $adminGroup = Db::name('admin_group_access')->where('uid', $this->auth->id)->column('group_id');
        $count      = 0;
        $this->model->startTrans();
        try {
            foreach ($data as $v) {
                if (!in_array($v['id'], $adminGroup)) {
                    $count += $v->delete();
                }
            }
            $this->model->commit();
        } catch (Throwable $e) {
            $this->model->rollback();
            return $this->error($e->getMessage());
        }
        if ($count) {
            return $this->success(__('Deleted successfully'));
        }
        return $this->error(__('No rows were deleted'));
    }

    public function select(Request $request): Response
    {
        $response = $this->initializeBackend($request);
        if ($response !== null) return $response;

        $data = $this->getGroups($request, [['status', '=', 1]]);

        if ($this->assembleTree) {
            $data = $this->tree->assembleTree($this->tree->getTreeArray($data));
        }
        return $this->success('', [
            'options' => $data
        ]);
    }

    /**
     * @return array|Response
     */
    private function handleRules(array &$data)
    {
        if (!empty($data['rules']) && is_array($data['rules'])) {
            $superAdmin   = true;
            $checkedRules = [];
            $allRuleIds   = AdminRule::column('id');

            foreach ($data['rules'] as $postRuleId) {
                if (in_array($postRuleId, $allRuleIds)) {
                    $checkedRules[] = $postRuleId;
                }
            }

            foreach ($allRuleIds as $ruleId) {
                if (!in_array($ruleId, $checkedRules)) {
                    $superAdmin = false;
                }
            }

            if ($superAdmin && $this->auth->isSuperAdmin()) {
                $data['rules'] = '*';
            } else {
                $ownedRuleIds = $this->auth->getRuleIds();

                if (!array_diff($ownedRuleIds, $checkedRules)) {
                    return $this->error(__('Role group has all your rights, please contact the upper administrator to add or do not need to add!'));
                }

                if (array_diff($checkedRules, $ownedRuleIds) && !$this->auth->isSuperAdmin()) {
                    return $this->error(__('The group permission node exceeds the range that can be allocated'));
                }

                $data['rules'] = implode(',', $checkedRules);
            }
        } else {
            unset($data['rules']);
        }
        return $data;
    }

    private function getGroups(Request $request, array $where = []): array
    {
        $pk      = $this->model->getPk();
        $initKey = $request->get('initKey') ?? $pk;

        $absoluteAuth = $request->get('absoluteAuth') ?? false;

        if ($this->keyword) {
            $keyword = explode(' ', $this->keyword);
            foreach ($keyword as $item) {
                $where[] = [$this->quickSearchField, 'like', '%' . $item . '%'];
            }
        }

        if ($this->initValue) {
            $where[] = [$initKey, 'in', $this->initValue];
        }

        if (!$this->auth->isSuperAdmin()) {
            $authGroups = $this->auth->getAllAuthGroups($this->authMethod, $where);
            if (!$absoluteAuth) {
                $authGroups = array_merge($this->adminGroups, $authGroups);
            }
            $where[] = ['id', 'in', $authGroups];
        }
        $data = $this->model->where($where)->select()->toArray();

        foreach ($data as &$datum) {
            if ($datum['rules']) {
                if ($datum['rules'] == '*') {
                    $datum['rules'] = __('Super administrator');
                } else {
                    $rules = explode(',', $datum['rules']);
                    if ($rules) {
                        $rulesFirstTitle = AdminRule::where('id', $rules[0])->value('title');
                        $datum['rules']  = count($rules) == 1 ? $rulesFirstTitle : __('%first% etc. %count% items', ['%first%' => $rulesFirstTitle, '%count%' => count($rules)]);
                    }
                }
            } else {
                $datum['rules'] = __('No permission');
            }
        }

        return $this->assembleTree ? $this->tree->assembleChild($data) : $data;
    }

    private function checkAuth($groupId): ?Response
    {
        $authGroups = $this->auth->getAllAuthGroups($this->authMethod, []);
        if (!$this->auth->isSuperAdmin() && !in_array($groupId, $authGroups)) {
            return $this->error(__($this->authMethod == 'allAuth' ? 'You need to have all permissions of this group to operate this group~' : 'You need to have all the permissions of the group and have additional permissions before you can operate the group~'));
        }
        return null;
    }
}
