import PageContainerBehavior from "../../../../core/behavior/page-container.behavior";
import I18nBehavior from "../../../../i18n/behavior";
import tickleBehavior, { getTickleContext } from "../../../../core/behavior/tickle.behavior";
import { getScienceListMethod } from "../../request";
// module/diet/pages/science-list/science-list.ts
Component({
  behaviors: [
    I18nBehavior,
    PageContainerBehavior,
    tickleBehavior,
  ],
  lifetimes: {
    attached() {
      wx.showLoading({ title: '加载中' });
      this.load();
    }
  },
  properties: {
    classify: { type: String, value: '' },
  },
  data: {
    i18n: {
      healthTeach: { title: '分享文章' },
    },
    keyword: '',
    searchInputProps: {
      placeholderStyle: 'color: #929292;',
      // cursorColor: '#1D6FF6',
      // iconColor: '#1D6FF6',
      cursorColor: '#929292',
      iconColor: '#929292',
      focus: false,
      placeholder: '搜索名称',
    },
    title: '',
    dataset: [] as AnyObject[],
    page: 1, size: 20, total: 0, loading: false, isLastPage: false,
  },
  observers: {
    'classify'(value) {
      const ref = { tonic: '药膳查询', tea: '中医茶饮' } as any;
      this.setData({ title: ref[value] || '' })
    },
    'page,size,total'(page, size, total) {
      this.setData({ isLastPage: page * size >= total })
    }
  },
  methods: {
    async load() {
      try {
        const { data, total } = await getScienceListMethod(1, this.data.size, {
          keyword: this.data.keyword,
        });
        this.setData({ dataset: data, total });
      } catch (error) {
        getTickleContext.call(this).showWarnMessage(error.errMsg);
      }
      wx.hideLoading();
    },
    async loadMore() {
      if (this.data.isLastPage || this.data.loading) return;
      this.setData({ loading: true });
      try {
        const _page = this.data.page + 1;
        const { data, total } = await getScienceListMethod(_page, this.data.size, {
          keyword: this.data.keyword,
        });
        this.setData({ dataset: [...this.data.dataset, ...data], total, page: _page });
      } catch (error) {
        getTickleContext.call(this).showWarnMessage(error.errMsg);
      }
      this.setData({ loading: false });
    },
    onConfirmSearchInput(event: WechatMiniprogram.InputConfirm) {
      const _keyword = this.data.keyword;
      this.setData({ keyword: event.detail.value });
      wx.showLoading({ title: '搜索中' });
      this.load().catch(() => { this.setData({ keyword: _keyword }) });
    },
    toInfoPage(event: WechatMiniprogram.TouchEvent) {
      const id = event.currentTarget.id;
      wx.navigateTo({ url: `/module/article/pages/science-info/science-info?id=${id}` })
        .then(res => {
          res.eventChannel.emit('load', this.data.dataset.find(item => item.id.toString() === id))
        })
    }
  }
})