<script setup lang="ts">
import type { RecordEntry } from './recordEntries'
import type { BaseUser, ConfigItem } from './types'
import useLoading from '@af-mobile-client-vue3/hooks/useLoading'
import { mobileUtil } from '@af-mobile-client-vue3/utils/mobileUtil'
import { Button as VanButton, Empty as VanEmpty, Loading as VanLoading } from 'vant'
import { computed, onActivated, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import InfoDisplay from '../InfoDisplay/index.vue'
import { getCacheUserDetail, getRecentBusinessTime } from './api'
import { defaultRecordEntries } from './recordEntries'

interface Props {
  userInfoId: string // 用户ID（必传）
  isRedirect?: boolean // 是否跳转业务办理页面，默认false
  showRecentTime?: boolean // 是否展示历史时间，默认false
  recordEntries?: RecordEntry[] // 记录入口配置（可选）
  businessButtonText?: string // 业务办理按钮文本，默认"业务办理"
  showBottomButtons?: boolean // 是否显示底部按钮区域，默认false
  showHeader?: boolean // 是否显示头部导航栏，默认false
  headerTitle?: string // 头部标题，默认"用户档案详情"
  getUserDetailApi?: (id: string) => Promise<BaseUser> // 自定义获取用户详情接口
  getRecentTimeApi?: (id: string) => Promise<Record<string, string>> // 自定义获取历史时间接口
}

interface Emits {
  (e: 'close'): void
  (e: 'recordClick', entry: RecordEntry, user: BaseUser): void
  (e: 'businessClick', user: BaseUser): void
  (e: 'print', user: BaseUser): void
}

const props = withDefaults(defineProps<Props>(), {
  isRedirect: false,
  showRecentTime: false,
  businessButtonText: '业务办理',
  showBottomButtons: false,
  showHeader: false,
  headerTitle: '用户档案详情',
  recordEntries: () => defaultRecordEntries,
})

const emit = defineEmits<Emits>()
const router = useRouter()

// 用户数据
const user = ref<BaseUser | null>(null)
const { loading: userLoading, startLoading: startUserLoading, endLoading: endUserLoading } = useLoading(false)
const userError = ref<string | null>(null)

// 控制用户信息展开收起
const showUserInfo = ref(false)

// 最近记录
const recentRecord = ref<Record<string, string>>({})
const { loading: recentRecordLoading, startLoading: startRecentRecordLoading, endLoading: endRecentRecordLoading } = useLoading(false)

// 状态类名
const statusClass = computed(() => {
  if (!user.value?.f_user_state)
    return ''

  switch (user.value.f_user_state) {
    case '正常':
      return 'status-badge--normal'
    case '欠费':
      return 'status-badge--overdue'
    case '暂停':
      return 'status-badge--suspended'
    default:
      return ''
  }
})

// 用户详细信息配置
const userDetailConfig = computed<ConfigItem[]>(() => {
  if (!user.value)
    return []

  return [
    { label: '联系电话', field: 'f_user_phone' },
    { label: '用户类型', field: 'f_user_type' },
    { label: '用户地址', field: 'f_address', full: true },
    { label: '表具类型', field: 'f_meter_type' },
    { label: '表具编号', field: 'f_meternumber' },
    {
      label: '卡号',
      field: 'f_card_id',
      condition: data => data.f_meter_type?.includes('卡表') || data.f_hascard === '是',
    },
    {
      label: '账户余额',
      field: 'f_balance',
      format: value => `¥ ${value}`,
      condition: data => !data.f_meter_type?.includes('物联网表') || (data.f_meter_type?.includes('物联网表') && data.f_user_balance > 0),
    },
    {
      label: '表上余额',
      field: 'f_balance_amount',
      condition: data => data.f_meter_type?.includes('物联网表'),
    },
    { label: '购气次数', field: 'f_times' },
    {
      label: '累计购气(m³)',
      field: 'f_total_gas',
      format: value => `${value}m³`,
    },
    {
      label: '阀控状态',
      field: 'f_valve_state',
      condition: data => data.f_meter_type?.includes('物联网表'),
    },
  ].filter(item => !item.condition || item.condition(user.value))
})

// 筛选符合当前用户表具类型的记录入口
const filteredRecordEntries = computed(() => {
  if (!user.value?.f_meter_type)
    return []

  return props.recordEntries.filter(entry =>
    entry.forMeterTypes.includes(user.value!.f_meter_type),
  )
})

// 获取用户详情
async function fetchUserDetail() {
  if (!props.userInfoId)
    return

  try {
    startUserLoading()
    userError.value = null
    const api = props.getUserDetailApi || getCacheUserDetail
    user.value = await api(props.userInfoId)
  }
  catch (error) {
    console.error('获取用户详情失败:', error)
    userError.value = error instanceof Error ? error.message : '获取用户详情失败'
    user.value = null
  }
  finally {
    endUserLoading()
  }
}

// 重试获取用户详情
function retryFetchUserDetail() {
  fetchUserDetail()
}

// 获取最近记录
async function fetchRecentRecord() {
  if (!props.showRecentTime || !props.userInfoId)
    return

  try {
    startRecentRecordLoading()
    const api = props.getRecentTimeApi || getRecentBusinessTime
    recentRecord.value = await api(props.userInfoId)
  }
  catch (error) {
    console.error('获取最近记录失败:', error)
    recentRecord.value = {}
  }
  finally {
    endRecentRecordLoading()
  }
}

// 查看记录详情
function viewRecordDetail(entry: RecordEntry) {
  if (!user.value)
    return
  router.push({
    name: entry.route,
    query: {
      userName: user.value.f_user_name,
      userId: user.value.f_userinfo_id,
      userfilesId: user.value.f_userfiles_id,
    },
  })
}

// 打开业务办理
function openBusinessHandler() {
  if (!user.value)
    return
  console.log('openBusinessHandler', props.isRedirect)
  if (props.isRedirect) {
    router.push({
      name: 'BusinessHandler',
    })
  }
  else {
    emit('businessClick', user.value)
  }
}

// 打印档案
function printProfile() {
  if (!user.value)
    return

  // 默认打印实现
  const printContent = [
    { type: 3, text: '自 助 购 气 凭 证', fontsize: 3, isbold: true, align: 'center' },
    { type: 3, text: '----------------------------', fontsize: 3, isbold: true, align: 'center' },
    { type: 3, text: `用户编号：${user.value.f_userinfo_code}`, fontsize: 2, isbold: true, align: 'left' },
    { type: 3, text: `用户姓名：${user.value.f_user_name}`, fontsize: 2, isbold: true, align: 'left' },
    { type: 3, text: `用户地址：${user.value.f_address}`, fontsize: 2, isbold: true, align: 'left' },
    { type: 3, text: '', fontsize: 3, isbold: true, align: 'center' },
    { type: 4, value: 5, unit: 'pixel' },
  ]

  mobileUtil.execute({
    funcName: 'print',
    param: { data: printContent },
    callbackFunc: (result) => {
      console.log('打印结果:', result)
    },
  })

  // 同时触发自定义打印事件
  emit('print', user.value)
}

// 防止操作员办完业务从业务办理返回到此页面再点击业务办理这里需要在进入页面时调用刷新数据
onActivated(async () => {
  console.log('进入页面（已缓存）')
  await fetchUserDetail()
  if (props.showRecentTime) {
    await fetchRecentRecord()
  }
})

// 监听用户ID变化
watch(() => props.userInfoId, async (newId) => {
  if (newId) {
    await fetchUserDetail()
    if (props.showRecentTime) {
      await fetchRecentRecord()
    }
  }
}, { immediate: true })
</script>

<template>
  <div class="user-detail" :class="{ 'has-header': props.showHeader }">
    <!-- 头部导航栏 -->
    <div v-if="props.showHeader" class="user-detail__header">
      <div class="header-left">
        <button type="button" class="back-button" @click="emit('close')">
          <VanIcon name="arrow-left" />
        </button>
        <h3 class="header-title">
          {{ props.headerTitle }}
        </h3>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="userLoading" class="loading-container">
      <VanLoading size="24px" vertical>
        加载中...
      </VanLoading>
    </div>

    <!-- 错误状态 -->
    <div v-else-if="userError" class="error-container">
      <VanEmpty
        image="error"
        :description="userError"
      >
        <VanButton type="primary" @click="retryFetchUserDetail">
          重试
        </VanButton>
      </VanEmpty>
    </div>

    <!-- 用户详情内容 -->
    <div v-else-if="user" class="user-detail__content">
      <!-- 用户基本信息卡片 -->
      <div class="user-info-card">
        <div
          class="user-info-header"
          @click="showUserInfo = !showUserInfo"
        >
          <div class="user-info-header__left">
            <div class="user-avatar bg-blue-100">
              <i class="i-fa6-solid-user text-blue-500" />
            </div>
            <div class="user-base-info">
              <h3 class="user-name">
                {{ user.f_user_name }}
              </h3>
              <p class="user-id">
                {{ user.f_userinfo_code }}
              </p>
            </div>
          </div>
          <div class="user-info-header__right">
            <span class="status-badge" :class="statusClass">{{ user.f_user_state }}</span>
            <i :class="showUserInfo ? 'i-fa6-solid-chevron-up' : 'i-fa6-solid-chevron-down'" class="text-gray-400" />
          </div>
        </div>
        <div v-show="showUserInfo" class="user-info-body">
          <InfoDisplay :config="userDetailConfig" :data="user" />
        </div>
      </div>

      <!-- 交易记录入口 -->
      <div class="records-container">
        <div
          v-for="entry in filteredRecordEntries"
          :key="entry.id"
          class="record-card"
          @click="viewRecordDetail(entry)"
        >
          <div class="record-card__icon" :class="[entry.bgColor]">
            <i :class="[entry.icon, entry.textColor]" />
          </div>
          <div class="record-card__content">
            <h3 class="record-title">
              {{ entry.title }}
            </h3>
            <p class="record-date">
              最近{{ entry.dateLabel }}：
              <template v-if="recentRecordLoading">
                <i class="i-fa6-solid-spinner animate-spin" />
              </template>
              <template v-else>
                {{ recentRecord[entry.dateLabel] || '无' }}
              </template>
            </p>
          </div>
          <i class="i-fa6-solid-chevron-right text-gray-400" />
        </div>
      </div>

      <!-- 底部按钮 -->
      <div v-if="props.showBottomButtons" class="fixed-bottom-buttons">
        <!-- 自定义底部插槽 -->
        <slot name="bottom" :user="user">
          <!-- 默认底部按钮 -->
          <VanButton
            class="print-button"
            plain
            type="default"
            @click="printProfile"
          >
            <i class="i-fa6-solid-print mr-1" />
            打印档案
          </VanButton>
          <VanButton
            class="business-button"
            type="primary"
            @click="openBusinessHandler"
          >
            <i class="i-fa-solid-file-invoice" />
            {{ businessButtonText }}
          </VanButton>
        </slot>
      </div>
    </div>
  </div>
</template>

<style lang="less" scoped>
.user-detail {
  position: relative;
  background-color: #f5f7fa;
  min-height: 100vh;
  padding-bottom: 70px;

  &__header {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 10;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 16px;
    background-color: #fff;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  }

  &__content {
    padding: 16px;
  }

  // 当有 header 时，为 content 腾出空间
  &.has-header &__content {
    padding-top: calc(16px + 46px); // 16px原有padding + 56px header高度
  }
}

// 加载状态
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
  background-color: #fff;
  margin: 16px;
  border-radius: 8px;
}

// 错误状态
.error-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
  background-color: #fff;
  margin: 16px;
  border-radius: 8px;
  padding: 32px 16px;
}

