const Base = require('../../base');

module.exports = class extends Base {
  // 角色列表页面
  async indexAction() {
    this.assign('currentPage', 'sys-role');
    this.assign('pageTitle', '角色权限');
    this.assign('breadcrumb', [
      { name: '系统管理', url: '/admin/system/user.html' },
      { name: '角色权限' }
    ]);

    // 权限树数据
    this.assign('permissionTree', await this.getPermissionTree());

    this.assign('adminUser', this.adminUser || {});

    return this.display();
  }

  // 获取角色列表接口
  async listAction() {
    const { keyword, page = 1, pageSize = 20 } = this.get();

    const where = { is_deleted: 0 };

    if (keyword) {
      where.name = ['like', `%${keyword}%`];
    }

    const list = await this.model('admin_role')
      .where(where)
      .order('sort ASC, id ASC')
      .page(page, pageSize)
      .countSelect();

    return this.success(list);
  }

  // 获取所有角色（下拉用）
  async allAction() {
    const list = await this.model('admin_role')
      .where({ is_deleted: 0, status: 1 })
      .order('sort ASC')
      .select();

    return this.success(list);
  }

  // 获取单个角色
  async detailAction() {
    const { id } = this.get();
    if (!id) return this.fail('参数错误');

    const role = await this.model('admin_role')
      .where({ id, is_deleted: 0 })
      .find();

    if (think.isEmpty(role)) {
      return this.fail('角色不存在');
    }

    // 解析 permissions JSON 字符串为数组
    try {
      role.permissions = JSON.parse(role.permissions || '[]');
    } catch (e) {
      role.permissions = [];
    }

    return this.success(role);
  }

  // 新增角色
  async addAction() {
    const { name, code, description, is_default = 0, sort = 0 } = this.post();

    if (!name) {
      return this.fail('角色名称不能为空');
    }

    // 检查名称是否存在
    const exist = await this.model('admin_role')
      .where({ name, is_deleted: 0 })
      .find();

    if (!think.isEmpty(exist)) {
      return this.fail('角色名称已存在');
    }

    const data = {
      name,
      code: code || '',
      description: description || '',
      permissions: JSON.stringify([]),
      is_default: is_default ? 1 : 0,
      sort: sort || 0,
      create_by: this.adminUser?.id || 0
    };

    const id = await this.model('admin_role').add(data);
    await this.log('add', '角色管理', `新增角色「${name}」`);
    return this.success({ id });
  }

  // 编辑角色
  async editAction() {
    const { id, name, code, description, is_default, sort } = this.post();

    if (!id) return this.fail('参数错误');

    const role = await this.model('admin_role')
      .where({ id, is_deleted: 0 })
      .find();

    if (think.isEmpty(role)) {
      return this.fail('角色不存在');
    }

    // 默认角色不能编辑
    if (role.is_default === 1) {
      return this.fail('默认角色不能编辑');
    }

    // 检查名称是否重复
    if (name && name !== role.name) {
      const exist = await this.model('admin_role')
        .where({ name, is_deleted: 0, id: ['!=', id] })
        .find();

      if (!think.isEmpty(exist)) {
        return this.fail('角色名称已存在');
      }
    }

    const data = {
      name: name || role.name,
      code: code !== undefined ? code : role.code,
      description: description !== undefined ? description : role.description,
      is_default: is_default !== undefined ? (is_default ? 1 : 0) : role.is_default,
      sort: sort !== undefined ? sort : role.sort,
      update_by: this.adminUser?.id || 0
    };

    await this.model('admin_role').where({ id }).update(data);
    await this.log('edit', '角色管理', `编辑角色「${name || role.name}」(ID:${id})`);
    return this.success();
  }

  // 分配权限
  async assignPermissionsAction() {
    const { id, permissions } = this.post();

    if (!id) return this.fail('参数错误');

    const role = await this.model('admin_role')
      .where({ id, is_deleted: 0 })
      .find();

    if (think.isEmpty(role)) {
      return this.fail('角色不存在');
    }

    await this.model('admin_role')
      .where({ id })
      .update({
        permissions: JSON.stringify(permissions || []),
        update_by: this.adminUser?.id || 0
      });

    await this.log('edit', '角色管理', `分配权限「${role.name}」(ID:${id})`);
    return this.success();
  }

  // 删除角色
  async deleteAction() {
    const { id } = this.post();

    if (!id) return this.fail('参数错误');

    const role = await this.model('admin_role')
      .where({ id, is_deleted: 0 })
      .find();

    if (think.isEmpty(role)) {
      return this.fail('角色不存在');
    }

    // 默认角色不能删除
    if (role.is_default === 1) {
      return this.fail('默认角色不能删除');
    }

    // 检查是否有用户使用该角色
    const userCount = await this.model('admin_user')
      .where({ role_id: id, is_deleted: 0 })
      .count();

    if (userCount > 0) {
      return this.fail(`该角色下有 ${userCount} 个用户，无法删除`);
    }

    await this.model('admin_role')
      .where({ id })
      .update({
        is_deleted: 1,
        update_by: this.adminUser?.id || 0
      });

    await this.log('delete', '角色管理', `删除角色「${role.name}」(ID:${id})`);
    return this.success();
  }

  // 批量删除
  async batchDeleteAction() {
    const { ids } = this.post();

    if (!ids || !ids.length) return this.fail('参数错误');

    // 检查是否包含默认角色
    const defaultCount = await this.model('admin_role')
      .where({ id: ['in', ids], is_default: 1, is_deleted: 0 })
      .count();

    if (defaultCount > 0) {
      return this.fail('选中的角色包含默认角色，无法删除');
    }

    // 检查是否有用户使用这些角色
    const userCount = await this.model('admin_user')
      .where({ role_id: ['in', ids], is_deleted: 0 })
      .count();

    if (userCount > 0) {
      return this.fail(`选中的角色下有 ${userCount} 个用户，无法删除`);
    }

    await this.model('admin_role')
      .where({ id: ['in', ids] })
      .update({
        is_deleted: 1,
        update_by: this.adminUser?.id || 0
      });

    await this.log('delete', '角色管理', `批量删除角色(IDs:${ids.join(',')})`);
    return this.success();
  }

  // 获取权限树配置
  async getPermissionTree() {
    return [
      {
        name: '患者管理', key: 'patient',
        children: [
          { name: '查看', key: 'patient:view' },
          { name: '新增', key: 'patient:add' },
          { name: '编辑', key: 'patient:edit' },
          { name: '导出', key: 'patient:export' },
          { name: '审核', key: 'patient:audit' },
          { name: '删除', key: 'patient:delete' }
        ]
      },
      {
        name: '瘤种管理', key: 'tag',
        children: [
          { name: '查看', key: 'tag:view' },
          { name: '新增', key: 'tag:add' },
          { name: '编辑', key: 'tag:edit' },
          { name: '删除', key: 'tag:delete' }
        ]
      },
      {
        name: '内容管理', key: 'content',
        children: [
          { name: '查看', key: 'content:view' },
          { name: '新增', key: 'content:add' },
          { name: '编辑', key: 'content:edit' },
          { name: '删除', key: 'content:delete' }
        ]
      },
      {
        name: '系统管理', key: 'setting:system',
        children: [
          { name: '用户管理', key: 'setting:system:user' },
          { name: '角色权限', key: 'setting:system:role' },
          { name: '操作日志', key: 'setting:system:log' },
          { name: '短信记录', key: 'setting:system:sms' }
        ]
      }
    ];
  }
};
