import { wikiDrugs, categories } from '../../../utils/drug-data';
import type { WikiDrug } from '../../../utils/drug-data';
import { getDrugImage } from '../../../utils/drug-images';

interface DrugItem extends WikiDrug {
  image: string;
}

Page({
  data: {
    categories,
    activeCategory: '全部',
    searchText: '',
    drugList: [] as DrugItem[],
    allDrugs: [] as DrugItem[],
    topSearches: ['阿莫西林', '布洛芬', '头孢', '二甲双胍', '奥美拉唑', '氯雷他定'],
  },
  onLoad() {
    const list: DrugItem[] = Object.values(wikiDrugs)
      .filter((d) => d.id < 100)
      .map((d) => ({ ...d, image: getDrugImage(d.category) }));
    this.setData({ allDrugs: list, drugList: list });
  },
  onShow() {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({ selected: 1 });
    }
  },
  onSearchInput(e: WechatMiniprogram.Input) {
    const searchText = e.detail.value.trim();
    this.setData({ searchText });
    this.filterDrugs();
  },
  onClearSearch() {
    this.setData({ searchText: '' });
    this.filterDrugs();
  },
  onCategoryTap(e: WechatMiniprogram.TouchEvent) {
    const { cat } = e.currentTarget.dataset;
    this.setData({ activeCategory: cat });
    this.filterDrugs();
  },
  onTopSearchTap(e: WechatMiniprogram.TouchEvent) {
    const { kw } = e.currentTarget.dataset;
    this.setData({ searchText: kw });
    this.filterDrugs();
  },
  filterDrugs() {
    const { searchText, activeCategory, allDrugs } = this.data;
    let list = allDrugs;
    if (activeCategory !== '全部') {
      list = list.filter((d) => d.category === activeCategory);
    }
    if (searchText) {
      const kw = searchText.toLowerCase();
      list = list.filter(
        (d) =>
          d.name.includes(kw) ||
          d.genericName.toLowerCase().includes(kw) ||
          d.category.includes(kw) ||
          d.tag.includes(kw),
      );
    }
    this.setData({ drugList: list });
  },
  goDetail(e: WechatMiniprogram.TouchEvent) {
    const { id } = e.currentTarget.dataset;
    wx.navigateTo({ url: `/pages/drug-guide/index?id=${id}` });
  },
});
