<template>
  <ElDialog
    v-model="visible"
    :title="$t('billing.export.title')"
    width="600px"
    :close-on-click-modal="false"
    @closed="handleClosed"
  >
    <ElForm :model="formData" :rules="rules" ref="formRef" label-width="100px">
      <!-- 导出格式 -->
      <ElFormItem :label="$t('billing.export.format')" prop="format">
        <ElRadioGroup v-model="formData.format">
          <ElRadioButton value="excel">
            <ArtSvgIcon icon="ri:file-excel-2-line" class="mr-1" />
            {{ $t('billing.export.formatExcel') }}
          </ElRadioButton>
          <ElRadioButton value="pdf">
            <ArtSvgIcon icon="ri:file-pdf-2-line" class="mr-1" />
            {{ $t('billing.export.formatPdf') }}
          </ElRadioButton>
          <ElRadioButton value="csv">
            <ArtSvgIcon icon="ri:file-text-line" class="mr-1" />
            {{ $t('billing.export.formatCsv') }}
          </ElRadioButton>
        </ElRadioGroup>
      </ElFormItem>

      <!-- 导出范围 -->
      <ElFormItem :label="$t('billing.export.scope')" prop="scope">
        <ElRadioGroup v-model="formData.scope">
          <ElRadio value="current">{{ $t('billing.export.currentPage') }}</ElRadio>
          <ElRadio value="selected" :disabled="!hasSelectedRows">
            {{ $t('billing.export.selected') }}
            <span v-if="hasSelectedRows" class="text-sm text-gray-500">
              ({{ selectedCount }})
            </span>
          </ElRadio>
          <ElRadio value="all">{{ $t('billing.export.all') }}</ElRadio>
        </ElRadioGroup>
      </ElFormItem>

      <!-- 字段选择 -->
      <ElFormItem :label="$t('billing.export.fields')" prop="fields">
        <ElCheckboxGroup v-model="formData.fields">
          <ElRow :gutter="16">
            <ElCol :span="8" v-for="field in fieldOptions" :key="field.value">
              <ElCheckbox :value="field.value" :disabled="field.required">
                {{ field.label }}
                <ElTag v-if="field.required" size="small" type="info">
                  {{ $t('common.required') }}
                </ElTag>
              </ElCheckbox>
            </ElCol>
          </ElRow>
        </ElCheckboxGroup>
      </ElFormItem>

      <!-- 日期范围（仅当选择"全部"时显示） -->
      <ElFormItem
        v-if="formData.scope === 'all'"
        :label="$t('billing.export.dateRange')"
        prop="dateRange"
      >
        <ElDatePicker
          v-model="formData.dateRange"
          type="daterange"
          :placeholder="$t('billing.export.dateRangePlaceholder')"
          value-format="YYYY-MM-DD"
          style="width: 100%"
        />
      </ElFormItem>
    </ElForm>

    <template #footer>
      <ElButton @click="handleCancel">{{ $t('common.cancel') }}</ElButton>
      <ElButton type="primary" :loading="exporting" @click="handleExport">
        <ArtSvgIcon icon="ri:download-2-line" class="mr-1" />
        {{ $t('billing.export.confirm') }}
      </ElButton>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
  import { ref, computed, reactive, watch } from 'vue'
  import { useI18n } from 'vue-i18n'
  import {
    ElDialog,
    ElForm,
    ElFormItem,
    ElRadioGroup,
    ElRadioButton,
    ElRadio,
    ElCheckboxGroup,
    ElCheckbox,
    ElDatePicker,
    ElButton,
    ElRow,
    ElCol,
    ElTag,
    type FormInstance,
    type FormRules
  } from 'element-plus'
  import ArtSvgIcon from '@/components/core/base/art-svg-icon/index.vue'

  interface Props {
    selectedRows?: Api.Billing.BillingListDto[]
  }

  interface Emits {
    (e: 'export', data: ExportConfig): void
  }

  interface ExportConfig {
    format: 'excel' | 'pdf' | 'csv'
    scope: 'current' | 'selected' | 'all'
    fields: string[]
    dateRange?: string[]
  }

  const props = defineProps<Props>()
  const emit = defineEmits<Emits>()

  const { t } = useI18n()

  const visible = ref(false)
  const exporting = ref(false)
  const formRef = ref<FormInstance>()

  const formData = reactive<ExportConfig>({
    format: 'excel',
    scope: 'current',
    fields: [
      'statementNo',
      'tenantName',
      'billingType',
      'amountDue',
      'amountPaid',
      'status',
      'dueDate'
    ],
    dateRange: undefined
  })

  const fieldOptions = computed(() => [
    { value: 'statementNo', label: t('billing.field.statementNo'), required: true },
    { value: 'tenantName', label: t('billing.field.tenantName'), required: true },
    { value: 'billingType', label: t('billing.field.billingType'), required: false },
    { value: 'amountDue', label: t('billing.field.amountDue'), required: false },
    { value: 'amountPaid', label: t('billing.field.amountPaid'), required: false },
    { value: 'status', label: t('billing.field.status'), required: false },
    { value: 'dueDate', label: t('billing.field.dueDate'), required: false },
    { value: 'periodStart', label: t('billing.field.periodStart'), required: false },
    { value: 'periodEnd', label: t('billing.field.periodEnd'), required: false },
    { value: 'createdAt', label: t('billing.field.createdAt'), required: false }
  ])

  const hasSelectedRows = computed(() => (props.selectedRows?.length ?? 0) > 0)
  const selectedCount = computed(() => props.selectedRows?.length ?? 0)

  const rules: FormRules = {
    format: [{ required: true, message: t('billing.export.formatRequired'), trigger: 'change' }],
    scope: [{ required: true, message: t('billing.export.scopeRequired'), trigger: 'change' }],
    fields: [
      {
        required: true,
        type: 'array',
        min: 1,
        message: t('billing.export.fieldsRequired'),
        trigger: 'change'
      }
    ]
  }

  // Watch scope changes to ensure required fields are always selected
  watch(
    () => formData.fields,
    (newFields) => {
      const requiredFields = fieldOptions.value.filter((f) => f.required).map((f) => f.value)
      requiredFields.forEach((field) => {
        if (!newFields.includes(field)) {
          newFields.push(field)
        }
      })
    }
  )

  // Auto-switch scope when selected rows change
  watch(
    () => props.selectedRows,
    (newRows) => {
      if (!newRows || newRows.length === 0) {
        if (formData.scope === 'selected') {
          formData.scope = 'current'
        }
      }
    }
  )

  const open = () => {
    visible.value = true
  }

  const handleCancel = () => {
    visible.value = false
  }

  const handleExport = async () => {
    if (!formRef.value) return

    try {
      await formRef.value.validate()
      exporting.value = true
      emit('export', { ...formData })
      visible.value = false
    } catch (error) {
      console.error('Validation failed:', error)
    } finally {
      exporting.value = false
    }
  }

  const handleClosed = () => {
    formRef.value?.resetFields()
    formData.format = 'excel'
    formData.scope = 'current'
    formData.fields = [
      'statementNo',
      'tenantName',
      'billingType',
      'amountDue',
      'amountPaid',
      'status',
      'dueDate'
    ]
    formData.dateRange = undefined
  }

  defineExpose({
    open
  })
</script>

<style scoped>
  .mr-1 {
    margin-right: 4px;
  }

  .text-sm {
    font-size: 14px;
  }

  .text-gray-500 {
    color: var(--el-text-color-secondary);
  }
</style>
