import SocketUtil from "@/utils/socket";
import { initSocket } from "@/api/common/index";
import priceAudio from "@/mixins/priceAudio";

export default {
	mixins: [priceAudio],
	data() {
		return {
			priceSocket: null
		};
	},
	onLaunch() {
		this.priceSocketFun();

	},
	methods:{
		/*延迟监听token*/
		priceSocketFun(){
			if(!uni.getStorageSync('token')){
				setTimeout(()=>{
					this.priceSocketFun();
				},100);
			}else{
				this.priceSocket = new SocketUtil({
					onOpen: () => {},
					onMessage: data => {
						let type = data.type || "";
						switch (type) {
							case "init":
								let clientId = data.client_id;

								initSocket(clientId);
								break;
							case "money":
								//到账消息    data:  {type: "money", msg: "微信到账1.2", money: 1.2}
								console.log(data);
								// this.playPriceAudio(data.money);
								this.createPlayHandlerFun(data.url);
								break;
							case "new_order":
								//新订单    data:  {type: "money", msg: "微信到账1.2", money: 1.2}
								console.log(data);
								this.createPlayHandlerFun(data.url);
								break;
							default:
								console.log("default");
						}
					},
					onClose: () => {},
					onError: () => {}
				});
			}
		},
		createPlayHandlerFun(url) {
			const innerAudioContext = uni.createInnerAudioContext();
			innerAudioContext.autoplay = true;
			innerAudioContext.src = url;
			innerAudioContext.onPlay(() => {
				console.log("开始播放");
			});
			innerAudioContext.onError(res => {
				console.log(res.errMsg);
				console.log(res.errCode);
			});
			innerAudioContext.onEnded(err => {
				console.log("开始结束");
				innerAudioContext.destroy();
			});
		}
	}
};
