/* eslint-disable no-unused-vars */
import Store from 'herculex';
import { getComponentDetail, getServiceDynamicList } from '../../utils/request';

const app = getApp();
export default new Store({
  connectGlobal: true,
  state: {
    imgSrcPrefix: app.globalData.imgSrcPrefix,
    componentUUID: '',
    templateUUID: '',
    componentType: '',
    serviceList: [],
    errorType: '',
    errorMsg: '',
    pageNo: 1,
    pageSize: 10,
    needLoad: true, // 是否还有数据
    whetherSetDynamicDatasource: 'N',
  },
  actions: {
    // eslint-disable-next-line no-unused-vars
    async getServiceData({ state, commit }, payload) {
      const { componentUUID, templateUUID, componentType, whetherSetDynamicDatasource } = state;
      try {
        let [err, response] = [];
        if (whetherSetDynamicDatasource === 'Y') {
          [err, response] = await getServiceDynamicList({
            componentUuid: componentUUID,
          });
        } else {
          [err, response] = await getComponentDetail({
            componentUUID,
            componentType,
            templateUUID,
            pageSize: state.pageSize,
            current: state.pageNo,
          });
        }
        if (err) throw err;
        const list = response.serviceList || response.list;
        if (!response || !list) {
          // 如果没有数据 分页时候needLoad为false 首次就报错
          // eslint-disable-next-line no-throw-literal
          if (componentType !== 'pullUpLoad') throw {};
          return commit({
            needLoad: false,
          });
        }
        const { serviceList = [], pageNo, pageSize } = state;
        commit({
          serviceList: serviceList.concat(list),
          pageNo: pageNo + 1,
          needLoad: list.length >= pageSize,
        });
      } catch (error) {
        // 上拉加载时报错 不做报错处理
        if (componentType === 'pullUpLoad') return;
        commit({
          errorType: 'SYSTEM_ERROR',
          errMsg: error && error.msg,
        });
      }
    },
    async pullUpLoad({ dispatch, state }) {
      if (state.needLoad) {
        dispatch('getServiceData', 'pullUpLoad');
      }
    },
  },
});
