<?php

namespace app\admin\controller\sys_manage;

use app\admin\validate\sys_manage\MenuValidate;
use app\common\Tree;
use app\controller\Curd;
use app\model\SysMenu;
use app\model\SysRole;
use app\model\SysUser;
use support\Db;
use support\exception\BusinessException;
use support\Request;
use support\Response;

class MenuController extends Curd
{
    public function __construct()
    {
        $this->model = new SysMenu();
        $this->validate = true;
        $this->validateClass = new MenuValidate();
    }

    /**
     * @Desc 列表
     * @Author Gorden
     * @Date 2024/3/12 14:07
     *
     * @param Request $request
     * @return Response
     * @throws \support\exception\BusinessException
     */
    public function select(Request $request): Response
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        $format = $request->get('format', 'menu_tree');
        $order = $request->get('order', 'desc');
        $field = $field ?? 'menu_sort';
        $limit = 1000;
        $query = $this->doSelect($where, $field, $order);
        return $this->doFormat($query, $format, $limit);
    }

    public function save(Request $request)
    {
        $params = $request->post();
        $data = [
            'menu_pid' => $params['parentId'],
            'menu_icon' => $params['meta']['icon'] ?? '',
            'menu_name' => $params['name'],
            'menu_title' => $params['meta']['title'],
            'menu_uri' => $params['redirect'] ?? '',
            'menu_route' => $params['path'],
            'menu_component' => $params['component'] ?? '',
            'menu_sort' => $params['meta']['sort'] ?? 0,
            'menu_is_show' => isset($params['meta']['hidden']) && $params['meta']['hidden'] ? 2 : 1,
            'menu_is_menu' => $params['meta']['type'] == 'menu' ? 1 : 2,
            'menu_status' => $params['meta']['status'] == true ? 1 : 2,
//            'level' => $params['level'],
        ];
        $operate = $params['operate'];
        if ($operate == 'add') {
            if ($this->validate && !$this->validateClass->scene('add')->check($data)) {
                return json_fail($this->validateClass->getError());
            }

            try {
                $data = $this->inputFilter($data);
                $id = $this->doInsert($data);
            } catch (BusinessException $customException) {
                return json_fail($customException->getMessage());
            } catch (\Exception $exception) {
                return json_fail('数据写入失败');
            }
            // 写操作日志
            _syslog("添加菜单", "添加菜单【" . $data['menu_name'] . '】', $data);
            return json_success('success', ['id' => $id]);
        } else if ($operate == 'update') {
            $data['goods_id'] = $params['id'];
            $goodsId = $data['goods_id'];
            if ($this->validate && !$this->validateClass->scene('update')->check($data)) {
                return json_fail($this->validateClass->getError());
            }

            try {
                $data = $this->inputFilter($data);
                $this->doUpdate($goodsId, $data);
            } catch (BusinessException $customException) {
                return json_fail($customException->getMessage());
            } catch (\Exception $e) {
                return json_fail('数据更新失败');
            }
            // 记录日志
            _syslog("修改菜单", "修改菜单【" . $data['menu_title'] . '】', $data);

            return json_success('success', ['id' => $params['id']]);
        }

        return json_fail('请求失败~');
    }

    /**
     * @Desc 执行插入
     * @Author Gorden
     * @Date 2024/3/12 14:15
     *
     * @param array $data
     * @throws BusinessException\
     */
    protected function doInsert(array $data)
    {
        Db::beginTransaction();
        try {
            $primary_key = $this->model->getKeyName();
            $model_class = get_class($this->model);
            $model = new $model_class;
            foreach ($data as $key => $val) {
                $model->{$key} = $val;
            }
            $model->save();

            $prePath = '/0/';
            if ($model->menu_pid != 0) {
                $parentMenu = SysMenu::getParent($model->menu_pid);
                $prePath = $parentMenu->menu_path;
            }
            $model->menu_path = $prePath . $model->menu_id . '/';
            $model->save();
            Db::commit();

            return $model->menu_id;
        } catch (\Exception $e) {
            Db::rollBack();
            throw new BusinessException('数据写入失败~');
        }
    }

    /**
     * 执行更新
     * @param $id
     * @param $data
     * @return void
     */
    protected function doUpdate($id, $data)
    {
        $model = $this->model->find($id);
        foreach ($data as $key => $val) {
            $model->{$key} = $val;
        }
        if ($model->menu_pid != $data['menu_pid']) {
            $parentMenu = SysMenu::getParent($data['menu_pid']);
            $prePath = $parentMenu->menu_path;
            $model->menu_path = $prePath . $model->menu_id . '/';
        }

        $model->save();
    }

    protected function doFormat($query, $format, $limit): Response
    {
        $methods = [
            'select' => 'formatSelect',
            'tree' => 'formatTree',
            'menu_tree' => 'formatMenuTree',
            'table_tree' => 'formatTableTree',
            'normal' => 'formatNormal',
        ];
        $paginator = $query->paginate($limit);
        $total = $paginator->total();
        $items = $paginator->items();
        if (method_exists($this, "afterQuery")) {
            $items = call_user_func([$this, "afterQuery"], $items);
        }
        $format_function = $methods[$format] ?? 'formatNormal';
        return call_user_func([$this, $format_function], $items, $total);
    }

    /**
     * @Desc 树形输出
     * @Author Gorden
     * @Date 2024/3/12 14:22
     *
     * @param $items
     * @return Response
     */
    protected function formatTree($items): Response
    {
        $format_items = [];
        $btnAuth = []; //按钮权限
        foreach ($items as $item) {
            if ($item->menu_is_menu == 2) {
                $btnAuth[] = $item->menu_name;
            }
            $format_items[] = [
                'id' => $item->menu_id,
                'pid' => $item->menu_pid,
                'name' => $item->menu_name,
                'path' => $item->menu_route,
                'component' => $item->menu_component,
                'meta' => [
                    'icon' => $item->menu_icon,
                    'title' => $item->menu_title,
                    'type' => $item->menu_is_menu == 1 ? 'menu' : 'button',
                    'status' => $item->menu_status == 1 ? true : false,
                    'sort' => $item->menu_sort,
                    'hidden' => $item->menu_is_show == 1 ? false : true,
                ]
            ];
        }
        $tree = new Tree($format_items);

        $menu = $tree->getTree();
//        foreach ($menu as &$item) {
//            unset($item['component']);
//            unset($item['redirect']);
//        }

        $data = [
            'dashboardGrid' => ["welcome", "member", "sysManage", "about"],
            'menu' => $menu,
            'permissions' => $btnAuth //按钮权限
        ];

        return json_success('success', $data);
    }

    protected function formatMenuTree($items): Response
    {
        $format_items = [];
        foreach ($items as $item) {
            $format_items[] = [
                'id' => $item->menu_id,
                'pid' => $item->menu_pid,
                'name' => $item->menu_name,
                'path' => $item->menu_route,
                'component' => $item->menu_component,
                'meta' => [
                    'icon' => $item->menu_icon,
                    'title' => $item->menu_title,
                    'type' => $item->menu_is_menu == 1 ? 'menu' : 'button',
                    'status' => $item->menu_status == 1 ? true : false,
                    'sort' => $item->menu_sort,
                    'hidden' => $item->menu_is_show == 1 ? false : true,
                ]
            ];
        }
        $tree = new Tree($format_items);

        $menu = $tree->getTree();
//        foreach ($menu as &$item) {
//            unset($item['component']);
//        }

        return json_success('success', $menu);
    }

    public function myMenu(Request $request)
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);

        $adminId = \Tinywan\Jwt\JwtToken::getCurrentId();
        if (!$adminId) {
            throw new BusinessException("请先登录");
        }
        $user = SysUser::where('user_id', $adminId)->first();
        if (empty($user->join_user_role_id)) {
            throw new BusinessException("权限不足");
        }
        $role = SysRole::where('role_id', $user->join_user_role_id)->first();
        $permission = json_decode($role->role_permission,true);
        if (!empty($permission)){
            $where['menu_name'] = ['in', implode(',', $permission)];
        }else{
            throw new BusinessException("权限不足");
        }

        $format = $request->get('format', 'tree');
        $order = $request->get('order', 'desc');
        $field = $field ?? 'menu_sort';
//        $where['menu_is_show'] = 1;
        $where['menu_status'] = 1;
        $limit = 1000;
        $query = $this->doSelect($where, $field, $order);
        return $this->doFormat($query, $format, $limit);
    }

    /**
     * @Des
     * @Author Gorden
     * @Date 2024/3/14 10:02
     *
     * @param Request $request
     * @return Response
     */
    public function delete(Request $request): Response
    {
        Db::beginTransaction();
        try {
            $ids = $this->deleteInput($request);
            if (!$ids) {
                return json_fail('数据错误');
            }
            $menu = $this->model->whereIn('menu_id', $ids)->get();
            foreach ($menu as $item) {
                // 删菜单及子菜单
                $this->model->where('menu_path', 'like', $item->menu_path . '%')->delete();
            }
            Db::commit();
            // 记录日志
            $menu = $menu ? $menu->toArray() : [];
            _syslog("删除菜单", "删除菜单", $menu);
            return json_success('删除成功');
        } catch (\Exception $e) {
            Db::rollBack();
            return json_fail('删除失败');
        }
    }
}