import { createSubscribe } from 'applet-page-component';
import { getCardListRange } from '../../utils';
Component(createSubscribe({
  onReachBottom() {
    this.fetchList({
      pageIndex: this.data.pageIndex + 1
    });
  }

})({
  props: {
    style: '',
    onService: () => [new Error('请传入接口')],
    onFetchRange: getCardListRange,
    // 搜索条件获取数据方法
    fetchTitle: '选择就诊卡',
    // 搜索条件说明
    showRange: true // 是否显示搜索

  },
  data: {
    list: [],
    range: [{
      id: '',
      name: '请选择'
    }],
    value: '',
    pageIndex: 0,
    loading: false,
    noData: false,
    parameter: {}
  },

  async didMount() {
    this.props.showRange && (await this.fetchRange());
    const {
      range
    } = this.data;
    const value = range.findIndex(item => item.isDefault);

    if (value === -1) {
      this.fetchList();
    } else {
      this.pickerChange({
        detail: {
          value
        }
      });
    }
  },

  methods: {
    async fetchRange() {
      const {
        range
      } = this.data;
      const newRange = await this.props.onFetchRange();
      await this.setData({
        range: range.concat(newRange || [])
      });
    },

    // 获取列表 after: 放到前面还是后面
    async fetchList({
      pageIndex = 1,
      pageSize = 5,
      ...other
    } = {}, after = true, clear = false) {
      if (this.data.loading) {
        return;
      }

      if (clear) {
        this.setData({
          loading: true,
          noData: false,
          list: []
        });
      } else {
        this.setData({
          loading: true,
          noData: false
        });
      }

      const {
        parameter
      } = this.data;
      const [err, result] = await this.props.onService({
        pageIndex,
        pageSize,
        ...other,
        ...parameter
      });
      this.setData({
        loading: false
      });

      if (err) {
        return;
      }

      const {
        list: newList
      } = result;
      const {
        list
      } = this.data;
      this.setData({
        pageIndex,
        noData: Number(result.pagination.total) === 0 && list.length === 0
      });
      this.$spliceData({
        list: [after ? list.length : 0, 0, ...newList]
      });
    },

    async pickerChange({
      detail: {
        value
      }
    }) {
      const {
        range
      } = this.data;
      await this.setData({
        value,
        list: [],
        parameter: {
          cardNum: range[value] && range[value].id
        }
      });
      this.fetchList({
        pageIndex: 1
      });
    }

  }
}));