<template>
  <ElDialog
    v-model="visible"
    :title="$t('batch.extend.title')"
    width="700px"
    :close-on-click-modal="false"
    @closed="handleClosed"
  >
    <div v-loading="loading">
      <!-- 1. 已选订阅列表 -->
      <div class="selected-info">
        <ElAlert
          :title="$t('batch.extend.selectedCount', { count: selectedSubscriptions.length })"
          type="info"
          :closable="false"
        />
      </div>

      <div class="subscriptions-list">
        <ElTable :data="selectedSubscriptions" max-height="300" size="small">
          <ElTableColumn
            prop="tenantName"
            :label="$t('subscription.table.tenantName')"
            min-width="150"
          />
          <ElTableColumn
            prop="packageName"
            :label="$t('subscription.table.currentPackage')"
            min-width="120"
          />
          <ElTableColumn
            prop="effectiveTo"
            :label="$t('subscription.table.expireDate')"
            width="120"
          >
            <template #default="{ row }">
              {{ formatDate(row.effectiveTo) }}
            </template>
          </ElTableColumn>
        </ElTable>
      </div>

      <!-- 2. 延期表单 -->
      <ElForm
        ref="formRef"
        :model="formModel"
        :rules="rules"
        label-width="110px"
        class="extend-form"
      >
        <!-- 延期时长 -->
        <ElFormItem :label="$t('batch.extend.duration')" prop="duration">
          <div class="duration-input">
            <ElInputNumber v-model="formModel.duration" :min="1" :max="999" />
            <ElRadioGroup v-model="formModel.unit" class="ml-2">
              <ElRadio value="day">{{ $t('subscription.extend.unitDay') }}</ElRadio>
              <ElRadio value="month">{{ $t('subscription.extend.unitMonth') }}</ElRadio>
            </ElRadioGroup>
          </div>
        </ElFormItem>

        <!-- 备注 -->
        <ElFormItem :label="$t('batch.extend.notes')" prop="notes">
          <ElInput
            v-model="formModel.notes"
            :placeholder="$t('batch.extend.notesPlaceholder')"
            type="textarea"
            :rows="3"
            maxlength="256"
            show-word-limit
          />
        </ElFormItem>
      </ElForm>

      <!-- 3. 执行结果 -->
      <div v-if="showResult" class="result-section">
        <ElAlert
          :title="
            $t('batch.extend.result', { success: result.successCount, failed: result.failureCount })
          "
          :type="result.failureCount === 0 ? 'success' : 'warning'"
          :closable="false"
        />

        <div v-if="result.failureCount > 0" class="failed-list">
          <div class="failed-title">{{ $t('batch.extend.failedItems') }}</div>
          <div v-for="item in failedItems" :key="item.subscriptionId" class="failed-item">
            <span class="failed-name">{{ getSubscriptionName(item.subscriptionId) }}</span>
            <span class="failed-message">{{ item.reason }}</span>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <ElButton @click="visible = false">{{ $t('common.cancel') }}</ElButton>
        <ElButton type="primary" :loading="submitting" :disabled="showResult" @click="handleSubmit">
          {{ $t('common.confirm') }}
        </ElButton>
      </span>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
  import { ref, reactive, computed } from 'vue'
  import { useI18n } from 'vue-i18n'
  import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
  import { batchExtendSubscriptions } from '@/api/subscription'
  import {
    ElAlert,
    ElButton,
    ElDialog,
    ElForm,
    ElFormItem,
    ElInput,
    ElInputNumber,
    ElRadio,
    ElRadioGroup,
    ElTable,
    ElTableColumn
  } from 'element-plus'

  defineOptions({ name: 'BatchExtendDialog' })

  const { t } = useI18n()

  const emit = defineEmits<{
    (e: 'success'): void
  }>()

  // 1. 响应式变量
  const visible = ref(false)
  const loading = ref(false)
  const submitting = ref(false)
  const formRef = ref<FormInstance>()

  const selectedSubscriptions = ref<Api.Subscription.SubscriptionDto[]>([])

  const formModel = reactive({
    duration: 1,
    unit: 'month' as 'day' | 'month',
    notes: ''
  })

  const showResult = ref(false)
  const result = ref({
    successCount: 0,
    failureCount: 0,
    failures: [] as Array<{ subscriptionId: string; reason: string }>
  })

  // 2. 表单校验规则
  const rules = computed<FormRules>(() => ({
    duration: [
      {
        required: true,
        message: t('subscription.extend.validation.durationRequired'),
        trigger: 'change'
      },
      {
        type: 'number',
        min: 1,
        message: t('subscription.extend.validation.durationMin'),
        trigger: 'change'
      }
    ]
  }))

  // 3. 计算失败项
  const failedItems = computed(() => {
    return result.value.failures
  })

  // 4. 打开弹窗
  const open = (subscriptions: Api.Subscription.SubscriptionDto[]) => {
    if (subscriptions.length === 0) {
      ElMessage.warning(t('batch.extend.noSelection'))
      return
    }

    visible.value = true
    selectedSubscriptions.value = subscriptions

    // 初始化表单
    formModel.duration = 1
    formModel.unit = 'month'
    formModel.notes = ''
    showResult.value = false
    result.value = {
      successCount: 0,
      failureCount: 0,
      failures: []
    }
    formRef.value?.clearValidate()
  }

  // 5. 关闭处理
  const handleClosed = () => {
    selectedSubscriptions.value = []
    formRef.value?.resetFields()
  }

  // 6. 提交处理
  const handleSubmit = async () => {
    if (!formRef.value) return

    await formRef.value.validate(async (valid) => {
      if (!valid) return

      submitting.value = true
      try {
        // 计算延期天数
        let extendDays = formModel.duration
        if (formModel.unit === 'month') {
          extendDays = formModel.duration * 30
        }

        const response = await batchExtendSubscriptions({
          subscriptionIds: selectedSubscriptions.value.map((s) => s.id),
          durationDays: extendDays,
          notes: formModel.notes || undefined
        })

        result.value = response
        showResult.value = true

        if (response.failureCount === 0) {
          ElMessage.success(t('batch.extend.success'))
          emit('success')
          setTimeout(() => {
            visible.value = false
          }, 1500)
        } else {
          ElMessage.warning(
            t('batch.extend.partialSuccess', {
              success: response.successCount,
              failed: response.failureCount
            })
          )
        }
      } catch (error) {
        console.error(error)
      } finally {
        submitting.value = false
      }
    })
  }

  // 7. 工具函数
  const formatDate = (date: string | undefined) => {
    if (!date) return '-'
    return new Date(date).toLocaleDateString()
  }

  const getSubscriptionName = (subscriptionId: string) => {
    const subscription = selectedSubscriptions.value.find((s) => s.id === subscriptionId)
    return subscription ? subscription.tenantName : subscriptionId
  }

  defineExpose({ open })
</script>

<style scoped>
  .selected-info {
    margin-bottom: 16px;
  }

  .subscriptions-list {
    margin-bottom: 24px;
  }

  .extend-form {
    margin-top: 24px;
  }

  .duration-input {
    display: flex;
    align-items: center;
    width: 100%;
  }

  .ml-2 {
    margin-left: 12px;
  }

  .result-section {
    margin-top: 24px;
  }

  .failed-list {
    padding: 12px;
    margin-top: 16px;
    background-color: var(--el-fill-color-light);
    border-radius: 4px;
  }

  .failed-title {
    margin-bottom: 8px;
    font-weight: 600;
    color: var(--el-text-color-primary);
  }

  .failed-item {
    display: flex;
    gap: 12px;
    padding: 8px 0;
    border-bottom: 1px solid var(--el-border-color-lighter);
  }

  .failed-item:last-child {
    border-bottom: none;
  }

  .failed-name {
    min-width: 150px;
    font-weight: 500;
    color: var(--el-text-color-primary);
  }

  .failed-message {
    flex: 1;
    color: var(--el-text-color-secondary);
  }
</style>
