import { useWeAppAuthStore, useWorkStore } from '@/common'
import useModel from './model'
import { Apis } from '@/gen/Apis'
import { getApiLoading } from '@/common/libraries/apiLoading'
const auth = useWeAppAuthStore()
const work = useWorkStore()
import { tongLianPay } from '@/common/libraries/pay'
import { showToastBack, showToast } from '@/common/libraries/naviHelper'

const getPayStatus = (timer?: any) => {
  Apis.HouseOrder.HousePrepayments.GetPayments({
    house_prepayment_payments_id: useModel?.housePrepaymentPayment?.value?.id
  }).then(res => {
    console.log('获取支付状态', res?.data)
    useModel.loadingShowNumber.value += 1
    useModel.orderShow.value = res?.data
    if (res?.data?.payment_status === 'Paid') {
      clearInterval(timer)
      useModel.formData.value.amount = undefined
      useModel.payDisabled.value = false
      showToast('支付成功')
    }
  })
}

const loadShow = () => {
  console.log('定时器', useModel?.loadingShowNumber?.value)
  useModel.timer.value = setInterval(() => {
    if (
      useModel?.loadingShowNumber?.value > 2 &&
      useModel?.orderShow?.value?.payment_status === 'Pending'
    ) {
      useModel.payDisabled.value = false
      uni.hideLoading()
      clearInterval(useModel.timer.value)
      return
    }
    if (useModel.loadingShowNumber.value <= 2) {
      getPayStatus(useModel.timer.value)
    }
  }, 1000)
}

export default {
  loadShow,
  handlePay() {
    useModel.payDisabled.value = true
    getApiLoading(Apis.HouseOrder.HousePrepayments.Payment, useModel?.formData?.value)
      .then(res => {
        useModel.housePrepaymentPayment.value = res?.data?.house_prepayment_payment
        uni.showLoading({
          title: '正在支付...',
          mask: true
        })
        tongLianPay(
          res?.data?.pay_info,
          () => {
            useModel.loadingShowNumber.value = -1
            // loadShow()
            console.log('支付成功')
          },
          () => {
            useModel.payDisabled.value = false
            uni.hideLoading()
          }
        )
        console.log(res)
      })
      .catch(() => {
        useModel.payDisabled.value = false
      })
    console.log('e')
  }
}
