<template>
  <ElDialog v-model="visible" :title="title" width="520px" destroy-on-close>
    <ElAlert type="info" :closable="false" show-icon class="export-rule-alert">
      <template #title>{{ description }}</template>
    </ElAlert>

    <ElForm label-width="100px" class="export-task-form">
      <ElFormItem label="导出场景">
        <ElTag>{{ sceneName }}</ElTag>
      </ElFormItem>
      <ElFormItem label="导出格式">
        <ElRadioGroup v-model="form.format">
          <ElRadio label="xlsx">XLSX</ElRadio>
          <ElRadio label="csv">CSV</ElRadio>
        </ElRadioGroup>
      </ElFormItem>
    </ElForm>

    <template #footer>
      <div class="dialog-footer">
        <ElButton @click="visible = false">取消</ElButton>
        <ElButton
          v-if="!confirmPermission || hasAuth(confirmPermission)"
          type="primary"
          :loading="submitting"
          @click="submit"
        >
          创建导出任务
        </ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
  import { computed, reactive, ref, watch } from 'vue'
  import { ElMessage } from 'element-plus'
  import { ExportTaskService } from '@/api/modules'
  import { useAuth } from '@/composables/useAuth'
  import { getExportTaskSceneName } from '@/config/constants'
  import type { CreateExportTaskResponse, ExportTaskFormat, ExportTaskScene } from '@/types/api'

  const props = withDefaults(
    defineProps<{
      modelValue: boolean
      scene: ExportTaskScene
      query?: Record<string, unknown>
      defaultFormat?: ExportTaskFormat
      title?: string
      description?: string
      confirmPermission?: string
    }>(),
    {
      query: () => ({}),
      defaultFormat: 'xlsx',
      title: '创建导出任务',
      description: '导出规则基于列表中的检索条件全量导出，不仅导出当前分页数据。'
    }
  )

  const emit = defineEmits<{
    (e: 'update:modelValue', value: boolean): void
    (e: 'success', value: CreateExportTaskResponse): void
  }>()

  const { hasAuth } = useAuth()
  const submitting = ref(false)
  const form = reactive({
    format: props.defaultFormat
  })

  const visible = computed({
    get: () => props.modelValue,
    set: (value: boolean) => emit('update:modelValue', value)
  })

  const sceneName = computed(() => getExportTaskSceneName(props.scene))

  watch(
    () => props.modelValue,
    (opened) => {
      if (opened) {
        form.format = props.defaultFormat
      }
    }
  )

  const getNormalizedQuery = () => {
    const query: Record<string, unknown> = {}

    Object.entries(props.query || {}).forEach(([key, value]) => {
      if (value === undefined || value === null || value === '') return
      if (Array.isArray(value) && value.length === 0) return
      query[key] = value
    })

    return query
  }

  const submit = async () => {
    if (props.confirmPermission && !hasAuth(props.confirmPermission)) {
      ElMessage.warning('您没有创建导出任务的权限')
      return
    }

    submitting.value = true
    try {
      const res = await ExportTaskService.createExportTask({
        scene: props.scene,
        format: form.format,
        query: getNormalizedQuery()
      })

      if (res.code === 0) {
        ElMessage.success(res.data?.message || '导出任务已创建')
        if (res.data?.task_id) {
          localStorage.setItem(`export-task-active:${props.scene}`, String(res.data.task_id))
        }
        emit('success', res.data)
        visible.value = false
      } else {
        ElMessage.error(res.msg || '创建导出任务失败')
      }
    } catch (error) {
      console.error('创建导出任务失败:', error)
      ElMessage.error('创建导出任务失败')
    } finally {
      submitting.value = false
    }
  }
</script>

<style scoped lang="scss">
  .export-rule-alert {
    margin-bottom: 18px;
  }

  .export-task-form {
    padding-top: 4px;
  }
</style>
