import orderApi from '@/api/order'
import QRCode from 'qrcode'

interface PayConfig {
  type?: 'wx'
  interval?: number
  timeout?: number
  init?: anyFuc
}

export const usePay = (config: PayConfig = {}) => {
  const url = ref('')
  const qrCode = ref('')
  const status = ref<-1 | 0 | 1>(0) // -1二维码失效 0未支付 1已支付
  const reqRes = ref<anyObj>({})
  const loading = ref(false)
  let timer: any

  const loop = (id: any) => {
    timer = setInterval(async () => {
      if (!id) {
        console.error('order id is required')
        end()
        return
      }
      const {
        data: { data: res },
      } = await orderApi.getPayStatus(id)
      reqRes.value = res

      if (res.orderPayExpiredStatus === 1) {
        status.value = -1
        end()
        return
      }

      if (res.status === 1) {
        status.value = 1
        end()
        return
      }
    }, config.interval || 3000)
  }

  const start = async (init?: any) => {
    loading.value = true
    try {
      clear()
      if (!(init || config.init)) return
      const {
        data: { data: res },
      } = await (init || config.init)!()
      url.value = res.codeUrl
      qrCode.value = await QRCode.toDataURL(url.value)
      loop(res.payId)
      setTimeout(
        () => {
          end()
        },
        config.timeout || 1000 * 60 * 6,
      )
    } catch (err) {
      qrCode.value = ''
    } finally {
      loading.value = false
    }
  }

  const end = () => {
    clearInterval(timer)
    timer = null
  }

  const clear = () => {
    end()
    status.value = 0
  }

  return {
    qrCode,
    status,
    reqRes,
    loading,
    start,
    end,
  }
}
