import { v4 } from 'uuid'
import service from '@/services'
import eventBus from '@/services/bus'
import Socket from './build'
import { RequestCode, MessageType } from './build/types'

export default new (class {
    /** 交易链路 */
    private socket?: Socket;

    private async connect() {
        if (!this.socket) {
            await service.onReady()
            const tradeUrl = service.getConfig('tradeUrl')
            this.socket = new Socket(tradeUrl)

            this.socket.onPush = ({ requestCode, data }) => {
                switch (requestCode) {
                    case RequestCode.PaymentNotify:
                        // 推送支付通知
                        eventBus.$emit('Notify', data)
                        break
                    default: {
                        if (requestCode !== RequestCode.Heartbeat) {
                            console.warn('接收到未定义的通知', requestCode)
                        }
                    }
                }
            }
        }
        return this.socket
    }

    /**
     * 交易请求
     */
    async send() {
        const ws = await this.connect()
        return ws.send({
            headers: {
                requestId: v4(),
                requestCode: RequestCode.OrderPayment,
                messageType: MessageType.Request,
            },
            data: {
                orderNumber: '202304241630113',
                amount: 109.00
            }
        })
    }

    /**
     * 关闭交易链路
     */
    close() {
        this.socket?.close()
    }
})