<template>
  <ElDialog
    v-model="visible"
    :title="$t('batch.remind.title')"
    width="700px"
    :close-on-click-modal="false"
    @closed="handleClosed"
  >
    <div v-loading="loading">
      <!-- 1. 已选订阅列表 -->
      <div class="selected-info">
        <ElAlert
          :title="$t('batch.remind.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="remind-form"
      >
        <!-- 提醒内容 -->
        <ElFormItem :label="$t('batch.remind.content')" prop="content">
          <ElInput
            v-model="formModel.content"
            :placeholder="$t('batch.remind.contentPlaceholder')"
            type="textarea"
            :rows="5"
            maxlength="500"
            show-word-limit
          />
        </ElFormItem>
      </ElForm>

      <!-- 3. 执行结果 -->
      <div v-if="showResult" class="result-section">
        <ElAlert
          :title="
            $t('batch.remind.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.remind.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 { batchSendReminders } from '@/api/subscription'
  import {
    ElAlert,
    ElButton,
    ElDialog,
    ElForm,
    ElFormItem,
    ElInput,
    ElTable,
    ElTableColumn
  } from 'element-plus'

  defineOptions({ name: 'BatchRemindDialog' })

  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({
    content: ''
  })

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

  // 2. 表单校验规则
  const rules = computed<FormRules>(() => ({
    content: [
      { required: true, message: t('batch.remind.validation.contentRequired'), trigger: 'blur' },
      {
        min: 10,
        message: t('batch.remind.validation.contentMin'),
        trigger: 'blur'
      }
    ]
  }))

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

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

    visible.value = true
    selectedSubscriptions.value = subscriptions

    // 初始化表单
    formModel.content = ''
    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 {
        const response = await batchSendReminders({
          subscriptionIds: selectedSubscriptions.value.map((s) => s.id),
          reminderContent: formModel.content
        })

        result.value = response
        showResult.value = true

        if (response.failureCount === 0) {
          ElMessage.success(t('batch.remind.success'))
          emit('success')
          setTimeout(() => {
            visible.value = false
          }, 1500)
        } else {
          ElMessage.warning(
            t('batch.remind.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;
  }

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

  .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>
