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

module.exports = class extends Base {
  async indexAction() {
    this.assign('currentPage', 'sys-sms');
    this.assign('pageTitle', '短信记录');
    this.assign('breadcrumb', [
      { name: '系统管理', url: '/admin/system/user.html' },
      { name: '短信记录' }
    ]);
    return this.display();
  }

  async listAction() {
    const keyword = this.get('keyword') || '';
    const status = this.get('status');
    const bizType = this.get('bizType') || '';
    const startDate = this.get('startDate') || '';
    const endDate = this.get('endDate') || '';
    const page = this.get('page') || 1;
    const pageSize = this.get('pageSize') || 20;

    const model = this.model('sms_log');
    const where = {};

    if (keyword) {
      where.mobile = ['like', `%${keyword}%`];
    }
    if (status !== '' && status !== undefined) {
      where.status = parseInt(status);
    }
    if (bizType) {
      where.biz_type = bizType;
    }
    if (startDate && endDate) {
      where.create_time = ['between', [startDate + ' 00:00:00', endDate + ' 23:59:59']];
    } else if (startDate) {
      where.create_time = ['>=', startDate + ' 00:00:00'];
    } else if (endDate) {
      where.create_time = ['<=', endDate + ' 23:59:59'];
    }

    const list = await model.where(where)
      .order('id DESC')
      .page(page, pageSize)
      .countSelect();

    return this.json({ code: 0, data: list });
  }

  // 清除短信发送限制（手机号或IP）
  async clearLimitAction() {
    const { type, value } = this.post();
    if (!type || !value) return this.fail('参数错误');

    const dayjs = require('dayjs');
    const today = dayjs().format('YYYY-MM-DD');
    let cleared = [];

    if (type === 'phone') {
      // 清除手机号相关的所有限制
      const bizTypes = ['real_name_auth', 'change_phone', 'login'];
      for (const biz of bizTypes) {
        await think.cache(`sms:rate_limit:${value}:${biz}`, null);
        await think.cache(`sms:daily:${value}:${today}`, null);
        await think.cache(`sms:code:${value}:${biz}`, null);
      }
      cleared = ['频率限制', '每日上限', '验证码缓存'];
    } else if (type === 'ip') {
      await think.cache(`sms:ip_hour:${value}`, null);
      await think.cache(`sms:ip_day:${value}:${today}`, null);
      cleared = ['IP小时限制', 'IP每日限制'];
    } else {
      return this.fail('类型错误');
    }

    await this.log('edit', '系统管理', `清除短信限制: ${type === 'phone' ? '手机号' : 'IP'} ${value} (${cleared.join('、')})`);
    return this.success();
  }
};
