<script setup lang="ts">
import { ReceiptModal } from '@af-mobile-client-vue3/components/common/otherCharge'
import XCellList from '@af-mobile-client-vue3/components/data/XCellList/index.vue'
import { getConfigByName } from '@af-mobile-client-vue3/services/api/common'
import { showToast } from 'vant'
import { computed, nextTick, onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

interface PrintConfig {
  printLogic?: string
  [key: string]: any
}

interface ChargeConfigs {
  machineChargeConfig: PrintConfig
  iotChargeConfig: PrintConfig
  cardChargeConfig: PrintConfig
  overChargeConfig: PrintConfig
}

const configName = 'mobile_ChargeQueryCRUD'
const serviceName = 'af-revenue'
const userId = computed(() => useRoute().query.userId?.toString() || '')
const router = useRouter()

const config = reactive<ChargeConfigs>({
  machineChargeConfig: {},
  iotChargeConfig: {},
  cardChargeConfig: {},
  overChargeConfig: {},
})
const printRef = ref<InstanceType<typeof ReceiptModal> | null>(null)

const PRINT_LOGIC_MAP: Record<string, keyof ChargeConfigs> = {
  机表收费: 'machineChargeConfig',
  物联网收费: 'iotChargeConfig',
  卡表收费: 'cardChargeConfig',
  超量收费: 'overChargeConfig',
}

function fetchConfig(configKey: string, serviceName: string): Promise<PrintConfig> {
  return new Promise((resolve) => {
    getConfigByName(configKey, (res) => {
      resolve(res ?? {})
    }, serviceName)
  })
}

async function initConfig() {
  try {
    const [
      machineConfig,
      iotConfig,
      cardConfig,
      overConfig,
    ] = await Promise.all([
      fetchConfig('mobile_MachineCharge', 'af-revenue'),
      fetchConfig('mobile_IOTMeterCenter', 'af-revenue'),
      fetchConfig('mobile_CardMeterCenter', 'af-revenue'),
      fetchConfig('mobile_overUsageConfig', 'af-revenue'),
    ])
    Object.assign(config.machineChargeConfig, machineConfig)
    Object.assign(config.iotChargeConfig, iotConfig)
    Object.assign(config.cardChargeConfig, cardConfig)
    Object.assign(config.overChargeConfig, overConfig)
    const allEmpty = [machineConfig, iotConfig, cardConfig, overConfig]
      .every(c => Object.keys(c).length === 0)
    if (allEmpty) {
      showToast('配置加载失败，请检查网络')
    }
  }
  catch (error) {
    console.error('配置初始化异常:', error)
    showToast('系统异常，请稍后重试')
  }
}

function billPrint(record: { s_f_type: string, s_id: string }) {
  const { s_f_type, s_id } = record
  if (s_f_type === '退费') {
    printRef.value?.printParams('mobile_refundPrintParams', s_id)
    return
  }
  const configKey = PRINT_LOGIC_MAP[s_f_type]
  if (!configKey || !config[configKey]?.printLogic) {
    showToast(`该类型收费收据暂不支持补打`)
    return
  }
  printRef.value?.printParams(config[configKey].printLogic, s_id)
}

onMounted(() => {
  nextTick(initConfig)
})
</script>

<template>
  <main class="h-full w-full">
    <van-nav-bar
      title="缴费记录"
      left-arrow
      fixed
      @click-left="router.go(-1)"
    />

    <XCellList
      :config-name="configName"
      :service-name="serviceName"
      :fix-query-form="{ info_f_userinfo_id: userId }"
      @print="billPrint"
    />
    <ReceiptModal ref="printRef" />
  </main>
</template>
