const DEFAULT_SAMPLE_RECEIVER_INFO = {
  address: '武汉东湖新技术开发区花城大道8号武汉软件新城三期D2栋17层001室',
  receiver: '样本中心',
  phone: '027-6552 6665',
  contact_phone: ''
};

module.exports = class extends think.Model {
  get tableName() {
    return 'sys_config';
  }

  /**
   * 根据 key 获取配置值（自动 JSON.parse）
   */
  async getByKey(key) {
    const row = await this.where({ config_key: key }).find();
    if (think.isEmpty(row)) return null;
    try {
      return JSON.parse(row.config_value);
    } catch (e) {
      return row.config_value;
    }
  }

  /**
   * 设置配置值（自动 JSON.stringify）
   */
  async setByKey(key, value, remark) {
    const val = typeof value === 'string' ? value : JSON.stringify(value);
    const exists = await this.where({ config_key: key }).find();
    if (think.isEmpty(exists)) {
      return this.add({ config_key: key, config_value: val, remark: remark || '' });
    }
    return this.where({ config_key: key }).update({ config_value: val });
  }

  async getSampleReceiverInfo() {
    const info = await this.getByKey('sample_receiver_info');
    return {
      ...DEFAULT_SAMPLE_RECEIVER_INFO,
      ...(info && typeof info === 'object' ? info : {})
    };
  }

  async setSampleReceiverInfo(info) {
    const value = {
      address: (info.address || '').trim(),
      receiver: (info.receiver || '').trim(),
      phone: (info.phone || '').trim(),
      contact_phone: (info.contact_phone || '').trim()
    };
    return this.setByKey('sample_receiver_info', value, '送检收件信息配置');
  }
};
