<template>
  <ElDialog
    v-model="visible"
    :title="title"
    :width="width"
    align-center
    :before-close="handleClose"
  >
    <ElForm ref="formRef" :model="formData" :rules="formRules" label-width="100px">
      <!-- 选择下拉项表单项 -->
      <ElFormItem v-if="showSelect" :label="selectLabel" :prop="selectProp">
        <ElSelect
          v-model="formData[selectField]"
          :placeholder="selectPlaceholder"
          filterable
          remote
          :remote-method="handleRemoteSearch"
          :loading="selectLoading"
          clearable
          style="width: 100%"
        >
          <ElOption
            v-for="item in selectOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </ElSelect>
      </ElFormItem>

      <!-- 充值金额输入框 -->
      <ElFormItem v-if="showAmount" label="充值金额" prop="amount">
        <ElInput v-model="formData.amount" placeholder="请输入充值金额">
          <template #append>元</template>
        </ElInput>
      </ElFormItem>

      <!-- 备注信息 -->
      <ElFormItem v-if="showRemark" label="备注" prop="remark">
        <ElInput
          v-model="formData.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入备注信息（可选）"
        />
      </ElFormItem>

      <!-- 选中的网卡信息展示 -->
      <ElFormItem v-if="selectedCards.length > 0" label="选中网卡">
        <div class="selected-cards-info">
          <ElTag type="info">已选择 {{ selectedCards.length }} 张网卡</ElTag>
          <ElButton type="text" size="small" @click="showCardList = !showCardList">
            {{ showCardList ? '收起' : '查看详情' }}
          </ElButton>
        </div>
        <div v-if="showCardList" class="card-list">
          <div v-for="card in selectedCards.slice(0, 5)" :key="card.id" class="card-item">
            {{ card.iccid }}
          </div>
          <div v-if="selectedCards.length > 5" class="more-cards">
            还有 {{ selectedCards.length - 5 }} 张网卡...
          </div>
        </div>
      </ElFormItem>
    </ElForm>

    <template #footer>
      <ElButton @click="handleClose">取消</ElButton>
      <ElButton type="primary" @click="handleConfirm" :loading="confirmLoading"> 确认 </ElButton>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
  import {
    ElDialog,
    ElForm,
    ElFormItem,
    ElSelect,
    ElOption,
    ElInput,
    ElButton,
    ElTag
  } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'

  interface SelectOption {
    label: string
    value: string | number
  }

  interface SelectedCard {
    id: number | string
    iccid: string
    [key: string]: any
  }

  interface Props {
    // 弹框基础配置
    title: string
    width?: string

    // 下拉选择配置
    showSelect?: boolean
    selectLabel?: string
    selectProp?: string
    selectPlaceholder?: string

    // 其他表单项配置
    showAmount?: boolean
    showRemark?: boolean

    // 选中的网卡
    selectedCards?: SelectedCard[]

    // 远程搜索方法
    remoteSearch?: (query: string) => Promise<SelectOption[]>
  }

  interface Emits {
    (e: 'update:visible', value: boolean): void
    (e: 'confirm', data: any): void
    (e: 'close'): void
  }

  const props = withDefaults(defineProps<Props>(), {
    width: '500px',
    showSelect: true,
    selectLabel: '请选择',
    selectProp: 'selectedValue',
    selectPlaceholder: '请选择选项',
    showAmount: false,
    showRemark: true,
    selectedCards: () => []
  })

  const emit = defineEmits<Emits>()

  const visible = defineModel<boolean>('visible', { default: false })

  const formRef = ref<FormInstance>()
  const selectLoading = ref(false)
  const confirmLoading = ref(false)
  const showCardList = ref(false)

  // 表单数据
  type FormData = Record<string, string> & {
    selectedValue: string
    amount: string
    remark: string
  }

  const formData = reactive<FormData>({
    selectedValue: '',
    amount: '',
    remark: ''
  })

  const selectField = computed(() => props.selectProp || 'selectedValue')

  // 下拉选项
  const selectOptions = ref<SelectOption[]>([])

  // 表单验证规则
  const formRules = computed<FormRules>(() => {
    const rules: FormRules = {}

    if (props.showSelect) {
      rules[selectField.value] = [
        { required: true, message: `请选择${props.selectLabel}`, trigger: 'change' }
      ]
    }

    if (props.showAmount) {
      rules.amount = [
        { required: true, message: '请输入充值金额', trigger: 'blur' },
        { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确的金额格式', trigger: 'blur' }
      ]
    }

    return rules
  })

  // 处理远程搜索
  const handleRemoteSearch = async (query: string) => {
    if (!props.remoteSearch) return

    selectLoading.value = true
    try {
      const options = await props.remoteSearch(query)
      selectOptions.value = options
    } catch (error) {
      console.error('远程搜索失败:', error)
      console.log('搜索失败，请重试')
    } finally {
      selectLoading.value = false
    }
  }

  // 初始化时加载默认选项
  const loadDefaultOptions = async () => {
    if (props.remoteSearch) {
      // 加载默认数据，传入空字符串以获取默认的10条数据
      await handleRemoteSearch('')
    }
  }

  // 处理确认
  const handleConfirm = async () => {
    if (!formRef.value) return

    try {
      await formRef.value.validate()

      confirmLoading.value = true

      // 发送表单数据
      const submitData = {
        ...formData,
        selectedCards: props.selectedCards
      }

      emit('confirm', submitData)
    } catch (error) {
      console.error('表单验证失败:', error)
    } finally {
      confirmLoading.value = false
    }
  }

  // 处理关闭
  const handleClose = () => {
    formRef.value?.resetFields()
    showCardList.value = false
    emit('close')
    visible.value = false
  }

  // 监听弹框显示状态
  watch(visible, (newVal) => {
    if (newVal) {
      loadDefaultOptions()
    }
  })
</script>

<style lang="scss" scoped>
  .selected-cards-info {
    display: flex;
    gap: 12px;
    align-items: center;
    margin-bottom: 8px;
  }

  .card-list {
    max-height: 120px;
    padding: 8px;
    margin-top: 8px;
    overflow-y: auto;
    background-color: var(--el-fill-color-lighter);
    border-radius: 4px;

    .card-item {
      padding: 2px 0;
      font-size: 12px;
      color: var(--el-text-color-regular);
    }

    .more-cards {
      padding: 2px 0;
      font-size: 12px;
      font-style: italic;
      color: var(--el-text-color-placeholder);
    }
  }
</style>
