<?php

namespace app\admin\service\sys_manage;

use app\model\SysRole;
use support\Db;
use support\Request;

class RoleService
{
    /**
     * @Desc 角色列表
     * @Author Gorden
     * @Date 2024/2/20 16:29
     *
     * @param $page
     * @param $limit
     * @param $keyword
     * @return \support\Response
     */
    public static function roleList(Request $request)
    {
        $page = intval($request->get('page', 1));
        $pageSize = intval($request->get('pageSize', 10));
        $keyword = format_string($request->get('keyword', ''));
        $roleStatus = $request->get('role_status', '');

        $rows = SysRole::select('*')
            ->when($keyword != '', function ($query) use ($keyword) {
                $query->where('role_name', 'like', '%' . $keyword . '%');
            })
            ->when($roleStatus != '', function ($query) use ($roleStatus) {
                $query->where('role_status', $roleStatus);
            })
            ->orderBy('role_addtimes', 'DESC')
//            ->forPage($page, $pageSize)
            ->get()
            ->toArray();
        $total = SysRole::when($keyword != '', function ($query) use ($keyword) {
            $query->where('role_name', 'like', '%' . $keyword . '%');
        })->count();

        foreach ($rows as &$row) {
            if (!empty($row['role_permission']) && is_json($row['role_permission'])) {
                $row['role_permission'] = json_decode($row['role_permission']);
            }
        }

        return json_success('', compact('rows', 'page', 'pageSize', 'total'));
    }

    /**
     * @Desc 角色详情
     * @Author Gorden
     * @Date 2024/2/20 16:37
     *
     * @param $id
     * @return \support\Response
     */
    public static function roleInfo($id)
    {
        $role = SysRole::find($id);
        if (!$role) {
            return json_fail('角色不存在');
        }

        $role = $role->toArray();
        return json_success('', $role);
    }

    /**
     * @Desc 添加角色
     * @Author Gorden
     * @Date 2024/2/20 16:02
     *
     * @param $params
     * @return \support\Response
     */
    public static function insertRole($params)
    {
        try {
            Db::beginTransaction();
            $data = [
                'role_superior_id' => $params['role_superior_id'] ?? 0,
                'role_status' => $params['role_status'],
                'role_category' => $params['role_category'],
                'role_name' => $params['role_name'],
                'role_remark' => $params['role_remark'] ? format_string($params['role_remark']) : null,
                'role_extend_json' => $params['role_extend_json'] ?? null,
                'role_permission' => '[]',
                'role_addtimes' => time()
            ];
            $roleId = SysRole::insertGetId($data);
            $path = '/0/';
            if (!empty($params['role_superior_id'])) {
                $superior = SysRole::find($params['role_superior_id']);
                dump($superior);
                if (!isset($superior->role_path)) {
                    Db::rollBack();
                    return json_fail("上级角色不存在");
                }
                $path = $superior->role_path;
            }
            SysRole::where('role_id', $roleId)->update(['role_path' => $path . $roleId . '/']);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollBack();
            dump($e->getMessage());
            return json_fail('角色添加失败');
        }

        return json_success('角色添加成功');
    }

    /**
     * @Desc 修改角色
     * @Author Gorden
     * @Date 2024/2/20 16:02
     *
     * @param $id
     * @param $params
     * @return \support\Response
     */
    public static function updateRole($id, $params)
    {
        $role = SysRole::find($id);
        $oldPath = $role->role_path;
        if (!$role) {
            return json_fail('角色不存在');
        }
        try {
            Db::beginTransaction();
            $data = [
                'role_superior_id' => $params['role_superior_id'] ?? 0,
                'role_status' => $params['role_status'],
                'role_category' => $params['role_category'],
                'role_name' => $params['role_name'],
                'role_remark' => $params['role_remark'] ? format_string($params['role_remark']) : null,
                'role_extend_json' => $params['role_extend_json'] ?? '{}',
            ];
            if ($data['role_superior_id'] == 0) {
                $data['role_path'] = '/0/' . $id . '/';
            } else if ($data['role_superior_id'] != $role->role_superior_id) {
                $superior = SysRole::find($data['role_superior_id']);
                $data['role_path'] = $superior->role_path . $id . '/';
                $child = SysRole::where('role_path', 'like', $oldPath . '%')->get();
                dump($child);
                foreach ($child as $item) {
                    $childPath = str_replace($oldPath, $data['role_path'], $item->role_path);
                    SysRole::where('role_id', $item->role_id)->update(['role_path'=>$childPath]);
                }
            }
            dump($data);
            if (!SysRole::where('role_id', $id)->update($data)) {
                Db::rollBack();
                throw new \Exception('角色修改失败');
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollBack();
            return json_fail($e->getMessage());
        }

        return json_success('角色修改成功');
    }

    public static function updatePermission($id, $params)
    {
        $role = SysRole::find($id);
        if (!$role) {
            return json_fail('角色不存在');
        }

        try {
            $data = [
                'role_permission' => $params['role_permission'],
            ];
            SysRole::where('role_id', $id)->update($data);
        } catch (\Exception $e) {
            return json_fail($e->getMessage());
        }

        return json_success('角色修改成功');
    }

    /**
     * @Desc 删除角色
     * @Author Gorden
     * @Date 2024/2/20 16:40
     *
     * @param $id
     * @return \support\Response
     */
    public static function delRole($params)
    {
        try {
            if (!SysRole::whereIn('role_id', $params['role_id'])->delete()) {
                throw new \Exception('角色删除失败');
            }
        } catch (\Exception $e) {
            return json_fail('角色删除失败');
        }
        return json_success('角色删除成功');
    }

    /**
     * @Desc 修改角色状态
     * @Author Gorden
     * @Date 2024/2/20 16:50
     *
     * @param $id
     * @param $roleStatus
     * @return \support\Response
     */
    public static function updateStatus($id, $roleStatus)
    {
        try {
            if (!SysRole::where('role_id', $id)->update(['role_status' => $roleStatus])) {
                throw new \Exception('角色状态修改失败');
            }
        } catch (\Exception $e) {
            return json_fail('角色状态修改失败');
        }

        return json_success('角色状态修改成功');
    }

    /**
     * @Desc 检查角色是否存在
     * @Author Gorden
     * @Date 2024/2/21 13:36
     *
     * @param $roleId
     * @return bool
     */
    public static function checkRoleExist($roleId)
    {
        return SysRole::where('role_id', $roleId)->exists();
    }
}