import Ajax from '../../util/ajax'
import api from '../../util/api'
import wxsdk from '@/util/share'

export default {
  namespaced: true,
  state: {
    userInfo: null,
    appid: null,
    shareNum: 0
  },
  mutations: {
    updateAppId (state, data) {
      state.appid = data.message.appid
    },
    updateUserInfo (state, data) {
      state.userInfo = data || {}
    },
    updateShareNum (state, data) {
      state.shareNum = data || 0
    }
  },
  actions: {
    getAppId (context) {
      return new Promise((resolve, reject) => {
        Ajax({
          ...api.getAppId
        }).then(res => {
          context.commit('updateAppId', res)
          resolve(res)
        }).catch((res) => {
          reject(res)
        })
      })
    },
    getUser (context, payload) {
      return new Promise((resolve, reject) => {
        wxsdk({ url: encodeURIComponent(window.location.href.split('#')[0]), code: payload.code }, {
          title: '2019，这些我都想要！ ',
          desc: '立下Flag，打开你的新年心愿清单',
          link: `${window.location.origin}${window.location.pathname}#/home`,
          thu_image: `https://jingcheng-h5temp.oss-cn-shanghai.aliyuncs.com/20181229-images/share_20181229165703.jpg?x-oss-process=style/wxicon`
        }).then((res) => {
          context.commit('updateUserInfo', res)
          resolve(res)
        }).catch((err) => {
          reject(err)
        })
      })
    },
    getShare (context) {
      return new Promise((resolve, reject) => {
        Ajax({
          ...api.getShare
        }).then(res => {
          context.commit('updateShareNum', res)
          resolve(res)
        }).catch((res) => {
          reject(res)
        })
      })
    },
    putShare (context) {
      console.log(context)
      return new Promise((resolve, reject) => {
        Ajax({
          ...api.putShare
        }).then(res => {
          resolve(res)
        }).catch((res) => {
          reject(res)
        })
      })
    }
  }
}
