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

const COMMON_STATE = {};

export default {
  state: COMMON_STATE,
  reducers: {
    clean(state, { payload }) {
      return COMMON_STATE;
    },
    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);
        });
      }
    },
    *getDetail({ payload, callback }, { call, put }) {
      const { rc, msg, data } = yield call(getDetail, {
        ...payload,
      });
      if (rc === Config.constant.codeSuccess) {
        yield put({
          type: 'updateState',
          payload: {
            ...data,
          },
        });
        if (callback) {
          callback();
        }
      } else {
        Toast.fail(msg);
      }
    },
  },
  subscriptions: {
    // setupHistory({ dispatch, history }) {
    //   history.listen(location => {});
    // },
  },
};
