import wx from 'weixin-js-sdk';
import { getConfig, getList } from '../../services/index';
import Config from '../../../../utils/config';
import { Toast } from 'antd-mobile';

export default {
  state: {
    top: 0,
    tabFlag: false,
    tabTIndex: 0,
    tabBIndex: 0,
    wxOpenFlag: false,
    tab: [
      {
        tabName: 'CKU',
        organization: 'CKU',
      },
      {
        tabName: 'CSV',
        organization: 'CSV',
      },
      {
        tabName: '品牌',
        organization: 'BRAND',
      },
    ],
    classifys: [],
    awards: [],
  },
  reducers: {
    updateState(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
  effects: {
    *getConfig({ payload, callback }, { call, put }) {
      const { rc, msg, data } = yield call(getConfig, {
        url: window.location.href.split('#')[0],
      });
      console.log('data', data);
      if (rc === 0) {
        const AppId = data.appId;
        const Timestamp = data.timestamp;
        const Signature = data.signature;
        const Noncestr = data.noncestr;
        wx.config({
          debug: false,
          appId: AppId,
          timestamp: Timestamp,
          nonceStr: Noncestr,
          signature: Signature,
          jsApiList: [
            'checkJsApi',
            'updateAppMessageShareData',
            'updateTimelineShareData',
            'previewImage',
          ],
          openTagList: ['wx-open-launch-weapp'],
        });
        wx.ready(function() {
          console.log('设置config成功');
          if (callback) {
            callback();
          }
        });
        wx.error(function(res) {
          console.log(res);
        });
      }
    },
    *getList({ payload }, { call, put, select }) {
      const { tabTIndex, tabBIndex, tab, classifys } = yield select(state => state.index);
      const organization = tab[tabTIndex].organization;
      const classifyId = classifys.length > 0 ? classifys[tabBIndex].classifyId : null;
      const { rc, msg, data } = yield call(getList, {
        organization,
        classifyId,
        ...payload,
      });
      if (rc === Config.constant.codeSuccess) {
        yield put({
          type: 'updateState',
          payload: {
            ...data,
          },
        });
      } else {
        Toast.fail(msg);
      }
    },
  },
  subscriptions: {
    // setupHistory({ dispatch, history }) {
    //   history.listen(location => {});
    // },
  },
};
