<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, sumQuery } from '@af-mobile-client-vue3/services/api/common'
import {
  showToast,
  Col as VanCol,
  NavBar as VanNavBar,
  Row as VanRow,
} 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
}

interface SummaryItem {
  title: string
  value: number
}

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

const summaryList = ref<SummaryItem[]>([])
const isSummaryLoading = ref(false)

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)
}

async function loadSummary(conditionParams: Record<string, any>) {
  if (isSummaryLoading.value)
    return
  isSummaryLoading.value = true
  try {
    const result = await sumQuery({
      queryParamsName: configName,
      pageNo: 1,
      pageSize: 1,
      conditionParams,
    }, serviceName.value)
    if (Array.isArray(result)) {
      summaryList.value = result
    }
  }
  catch (error) {
    console.error('汇总查询异常:', error)
  }
  finally {
    isSummaryLoading.value = false
  }
}

function handleQueryParams(params: any) {
  loadSummary(params)
}

function formatSummaryValue(value: number): string {
  if (typeof value !== 'number' || !Number.isFinite(value))
    return '--'
  return value.toLocaleString('zh-CN', { maximumFractionDigits: 2 })
}

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

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

    <section
      v-if="isSummaryLoading || summaryList.length"
      class="payment-summary"
    >
      <template v-if="isSummaryLoading">
        <VanRow gutter="12" justify="space-around">
          <VanCol span="12">
            <div class="summary-card summary-card--skeleton" />
          </VanCol>
          <VanCol span="12">
            <div class="summary-card summary-card--skeleton" />
          </VanCol>
        </VanRow>
      </template>
      <VanRow v-else gutter="12" justify="space-around">
        <VanCol
          v-for="item in summaryList"
          :key="item.title"
          span="12"
        >
          <div class="summary-card">
            <span class="summary-card__label">{{ item.title }}</span>
            <span class="summary-card__value">{{ formatSummaryValue(item.value) }}</span>
          </div>
        </VanCol>
      </VanRow>
    </section>

    <XCellList
      :config-name="configName"
      :service-name="serviceName"
      :fix-query-form="{ info_f_userinfo_id: userId }"
      @print="billPrint"
      @query-params="handleQueryParams"
    />

    <ReceiptModal ref="printRef" />
  </main>
</template>

<style scoped lang="less">
.payment-summary {
  margin-top: 46px;
  padding: 12px 12px 4px;
  background-color: #f7f8fa;

  .summary-card {
    display: flex;
    flex-direction: column;
    gap: 4px;
    padding: 12px 16px;
    border-radius: 12px;
    background-color: #ffffff;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);

    &__label {
      font-size: 13px;
      color: #646566;
    }

    &__value {
      font-size: 20px;
      font-weight: 600;
      color: #323233;
    }

    &--skeleton {
      height: 72px;
      background: linear-gradient(90deg, #f2f3f5 25%, #e6e8eb 37%, #f2f3f5 63%);
      background-size: 400% 100%;
      animation: payment-summary-skeleton 1.4s ease infinite;
    }
  }
}

@keyframes payment-summary-skeleton {
  0% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0 50%;
  }
}
</style>
