import {appConfig} from '../config'

const openid_info_key = appConfig.openidInfoKey
const user_info_key = 'user_info_yunyubang'

export const weixin = {
  getOpenidInfo: (cb, refresh) => {
    cb = cb || function () {}
    refresh = refresh || false
	if (!refresh) {
		let user_info = uni.getStorageSync(user_info_key)
		if (user_info && user_info.openid && user_info.session_key) {
		  cb(user_info)
		  return
		}
	}

    uni.login({
      provider: 'weixin',
      success: (res) => {
        uni.request({
          url: appConfig.baseUrl + '/api/member/login-by-code',
          method: 'POST',
          data: {code: res.code},
          success: result => {
			const user_info1 = result.data.data.user_info
			user_info1.openid = user_info1.wechat_openid
            uni.setStorageSync(user_info_key, user_info1)
            cb(user_info1)
          }
        });
       }
    });
  },
  getUserProfile: (cb) => {
    cb = cb || function () {}

    wx.getUserProfile({
      desc: '用于完善会员资料',
      success: (res) => {
        uni.setStorageSync(user_info_key, res.userInfo)
        cb(res.userInfo)
      }
    })
  },
  getUserInfoCache: () => {
	  return uni.getStorageSync(user_info_key)
  }
}

export function login() {
	// uni.login({
	//   provider: 'weixin',
	//   success: res => {
	//     uni.request({
	//       url: appConfig.baseUrl + '/api/wechat/user-login',
	//       method: 'POST',
	//       data: {
	// 		  code: res.code,
	// 		  iv: '',
	// 	  },
	//       success: result => {
	//       }
	//     })
	//    }
	// });
}