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

const CONFIG_KEY = 'tag_options';

module.exports = class extends Base {
  // 瘤种管理页面
  async indexAction() {
    this.assign('currentPage', 'tag');
    this.assign('pageTitle', '瘤种管理');
    this.assign('breadcrumb', [{ name: '瘤种管理' }]);
    this.assign('adminUser', this.adminUser || {});
    this.assign('canAdd', this.isSuperAdmin || (this.userPermissions || []).includes('tag:add'));
    this.assign('canEdit', this.isSuperAdmin || (this.userPermissions || []).includes('tag:edit'));
    this.assign('canDelete', this.isSuperAdmin || (this.userPermissions || []).includes('tag:delete'));
    return this.display();
  }

  // 获取瘤种列表
  async listAction() {
    const tags = await this.model('sys_config').getByKey(CONFIG_KEY) || [];
    return this.success(tags);
  }

  // 新增瘤种
  async addAction() {
    const { name } = this.post();
    if (!name || !name.trim()) return this.fail('瘤种名称不能为空');

    const tags = await this.model('sys_config').getByKey(CONFIG_KEY) || [];
    if (tags.includes(name.trim())) return this.fail('该瘤种已存在');

    tags.push(name.trim());
    await this.model('sys_config').setByKey(CONFIG_KEY, tags, '瘤种选项');

    await this.log('add', '瘤种管理', `新增瘤种「${name.trim()}」`);
    return this.success();
  }

  // 编辑瘤种
  async editAction() {
    const { oldName, newName } = this.post();
    if (!oldName || !newName || !newName.trim()) return this.fail('参数错误');

    const tags = await this.model('sys_config').getByKey(CONFIG_KEY) || [];
    const idx = tags.indexOf(oldName);
    if (idx === -1) return this.fail('原瘤种不存在');
    if (oldName !== newName.trim() && tags.includes(newName.trim())) return this.fail('该瘤种已存在');

    tags[idx] = newName.trim();
    await this.model('sys_config').setByKey(CONFIG_KEY, tags, '瘤种选项');

    // 同步更新患者表中的瘤种名称
    if (oldName !== newName.trim()) {
      await this.model('patient').where({ tag: oldName }).update({ tag: newName.trim() });
    }

    await this.log('edit', '瘤种管理', `编辑瘤种「${oldName}」→「${newName.trim()}」`);
    return this.success();
  }

  // 删除瘤种
  async deleteAction() {
    const { name } = this.post();
    if (!name) return this.fail('参数错误');

    const tags = await this.model('sys_config').getByKey(CONFIG_KEY) || [];
    const idx = tags.indexOf(name);
    if (idx === -1) return this.fail('瘤种不存在');

    tags.splice(idx, 1);
    await this.model('sys_config').setByKey(CONFIG_KEY, tags, '瘤种选项');

    await this.log('delete', '瘤种管理', `删除瘤种「${name}」`);
    return this.success();
  }

  // 排序瘤种
  async sortAction() {
    const { tags } = this.post();
    if (!Array.isArray(tags)) return this.fail('参数错误');

    await this.model('sys_config').setByKey(CONFIG_KEY, tags, '瘤种选项');
    await this.log('edit', '瘤种管理', '调整瘤种排序');
    return this.success();
  }
};