// 当有 header 时，调整加载和错误状态的位置
.has-header {
  .loading-container,
  .error-container {
    margin-top: calc(16px + 56px); // header高度 + 原有margin
  }
}

.header-left {
  display: flex;
  align-items: center;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.back-button {
  background: none;
  border: none;
  padding: 4px;
  margin-right: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #666;
  cursor: pointer;

  .van-icon {
    font-size: 22px;
  }
}

// 用户信息卡片
.user-info-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin-bottom: 16px;
  overflow: hidden;
}

.user-info-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  cursor: pointer;

  &__left {
    display: flex;
    align-items: center;
  }

  &__right {
    display: flex;
    align-items: center;
    gap: 12px;
  }
}

.user-avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background-color: #e6f7ff;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;

  .van-icon {
    font-size: 24px;
    color: var(--van-primary-color);
  }
}

.user-base-info {
  .user-name {
    font-size: 16px;
    font-weight: 600;
    color: #333;
    margin: 0 0 4px 0;
  }

  .user-id {
    font-size: 13px;
    color: #999;
    margin: 0;
  }
}

.status-badge {
  display: inline-block;
  padding: 2px 10px;
  border-radius: 100px;
  font-size: 12px;
  font-weight: 500;

  &--normal {
    background-color: #e6ffed;
    color: #52c41a;
  }

  &--overdue {
    background-color: #fff1f0;
    color: #f5222d;
  }

  &--suspended {
    background-color: #fff7e6;
    color: #fa8c16;
  }
}

.user-info-body {
  padding: 16px 16px;
  border-top: 1px solid #f0f0f0;
}

// 记录入口卡片
.records-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.record-card {
  display: flex;
  align-items: center;
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  cursor: pointer;

  &__icon {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 12px;
  }

  &__content {
    flex: 1;
    min-width: 0;
  }
}

.record-title {
  font-size: 15px;
  font-weight: 500;
  color: #333;
  margin: 0 0 4px 0;
}

.record-date {
  font-size: 12px;
  color: #999;
  margin: 0;
}

// 底部按钮
.fixed-bottom-buttons {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-between;
  padding: 12px 16px;
  background-color: #fff;
  box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.05);
  z-index: 10;
  gap: 12px;

  .print-button,
  .business-button {
    flex: 1;
    height: 44px;
    font-size: 15px;
    font-weight: 500;
    border-radius: 8px;

    .van-icon {
      font-size: 18px;
      margin-right: 4px;
      vertical-align: -3px;
    }
  }

  .business-button {
    background-color: var(--van-primary-color);
    border-color: var(--van-primary-color);
    box-shadow: 0 2px 6px rgba(24, 144, 255, 0.3);
  }
}

.animate-spin {
  animation: spin 0.5s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
