import request from '../../utils/request/index';

import store from '../../store/index';

export default {

	// 当前是否处于发起请求
	status: false,

	// 本次请求的 唯一标示
	requestUnique: 0,

	// 购物数量 当前统计
	number: 0,

	numberFormat: '',

	getCartNumber:function (must) {

		if (!this.status || must) {

			let requestUnique = this.getUnique();

			this.requestUnique = requestUnique;

		    return new Promise( (resolve, reject)=> {

				request({
					url:'product/getCartNum',
					token:true,
					login:false,
					next:(status)=>{
						this.status = status;
					}
				}).then((data)=>{

					if (requestUnique === this.requestUnique) {

						if ( data.isSuccess) {
							this.setCartNumber(data.data);

							return resolve(this.number);
						} else {
							return reject({
								data: data,
								status: data.status,
								msg:data.msg
							});
						}

					} else {
						return reject({
							data: data,
							status: 0,
							msg:'invalid request'
						});
					}

				}).catch((fail)=>{
					return reject({
						status: 4,
						msg: fail
					})
				});

			});

		}

	},

	setCartNumber:function(number){

		if (number !== this.number) {

			this.number = number;

			if (number <= 0) {
				this.numberFormat  = '';
			} else {
				this.numberFormat = number >99?'99+': String(number);
			}

			// 更新
			store.commit('setNumberFormat',this.number);

			// wx.tab
			return this.saveTabBarBadge();

		}


	},

	checkSet:function(){
		if (this.setFail) {
			return this.saveTabBarBadge();
		}

	},

	saveTabBarBadge:function(){

		if (this.number > 0) {

			return uni.setTabBarBadge({
				index: 2,
				text: this.numberFormat,
				fail:()=>{
					this.setFail = true;
				}
			})
		} else {
			return wx.removeTabBarBadge({
				index: 2,
				fail:(res) =>{
					this.setFail = true;
				}
			});
		}
	},

	getUnique:function () {
		return new Date().getTime();
	}

}
