<?php

namespace app\admin\logic;

use app\model\CommonModel;
use app\model\RoleModel;
use think\Exception;
use think\exception\ValidateException;
use think\facade\Db;
use think\response\Json;

class RoleLogic extends BaseLogic
{
    //获取角色列表
    public static function list(array $data = []): Json
    {
        $db = RoleModel::where('is_del', CommonModel::$del_normal);
        if ($data['name'] != '') $db->whereLike('name', '%' . $data['name'] . '%');
        if ($data['level'] != '') $db->where('level', $data['level']);
        if ($data['status'] != '') $db->where('status', $data['status']);

        $count = $db->count('id');

        $list = $db
            ->field('id,name,level,status')
            ->page($data['page'], $data['size'])
            ->order(['id' => 'desc'])
            ->select()
            ->toArray();
        return json_show(CommonModel::$success, '获取角色列表成功', ['count' => $count, 'list' => $list]);
    }

    //获取全部角色
    public static function all(string $keyword = ''): Json
    {
        $db = RoleModel::where('is_del', CommonModel::$del_normal)
            ->field('id,name,level,status')
            ->order(['id' => 'desc']);
        if ($keyword != '') $db->whereLike('name', '%' . $keyword . '%');

        $list = $db
            ->select()
            ->toArray();

        return json_show(CommonModel::$success, '获取获取全部角色成功', $list);
    }

    //添加角色
    public static function add(array $data = []): Json
    {
        Db::startTrans();
        try {

            $rs = RoleModel::field('id')
                ->where(['is_del' => CommonModel::$del_normal, 'name' => $data['name']])
                ->findOrEmpty()
                ->isEmpty();
            if (!$rs) throw new Exception('该角色名已存在');

            $date = date('Y-m-d H:i:s');

            $roleid = Db::name('role')->strict(false)->insertGetId(array_merge($data, [
                'status' => CommonModel::$status_normal,
                'is_del' => CommonModel::$del_normal,
                'creater' => self::$uname,
                'createrid' => self::$uid,
                'addtime' => $date,
                'updater' => self::$uname,
                'updaterid' => self::$uid,
                'updatetime' => $date,
            ]));

            Db::name('role_action')->insert([
                'roleid' => $roleid,
                'action_data' => implode(',', $data['action_data']),
                'status' => CommonModel::$status_normal,
                'addtime' => $date,
                'updatetime' => $date,
            ]);

            Db::commit();

            return json_show(CommonModel::$success, '添加角色成功');

        } catch (Exception $exception) {
            Db::rollback();
            return json_show(CommonModel::$error_default, $exception->getMessage());
        }
    }

    //获取角色详情
    public static function read(int $id = 0): Json
    {
        $rs = RoleModel::field(true)
            ->where(['id' => $id, 'is_del' => CommonModel::$del_normal])
            ->findOrEmpty()
            ->toArray();

        if (empty($rs)) throw new ValidateException('该角色详情为空');

        //已有的权限信息
        $rs['action'] = Db::name('role_action')
            ->where(['roleid' => $id, 'is_del' => CommonModel::$del_normal, 'status' => CommonModel::$status_normal])
            ->value('action_data');
        $rs['action'] = explode(',', $rs['action']);

        return json_show(CommonModel::$success, '获取角色详情成功', $rs);

    }

    //编辑角色
    public static function edit(array $data = []): Json
    {
        Db::startTrans();
        try {

            $rs = RoleModel::field('id,name')
                ->where(['id' => $data['id'], 'is_del' => CommonModel::$del_normal])
                ->findOrEmpty();
            if ($rs->isEmpty()) throw new Exception('该角色不存在');

            if ($rs->name != $data['name']) {
                $rs = RoleModel::field('id')
                    ->where(['is_del' => CommonModel::$del_normal, 'name' => $data['name']])
                    ->findOrEmpty()
                    ->isEmpty();
                if (!$rs) throw new Exception('该角色名已存在');
            }

            $date = date('Y-m-d H:i:s');

            RoleModel::where('id', $data['id'])->strict(false)->save(array_merge($data, [
                'updater' => self::$uname,
                'updaterid' => self::$uid,
                'updatetime' => $date,
            ]));

            Db::name('role_action')
                ->where('roleid', $data['id'])
                ->save([
                    'action_data' => implode(',', $data['action_data']),
                    'updatetime' => $date,
                ]);

            Db::commit();

            return json_show(CommonModel::$success, '编辑角色成功');

        } catch (Exception $exception) {
            Db::rollback();
            return json_show(CommonModel::$error_default, $exception->getMessage());
        }
    }

    //删除角色
    public static function delete(int $id = 0): Json
    {
        Db::startTrans();
        try {


            $date = date('Y-m-d H:i:s');

            RoleModel::where(['id' => $id, 'is_del' => CommonModel::$del_normal])->save([
                'is_del' => CommonModel::$del_deleted,
                'updater' => self::$uname,
                'updaterid' => self::$uid,
                'updatetime' => $date,
            ]);

            Db::name('role_action')
                ->where(['roleid' => $id, 'is_del' => CommonModel::$del_normal])
                ->save([
                    'is_del' => CommonModel::$del_deleted,
                    'updatetime' => $date,
                ]);

            Db::commit();

            return json_show(CommonModel::$success, '删除角色成功');

        } catch (Exception $exception) {
            Db::rollback();
            return json_show(CommonModel::$error_default, $exception->getMessage());
        }
    }

    //启禁用菜单
    public static function status(array $data = []): Json
    {
        Db::startTrans();
        try {

            $rs = RoleModel::field('id,name')
                ->where(['id' => $data['id'], 'is_del' => CommonModel::$del_normal])
                ->where('status', '<>', $data['status'])
                ->findOrEmpty()
                ->isEmpty();
            if ($rs) throw new Exception('该角色不存在或重复操作');

            $date = date('Y-m-d H:i:s');

            RoleModel::where(['id' => $data['id'], 'is_del' => CommonModel::$del_normal])
                ->where('status', '<>', $data['status'])
                ->save(array_merge($data, [
                    'updater' => self::$uname,
                    'updaterid' => self::$uid,
                    'updatetime' => $date,
                ]));

            Db::name('role_action')
                ->where('roleid', $data['id'])
                ->save([
                    'status' => $data['status'],
                    'updatetime' => $date,
                ]);

            Db::commit();

            return json_show(CommonModel::$success, '操作成功');

        } catch (Exception $exception) {
            Db::rollback();
            return json_show(CommonModel::$error_default, $exception->getMessage());
        }
    }


}