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

module.exports = class extends Base {
  async indexAction() {
    this.assign('currentPage', 'sample-type');
    this.assign('pageTitle', '送检样本管理');
    this.assign('breadcrumb', [
      { name: '系统管理', url: '/admin/system/user.html' },
      { name: '送检样本管理' }
    ]);
    // 获取当前必选配置
    const required = await this.model('sys_config').getByKey('sample_required');
    this.assign('sampleRequired', required === '1' || required === 1 ? '1' : '0');
    return this.display();
  }

  async listAction() {
    const list = await this.model('sample_type')
      .where({ is_deleted: 0 })
      .order('sort DESC, id ASC')
      .select();
    return this.json({ code: 0, data: list });
  }

  async addAction() {
    const { name, need_return, sort } = this.post();
    if (!name) return this.fail('请输入样本类型名称');
    await this.model('sample_type').add({
      name,
      need_return: need_return ? 1 : 0,
      sort: sort || 0,
      status: 1
    });
    await this.log('add', '送检样本管理', `新增样本类型: ${name}`);
    return this.success();
  }

  async editAction() {
    const { id, name, need_return, sort, status } = this.post();
    if (!id) return this.fail('参数错误');
    if (!name) return this.fail('请输入样本类型名称');
    await this.model('sample_type').where({ id }).update({
      name,
      need_return: need_return ? 1 : 0,
      sort: sort || 0,
      status: status !== undefined ? parseInt(status) : 1
    });
    await this.log('edit', '送检样本管理', `编辑样本类型(ID:${id}): ${name}`);
    return this.success();
  }

  async deleteAction() {
    const { id } = this.post();
    if (!id) return this.fail('参数错误');
    await this.model('sample_type').where({ id }).update({ is_deleted: 1 });
    await this.log('edit', '送检样本管理', `删除样本类型(ID:${id})`);
    return this.success();
  }

  async sortAction() {
    const { ids } = this.post();
    if (!ids || !ids.length) return this.fail('参数错误');
    for (let i = 0; i < ids.length; i++) {
      await this.model('sample_type').where({ id: ids[i] }).update({ sort: ids.length - i });
    }
    return this.success();
  }

  async setRequiredAction() {
    const { value } = this.post();
    await this.model('sys_config').setByKey('sample_required', value ? '1' : '0', '送检样本是否必选');
    await this.log('edit', '送检样本管理', `设置送检样本必选: ${value ? '是' : '否'}`);
    return this.success();
  }
};
