import { createSubscribe } from 'applet-page-component';
import * as utils from './../../utils';
import { getDepDoctorList, getDepOrderSourceRemain } from './service';
/* 判断日期是不是今天 */

const isToday = date => {
  const _date = new Date();

  const year = _date.getFullYear();

  const month = _date.getMonth() + 1;

  const day = _date.getDate();

  const check = val => `${val}`.length <= 1 ? `0${val}` : val;

  return date === [year, check(month), check(day)].join('/');
};

const copy = obj => JSON.parse(JSON.stringify(obj));

const defaultSource = {
  normal: {
    items: [],
    type: 'normal',
    name: '普通号'
  },
  expert: {
    items: [],
    name: '专家号',
    type: 'expert'
  }
};
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: {
    date: '',
    loading: true,
    dateList: [],

    /* 原始的列表 */
    nativeList: [],

    /* 是否为最后一页 */
    isLastPage: false,
    dataSource: copy(defaultSource),
    headerHeight: utils.getHeaderHeight()
  },

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

  methods: {
    getQuery() {
      const {
        $routeConfig
      } = this.$page;
      return $routeConfig.query;
    },

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

    async onChange(date) {
      await this.onRefresh(date);
    },

    /* 获取日期列表 */
    async fetchDateRemainList() {
      /* 获取日期列表 */
      const {
        departmentId
      } = this.getQuery();
      const list = await getDepOrderSourceRemain({
        depId: departmentId
      });
      /* 处理数据 */

      const dateList = list.map(item => {
        const {
          date
        } = item;

        const _date = date.replace(/-/g, '/');

        const today = isToday(_date);
        const day = new Date(_date).getDate();
        const week = utils.getWeek(_date);
        return { ...item,
          date: _date,
          showDay: day,
          today,
          week
        };
      });
      await this.updateData({
        dateList
      });
    },

    /* 数据处理 */
    formatData(list = []) {
      const {
        dataSource
      } = this.data;
      list.forEach(item => {
        const {
          items
        } = dataSource[item.type];
        if (items) items.push(item);
      });
      return { ...dataSource
      };
    },

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

      if (curDate) {
        const reg = new RegExp('/', 'gm');
        curDate = curDate.replace(reg, '-');
      }

      const {
        departmentId
      } = this.getQuery();
      const params = {
        date: curDate,
        pageSize: 10,
        depId: departmentId,
        pageIndex: this.pageIndex
      };

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

      let state = {
        loading: false
      };

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

      await this.updateData(state);
    },

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

  }
}));