import { createSubscribe } from 'applet-page-component';
import history from '../../utils/history';
import { getDoctorList } from './service';
Component(createSubscribe({
  /* 分页逻辑 */
  async onReachBottom() {
    const {
      loading,
      isLastPage
    } = this.data;
    if (loading || isLastPage) return;
    this.pageIndex = this.pageIndex + 1;
    await this.updateData({
      loading: true
    });
    await this.onSplitPage();
  }

})({
  props: {
    componentData: {}
  },
  data: {
    loading: true,

    /* 是否为最后一页 */
    isLastPage: false,
    dataSource: []
  },

  async didMount() {
    await this.onRefresh();
  },

  methods: {
    updateData(data) {
      return new Promise(resolve => this.setData(data, resolve));
    },

    /* 分页显示医生列表 */
    async onSplitPage() {
      let total = 0;
      let dataList = [];
      let success = true;
      const {
        isLastPage
      } = this.data;
      const params = {
        pageSize: 10,
        pageIndex: this.pageIndex
      };

      if (!isLastPage) {
        try {
          const {
            list = [],
            pagination = {}
          } = await getDoctorList(params);
          dataList = list;
          total = pagination.total || 0;
        } catch (e) {
          success = false;
        }
      }

      let state = {
        loading: false
      };

      if (success) {
        const {
          dataSource
        } = this.data;
        const _list = [...dataSource, ...dataList];
        state = { ...state,
          dataSource: _list,
          isLastPage: _list.length >= total
        };
      }

      await this.updateData(state);
    },

    /* 刷新数据 */
    async onRefresh() {
      /* 初始化数据 */
      this.pageIndex = 1;
      await this.updateData({
        loading: true,
        isLastPage: false,
        dataSource: []
      });
      await this.onSplitPage();
    },

    toDetailPage({
      target
    }) {
      const {
        item
      } = target.dataset;
      const {
        doctorId
      } = item;
      history.push({
        query: {
          doctorId
        },
        title: '医生简介',
        pageType: 'doctor-profile-item'
      });
    }

  }
}));