import PageContainerBehavior from "../../../../core/behavior/page-container.behavior";
import tickleBehavior, { getTickleContext } from "../../../../core/behavior/tickle.behavior";
import { getDietListMethod } from "../../request";
// module/diet/pages/diet-list/diet-list.ts
Component({
  behaviors: [
    PageContainerBehavior,
    tickleBehavior,
  ],
  lifetimes: {
    attached() {
      wx.showLoading({ title: '加载中' });
      this.load();
    }
  },
  properties: {
    classify: { type: String, value: '' },
  },
  data: {
    keyword: '',
    searchInputProps: {
      placeholderStyle: 'color: #929292;',
      cursorColor: '#34A76B',
      iconColor: '#34A76B',
      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 getDietListMethod(1, this.data.size, {
          keyword: this.data.keyword,
          classify: <any>this.data.classify,
        });
        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 getDietListMethod(_page, this.data.size, {
          keyword: this.data.keyword,
          classify: <any>this.data.classify,
        });
        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 }) });
    }
  }
})