// 简易雪花算法生成器（单进程适用）
let sequence = 0;
let lastTimestamp = -1;
function snowflakeId() {
  let ts = Date.now();
  if (ts === lastTimestamp) {
    sequence = (sequence + 1) & 0xFFF;
    if (sequence === 0) {
      while (Date.now() <= ts) { /* wait */ }
      ts = Date.now();
    }
  } else {
    sequence = Math.floor(Math.random() * 16);
  }
  lastTimestamp = ts;
  // 取时间戳后8位 + 序列号3位 = 11位数字
  const tsStr = String(ts).slice(-8);
  const seqStr = String(sequence).padStart(3, '0');
  return tsStr + seqStr;
}

module.exports = class extends think.Model {
  /**
   * 生成患者编号: YYYYMM + 11位雪花ID
   */
  generatePatientNo() {
    const now = new Date();
    const ym = String(now.getFullYear()) + String(now.getMonth() + 1).padStart(2, '0');
    return ym + snowflakeId();
  }

  /**
   * 获取患者列表（分页）
   */
  async getList({ keyword, tag, status, startDate, endDate, province_code, city_code, district_code, page = 1, pageSize = 10 }) {
    const where = this._buildWhere({ keyword, tag, status, startDate, endDate, province_code, city_code, district_code });
    return this.where(where)
      .order('id DESC')
      .page(page, pageSize)
      .countSelect();
  }

  /**
   * 获取全部患者（不分页，用于导出）
   */
  async getAll({ keyword, tag, status, startDate, endDate, province_code, city_code, district_code }) {
    const where = this._buildWhere({ keyword, tag, status, startDate, endDate, province_code, city_code, district_code });
    return this.where(where).order('id DESC').select();
  }

  /**
   * 构建筛选条件
   */
  _buildWhere({ keyword, tag, status, startDate, endDate, province_code, city_code, district_code }) {
    const where = { is_deleted: 0 };

    if (keyword) {
      where._complex = {
        name: ['like', `%${keyword}%`],
        phone: ['like', `%${keyword}%`],
        patient_no: ['like', `%${keyword}%`],
        _logic: 'or'
      };
    }

    if (tag !== undefined && tag !== '') {
      if (tag === 'none') {
        where.tag = ['=', ''];
      } else {
        where.tag = tag;
      }
    }

    if (status !== undefined && status !== '') {
      where.status = parseInt(status, 10);
    }

    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`];
    }

    if (province_code) where.province_code = province_code;
    if (city_code) where.city_code = city_code;
    if (district_code) where.district_code = district_code;

    return where;
  }

  /**
   * 获取最近30天每日新增趋势（全部 + 直肠癌）
   */
  async getDailyTrend(days = 30) {
    const sql = `SELECT
      DATE(create_time) AS date,
      COUNT(*) AS total,
      SUM(tag = '直肠癌') AS rectal
      FROM patient WHERE is_deleted = 0
      AND create_time >= DATE_SUB(CURDATE(), INTERVAL ${parseInt(days, 10)} DAY)
      GROUP BY DATE(create_time) ORDER BY date ASC`;
    return this.query(sql);
  }

  /**
   * 获取最近提交记录
   */
  async getRecentList(limit = 10) {
    const list = await this.where({ is_deleted: 0 })
      .order('id DESC')
      .limit(limit)
      .select();
    // 脱敏
    list.forEach(item => {
      if (item.phone && item.phone.length === 11) {
        item.phone_mask = item.phone.slice(0, 3) + '****' + item.phone.slice(-4);
      } else {
        item.phone_mask = item.phone || '';
      }
    });
    return list;
  }

  /**
   * 获取今日各状态新增数量
   */
  async getTodayCounts() {
    const sql = `SELECT
      COUNT(*) AS \`all\`,
      SUM(status = -1) AS draft,
      SUM(status = 0) AS pending,
      SUM(status = 1) AS approved,
      SUM(status = 2) AS rejected
      FROM patient WHERE is_deleted = 0
      AND DATE(create_time) = CURDATE()`;
    const rows = await this.query(sql);
    const row = rows[0] || {};
    return {
      all: parseInt(row.all, 10) || 0,
      draft: parseInt(row.draft, 10) || 0,
      pending: parseInt(row.pending, 10) || 0,
      approved: parseInt(row.approved, 10) || 0,
      rejected: parseInt(row.rejected, 10) || 0
    };
  }

  /**
   * 获取各状态数量（支持筛选条件，排除 status）
   */
  async getStatusCounts(filters = {}) {
    // 复用 _buildWhere，但排除 status
    const { status, ...rest } = filters;
    const where = this._buildWhere(rest);
    // 删掉 status 条件（_buildWhere 不会加，但保险起见）
    delete where.status;
    const rows = await this.where(where)
      .field('COUNT(*) AS `all`, SUM(status = -1) AS draft, SUM(status = 0) AS pending, SUM(status = 1) AS approved, SUM(status = 2) AS rejected')
      .select();
    const row = rows[0] || {};
    return {
      all: parseInt(row.all, 10) || 0,
      draft: parseInt(row.draft, 10) || 0,
      pending: parseInt(row.pending, 10) || 0,
      approved: parseInt(row.approved, 10) || 0,
      rejected: parseInt(row.rejected, 10) || 0
    };
  }
};
