import { Apis } from '@/gen/Apis'
import useModel from './model'
import { getApiLoading } from '@/common/libraries/apiLoading'
import { tongLianPay } from '@/common/libraries/pay'

const getShow = (timer?: any) => {
  Apis.Bill.Bills.Show({ bill_id: useModel?.OrderInfo?.value?.id }).then(res => {
    useModel.loadingShowNumber.value += 1
    useModel.orderShow.value = res?.data
    // useModel.houseInfo.value = res?.data?.house_order_items[0]
    if (res?.data?.payment_status === 'Paid') {
      useModel.payDisabled.value = false
      clearInterval(timer)
      useModel.loadingLabel.value = ''
      uni.hideLoading()
      uni.redirectTo({
        url: '/INDEX/pay/success'
      })
    }
    console.log('orderShow', res?.data)
  })
}

const loadShow = () => {
  useModel.loadingLabel.value = '更新账单中...'
  useModel.timer.value = setInterval(() => {
    if (
      useModel?.loadingShowNumber?.value > 5 &&
      useModel?.orderShow?.value?.order_status === 'Pending'
    ) {
      useModel.loading.value = false
      useModel.payDisabled.value = false
      useModel.loadingShowNumber.value = 0
      useModel.loadingLabel.value = ''
      uni.hideLoading()
      clearInterval(useModel.timer.value)
      return
    }
    if (useModel.loadingShowNumber.value <= 5) {
      getShow(useModel.timer.value)
    }
  }, 1500)
}

export default {
  onPay() {
    useModel.loading.value = true
    getApiLoading(Apis.Bill.Bills.Payment, { bill_id: useModel?.OrderInfo?.value?.id,payment_method:useModel?.orderShow?.value?.payment_method }).then(
      res => {
        console.log('onPay', res?.data)
        useModel.loading.value = false
        useModel.payDisabled.value = true
        tongLianPay(
          res?.data,
          () => {},
          () => {
            useModel.loading.value = false
            useModel.payDisabled.value = false
          }
        )
      }
    )
  },
  loadShow,
  getShow
}
