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) => {
            console.log(res,'resssssssss')
            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
            uni.setStorageSync('loginInfo',loginInfo)
						resolve(loginInfo)
					})
				}
  			 }
  		})
  	})
  },
  loginDecrypt(res){
    const {faceInfoId} = res
	  return uni.$u.http.post('/weixin/decrypt ', {
		  session_key:res.loginInfo.session_key,
		  openId:res.loginInfo.openid,
		  encryptedData:res.data,
		  iv:res.iv,
      faceInfoId,
		  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
    const faceInfoId = res.faceInfoId
    // data.faceInfoId = String(res.faceInfoId)
    // if(res.faceInfoId){
    //   data.faceInfoId = res.faceInfoId
    // }
	  wx.checkSession({
	  	success: (res) => {
	  		console.log('seeion未过期')
	  		this.onLogin(loginInfo,iv,data,faceInfoId,callback)
	  	},
	  	fail: (res) => {
	  		console.log('seeion已过期')
	  		this.wxLoginAndGetOpenid(true).then(loginInfo => {
	  			this.onLogin(loginInfo,iv,data,faceInfoId,callback)
	  		})
	  	}
	  })
  },
  // 首页调用发送优惠券接口
  sendUserCoupon(data) {
      return uni.$u.http
      .post('/v1/issue/user/coupon', data)
      .then((res) => {
				Store.commit('setMenuOption', {});
        return res;
      })
      .catch((err) => {
        context.showToast({
          title: '服务器错误',
          icon: 'none',
        });
				Store.commit('setMenuOption', {});
        return err;
      });
  },
  // 获取用户信息
  getUserInfo(data) {
    return uni.$u.http
    .get(`/system/customer/detail`, {})
    .then((res) => {
      console.log(res,data)
      const { birthday, createTime, id, phone, sex, userName, avatarUrl } = res.data.data
      const {avatarUrl:localAvatarUrl} = uni.getStorageSync('UserInfo')
      const sendData = {
        ...data,
        avatarUrl: avatarUrl||localAvatarUrl,
        sex: sex?1:0,
        customerName:userName,
        phone: phone.substr(0,3) + "****" + phone.substr(7),
        id:id
      }
      if(!birthday){
        sendData.canEditBirthday = true
        sendData.birthday = new Date(createTime.replace(/-/g,'/')).valueOf()
      }else{
        sendData.canEditBirthday = false
        sendData.birthday = Date.parse(birthday)
      }
      Store.commit('setUserInfo', sendData);
      uni.setStorageSync('UserInfo',sendData)
      const MenuOption = Store.state.user.menuOption
      if(JSON.stringify(MenuOption)!=='{}') {
        const {num,serial_no,source} = MenuOption
        const sendDataOption = {
					phone:sendData.phoneNumber,
					user_id:sendData.id,
					source:source,
					param:JSON.stringify({
						serial_no,
						num
					})
				}
        this.sendUserCoupon(sendDataOption)
      }
    })
    .catch((err) => {
      context.showToast({ title: '服务器错误', icon: 'none' });
    });
  },
  onLogin(loginInfo,iv,data,faceInfoId,callback) {
	this.loginDecrypt({loginInfo:JSON.parse(loginInfo),faceInfoId,iv,data}).then(res => {
	const { statusCode, data } = res;
            const { code, token, phoneNumber } = data;
            if (statusCode == 200 && data && code == 200) {
              console.log(token,'-------token')
              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);
					    this.getUserInfo(data)
		          if(callback)
		            return	callback();
              }
	}).catch((err) => {
            context.showToast({
              title: err.msg,
            });
    });
  },
  setAllow(params) {
    return uni.$u.http
      .post('/system/customer/allow', params)
      .then((res) => {
        return res;
      })
      .catch((err) => {
        const {data} = err
        const {msg} = data
        context.showToast({ title: msg, icon: 'none' });
        return err
      });
  },
  // 获取用户订阅消息
  getUserMsgInfo(params) {
    return  uni.$u.http
    .get('/system/customer/detail')
    .then((res) => {
      return res;
    })
    .catch((err) => {
      const {data} = err
      const {msg} = data
      context.showToast({ title: msg, icon: 'none' });
      return err
    });
  },
  // 获取用户优惠券数量
  getCouponNum(params) {
    return  uni.$u.http
    .get('/app/homepage/coupon-count')
    .then((res) => {
      return res;
    })
    .catch((err) => {
      const {data} = err
      const {msg} = data
      context.showToast({ title: msg, icon: 'none' });
      return err
    });
  }
};
