const HOSPITAL_TREE_CACHE_KEY = 'hospital_tree';

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

  /**
   * 获取展示中的医院树（省→市→区→医院），带缓存
   */
  async getTree() {
    const cached = await think.cache(HOSPITAL_TREE_CACHE_KEY);
    if (cached) return cached;

    const list = await this.where({ is_show: 1, is_deleted: 0 })
      .order('sort DESC, id ASC')
      .select();

    // 组装 省→市→区→医院 树
    const provinceMap = {};
    list.forEach(h => {
      const pCode = h.province_code || '';
      const pName = h.province_name || '其他';
      const pKey = pCode || `unknown:${pName}`;
      const cCode = h.city_code || '';
      const cName = h.city_name || '其他';
      const cKey = cCode || `unknown:${cName}`;
      const dCode = h.district_code || '';
      const dName = h.district_name || '其他';
      const dKey = dCode || `unknown:${dName}`;

      if (!provinceMap[pKey]) {
        provinceMap[pKey] = { provinceCode: pCode, provinceName: pName, _cityMap: {} };
      }
      const prov = provinceMap[pKey];
      if (!prov._cityMap[cKey]) {
        prov._cityMap[cKey] = { cityCode: cCode, cityName: cName, _distMap: {} };
      }
      const city = prov._cityMap[cKey];
      if (!city._distMap[dKey]) {
        city._distMap[dKey] = { districtCode: dCode, districtName: dName, hospitals: [] };
      }
      city._distMap[dKey].hospitals.push({
        id: h.id,
        name: h.name,
        province_code: h.province_code,
        city_code: h.city_code,
        district_code: h.district_code
      });
    });

    // map 转 array
    const tree = Object.values(provinceMap).map(prov => {
      const cities = Object.values(prov._cityMap).map(city => {
        const districts = Object.values(city._distMap);
        return { cityCode: city.cityCode, cityName: city.cityName, districts };
      });
      return { provinceCode: prov.provinceCode, provinceName: prov.provinceName, cities };
    });

    await think.cache(HOSPITAL_TREE_CACHE_KEY, tree, { timeout: 24 * 60 * 60 * 1000 });
    return tree;
  }

  /**
   * 清除医院树缓存（增删改后调用）
   */
  async clearTreeCache() {
    await think.cache(HOSPITAL_TREE_CACHE_KEY, null);
  }

  /**
   * 获取展示中的医院列表（兼容旧版小程序/H5）
   */
  async getShowList(keyword = '') {
    const where = { is_show: 1, is_deleted: 0 };
    if (keyword) where.name = ['like', `%${keyword}%`];
    return this.where(where).order('sort DESC, id ASC').select();
  }
};
