<?php

declare(strict_types=1);

namespace app\admin\controller\user;

use Throwable;
use app\admin\model\UserRule;
use app\admin\model\UserGroup;
use app\common\controller\Backend;
use Webman\Http\Request;
use support\Response;

class Group extends Backend
{
    protected ?object $model = null;

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

    protected function initController(Request $request): ?Response
    {
        $this->model = new UserGroup();
        return null;
    }

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

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $data = $this->model
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->limit(9999)
            ->select()
            ->toArray();

        return $this->success('', [
            'options' => $data,
        ]);
    }

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

        if ($request->method() !== 'POST') {
            return $this->error(__('Parameter error'));
        }

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

        $data = $this->excludeFields($data);
        $data = $this->handleRules($data);

        $result = false;
        $this->model->startTrans();
        try {
            if ($this->modelValidate) {
                $validateClass = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                if (class_exists($validateClass)) {
                    $validate = new $validateClass();
                    $validate->scene('add')->check($data);
                }
            }
            $result = $this->model->save($data);
            $this->model->commit();
        } catch (Throwable $e) {
            $this->model->rollback();
            return $this->error($e->getMessage());
        }
        return $result !== false ? $this->success(__('Added successfully')) : $this->error(__('No rows were added'));
    }

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

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

        if ($request->method() === 'POST') {
            $data = $request->post();
            if (!$data) {
                return $this->error(__('Parameter %s can not be empty', ['']));
            }
            $data = $this->excludeFields($data);
            $data = $this->handleRules($data);
            $result = false;
            $this->model->startTrans();
            try {
                if ($this->modelValidate) {
                    $validateClass = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validateClass)) {
                        $validate = new $validateClass();
                        $validate->scene('edit')->check(array_merge($data, [$pk => $row[$pk]]));
                    }
                }
                $result = $row->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                return $this->error($e->getMessage());
            }
            return $result !== false ? $this->success(__('Update successful')) : $this->error(__('No rows updated'));
        }

        $pidArr = UserRule::field('pid')->distinct(true)->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]);
    }

    private function handleRules(array $data): array
    {
        if (isset($data['rules']) && is_array($data['rules']) && $data['rules']) {
            $rules = UserRule::select();
            $super = true;
            foreach ($rules as $rule) {
                if (!in_array($rule['id'], $data['rules'])) {
                    $super = false;
                    break;
                }
            }
            $data['rules'] = $super ? '*' : implode(',', $data['rules']);
        } else {
            unset($data['rules']);
        }
        return $data;
    }
}
