import config from '../config'
import storage from './storage'
import {navigateTo} from './utils'

export default {
	
	connected: false,
	connecting: false,
	socketTask: false,
	timer: 3000,
	link:0,
	
	/**
	 * 创建 WebSocket 连接。
	 */
	connect(kf_id){
		let users = storage.getJson("users");
		if(users == null){
			navigateTo("public/login");
			return false;
		}
		
		if(this.isConnect()){
			return false;
		}
		
		this.connecting = true;
		this.socketTask = uni.connectSocket({
			url: config.web_socket_url,
			header: {
				'content-type': 'application/json'
			},
			complete: ()=> {}
		});
		
		// 监听WebSocket连接打开事件。
		this.socketTask.onOpen((res) => {
			this.connecting = false
			this.connected = true
			this.send({type:"login", auth:users.token,service_id:kf_id});
		});
		
		this.error();
		
		this.close();
	},
	
	/**
	 * 检查是否己连接
	 */
	isConnect(){
		if (this.connected || this.connecting) {
			return true;
		}
		
		return false;
	},
	
	/**
	 * 重新连接websocket
	 */
	reConnect(){
		this.close();
		this.connect();
	},
	
	/**
	 * 监听 WebSocket 接受到服务器的消息事件
	 * @param {Object} callback
	 */
	message(callback){
		if(this.socketTask != null && this.socketTask.onMessage){
			this.socketTask.onMessage(callback);
		}
	},
	
	send(data){
		if(typeof data == "object"){
			data = JSON.stringify(data);
		}
		
		let that = this;
		return new Promise((resolve, reject)=>{
			that.socketTask.send({
				data:data,
				success(res){
					resolve(res);
				},
				fail(err){
					reject(err);
				}
			})
		});
	},
	
	error(){
		this.socketTask.onError((err) => {
			this.connecting = false
			this.connected = false
			// uni.hideLoading()
			// uni.showModal({
			// 	content: '与服务器断开连接，请稍后再试',
			// 	showCancel: false
			// });
		});
	},
	
	close(){
		if(this.link > 2) {
			return ;
		}
		
		if (this.socketTask && this.socketTask.close) {
			
			this.socketTask.onClose((res) => {
				this.connected = false;
				this.socketTask = false;
				this.link+=1;
				setTimeout(()=>{
					//this.connect();
				},this.timer);
			})
		}
	}
}