import Store from '@/store';
import { $EventBus } from '@/utils/EventBus';
import loadingIcon from 'uview-ui/libs/config/props/loadingIcon';
import { data } from 'uview-ui/libs/mixin/mixin';
import context from '../../main.js'
export default {
  getLocation(callback) {
    let _this = this;
    return uni.getLocation({
      type: 'gcj02', //返回可以用于uni.openLocation的经纬度
      success: function (res) {
        var params = {
			lat: res.latitude,
			lng: res.longitude,
        };
		if(params.lat && params.lng) {
			Store.commit('saveLocation', params);
			uni.setStorage({ key: 'location', data: params });
		} else {
			params = uni.getStorageSync('location');
		}
        callback && callback(1, params);
      },
      fail: function (res) {
        console.log(res)
		const params = uni.getStorageSync('location');
        callback && callback(0, params);
      },
    });
  },
  // 获取店铺信息
  getShopInfo(params) {
	return uni.$u.http.get('/weixin/getShop', { params })
	.then((res) => {
		// console.log("get shop:"+JSON.stringify(res.data.data));
		if (res.data.code == 200) {
			Store.commit('saveShopInfo', res.data.data);
			uni.setStorage({ key: 'shopData', data: res.data.data });
			if (res.data.data) {
				$EventBus.$emit('getMenuList', res.data.data);
			}
		}
		return res;
	}).catch((err) => {
		console.log("get shop error");
		return err;
	});
  },
  uniLogin(res, callback) {
    uni.login({
      provider: 'weixin',
      success: function (data) {
        //   传给后台接口所需登录数据
        uni.$u.http
          .post('/weixin/login', {
            code: data.code,
            source: 3,
            iv: res.iv,
            encryptedData: res.encryptedData,
          })
          .then((res) => {
            const { statusCode, data } = res;
            const { code, token, phoneNumber } = data;
            if (statusCode == 200 && data && code == 200) {
              uni.setStorage({ key: 'Authorization', data: token });
              uni.setStorage({ key: 'phoneNumber', data: phoneNumber });
              uni.setStorage({ key: 'userInfo', data: data });
              Store.commit('setUserInfo', data);
              Store.commit('setAuthorization', token);
			  if(callback)
				callback();
            }
          })
          .catch((err) => {
            context.showToast({
              title: err.msg,
            });
          });
      },
    });
  },
  getOpenId(res) {
	  return uni.$u.http.post('/weixin/login', {code:res })
  },
  getAuthorization(phoneNumber) {
    uni.$u.http.post('/weixin/refreshToken ', { phoneNumber }).then((res) => {
      const { data } = res;
      uni.setStorage({ key: 'Authorization', data: data.token });
      Store.commit('setAuthorization', data.token);
      context.showToast({ title: '登录成功！' });
    });
  },
  wxLoginAndGetOpenid(loding, updata) {
  	return new Promise((resolve, reject) => {
  		uni.login({
  			 provider: 'weixin',
  			 success: (res) => {
  				const code = res.code
  				if(code){
					this.getOpenId(code).then((res)=>{
						const loginInfo = res.data.msg
						resolve(loginInfo)
					})
				}
  			 }
  		})
  	})
  },
  loginDecrypt(res){
	  return uni.$u.http.post('/weixin/decrypt ', {
		  session_key:res.loginInfo.session_key,
		  openId:res.loginInfo.openid,
		  encryptedData:res.data,
		  iv:res.iv,
		  source:3
		})
  },
  // 手机号授权登录
  getPhoneNumber(res, callback) {
    uni.setStorage({ key: 'userPhoneInfo', data: res });
    Store.commit('setUserPhoneInfo', res);
    uni.setStorage({ key: 'phoneInfo', data: res });
	  const loginInfo = res.loginInfo
	  const iv = res.detail.iv
	  const data = res.detail.encryptedData
	  wx.checkSession({
	  	success: (res) => {
	  		console.log('seeion未过期')
	  		this.onLogin(loginInfo,iv,data,callback)
	  	},
	  	fail: (res) => {
	  		console.log('seeion已过期')
	  		this.wxLoginAndGetOpenid(true).then(loginInfo => {
	  			this.onLogin(loginInfo,iv,data,callback)
	  		})
	  	}
	  })
  },
  onLogin(loginInfo,iv,data,callback) {
	this.loginDecrypt({loginInfo:JSON.parse(loginInfo),iv,data}).then(res => {
	const { statusCode, data } = res;
            const { code, token, phoneNumber } = data;
            if (statusCode == 200 && data && code == 200) {
              uni.setStorage({ key: 'Authorization', data: token });
              uni.setStorage({ key: 'phoneNumber', data: phoneNumber });
              uni.setStorage({ key: 'userInfo', data: data });
              Store.commit('setUserInfo', data);
              Store.commit('setAuthorization', token);
		          if(callback)
		            return	callback();
              }
	}).catch((err) => {
            context.showToast({
              title: err.msg,
            });
    });
  },
  setAllow(allow) {
    uni.$u.http
      .get('/system/customer/allow', {
        params: {
          allow,
        },
      })
      .then((res) => {
        return res;
      })
      .catch((err) => {
        context.showToast({ title: '服务器错误', icon: 'none' });
      });
  },
};
