<template>
  <AppPage>
    <n-upload
      multiple
      directory-dnd
      v-model:file-list="fileList"
      action="api/v1/parse_finance_data/upload"
      :max="5"
      :headers="uploadHeaders"
      @finish="handleFinish"
      :show-remove-button="false"
      show-download-button
      :on-download="handleCustomDownload"
    >
      <n-upload-dragger>
        <div style="margin-bottom: 12px">
          <n-icon size="64" :depth="3">
            <icon-ic:outline-cloud-upload />
          </n-icon>
        </div>
        <n-text style="font-size: 16px">
          点击或者拖动文件到该区域来上传
        </n-text>
        <!-- <n-p depth="3" style="margin: 8px 0 0 0">
          网站不会保存上传的文件，处理完后会立即删除。
        </n-p> -->
      </n-upload-dragger>
    </n-upload>

    <!-- 配置弹窗 -->
    <!-- 替换 preset="dialog" 为普通 modal + footer -->
    <n-modal v-model:show="showConfigModal" :mask-closable="false" :closable="false">
      <n-spin :show="showLoading">
        <n-card
          title="配置解析参数"
          style="width: 500px"
          :bordered="false"
          size="huge"
          role="dialog"
          aria-modal="true"
        >
          <n-form ref="formRef" :model="configForm" :rules="rules" label-placement="left" :label-width="85">
            <!-- 文件名 -->
            <n-form-item label="文件名:" path="filename">
              <n-input v-model:value="configForm.filename" disabled />
            </n-form-item>
            <n-form-item label="工作表:" path="sheet">
              <n-select
                v-model:value="configForm.sheet"
                :options="sheetOptions"
                @update:value="onSheetChange"
              />
            </n-form-item>
            <n-form-item label="解析列:" path="header">
              <n-select
                v-model:value="configForm.header"
                :options="headerOptions"
                :disabled="!configForm.sheet"
              />
            </n-form-item>
            <n-form-item label="解析方式:" path="parse_type">
              <n-select
                v-model:value="configForm.parse_type"
                :options="parseTypeOptions"
                :disabled="!configForm.sheet"
              />
            </n-form-item>
          </n-form>
          <template #footer>
            <div style="text-align: right">
              <n-button @click="closeModal">取消</n-button>
              <n-button type="primary" @click="onConfirmConfig" style="margin-left: 12px">确认</n-button>
            </div>
          </template>
        </n-card>
      </n-spin>
    </n-modal>
  </AppPage>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { useMessage } from 'naive-ui'
import type { UploadFileInfo } from 'naive-ui'
import { getToken } from '@/utils'
import { parse_finance_data, get_task_list } from '@/api/finance_parse'
import { downloadBlob } from '@/utils'

const message = useMessage()
const formRef = ref(null)

// 上传 headers
const uploadHeaders = computed(() => ({
  token: getToken(),
}))

// 弹窗控制
const showConfigModal = ref(false)
const showLoading = ref(false)

// 存储上传返回的解析数据
const currentFileData = ref<Record<string, string[]> | null>(null)

// 表单数据
const configForm = reactive({
  filename: '',
  sheet: null as string | null,
  header: null as string | null,
  parse_type: '',
})

// 上传文件列表
const fileList = ref<UploadFileInfo[]>([])
const fileMap = ref<Record<string, any>>({})

const parseTypeOptions = ref([
  { label: '横向排列：尺寸1、尺寸2、、', value: 'horizontal' },
  { label: '纵向排列：多尺寸自动填充或者复制新增行', value: 'vertical' },
])

const rules = reactive({
  filename: [{ required: true, message: '请输入文件名', trigger: 'blur' }],
  sheet: [{ required: true, message: '请选择工作表', trigger: 'change' }],
  header: [{ required: true, message: '请选择表头列', trigger: 'change' }],
  parse_type: [{ required: true, message: '请选择解析方式', trigger: 'change' }],
})

// 下拉选项
const sheetOptions = computed(() =>
  currentFileData.value
    ? Object.entries(currentFileData.value).filter(([name, headers]) => headers.length > 0).map(([name, headers]) => ({ label: name, value: name }))
    : []
)

const headerOptions = computed(() =>
  configForm.sheet && currentFileData.value?.[configForm.sheet]
    ? currentFileData.value[configForm.sheet].map(col => ({
        label: col.trim(),
        value: col.trim(),
      }))
    : []
)

// 上传完成
function handleFinish({ file, event }: { file: UploadFileInfo; event?: ProgressEvent }) {
  if (!event) return

  try {
    const xhr = event.target as XMLHttpRequest
    const response = JSON.parse(xhr.response)

    if (response.code !== 200) {
      message.error(response.msg || '上传失败')
      return
    }

    // 保存返回的 data（{ Sheet1: ["col1", "col2", ...] }）
    currentFileData.value = response.data.data
    configForm.filename = response.data.filename
    configForm.sheet = sheetOptions.value[0]?.value || null
    configForm.header = headerOptions.value?.find(item => item.value.endsWith('文件名'))?.value || ''
    configForm.parse_type = ''

    fileMap.value[file.id] = {
      currentFileData: currentFileData.value,
      filename: configForm.filename,
    }

    showConfigModal.value = true
  } catch (err) {
    console.error('Parse response error:', err)
    message.error('解析响应失败')
  }
}

const handleCustomDownload = (file: UploadFileInfo) => {
  console.log('custom download', file.id)
  const fileData = fileMap.value[file.id]
  currentFileData.value = fileData.currentFileData
  configForm.filename = fileData.filename
  configForm.sheet = sheetOptions.value[0]?.value || null
  configForm.header = headerOptions.value?.find(item => item.value.endsWith('文件名'))?.value || ''
  configForm.parse_type = ''
  showConfigModal.value = true
}

// 切换 sheet 时重置 header
function onSheetChange() {
  configForm.header = null
}

// 确认配置
function closeModal() {
  showConfigModal.value = false
  showLoading.value = false
}

// 确认配置
async function onConfirmConfig() {
  try {
    await formRef.value?.validate() // 使用 async/await 更简洁
    // ✅ 校验通过
    console.log('用户配置:', {
      filename: configForm.filename,
      sheet: configForm.sheet,
      header: configForm.header,
      parse_type: configForm.parse_type,
    })
    message.success('正在解析，请稍后...')
    showLoading.value = true

    // 调用解析接口
    const { blob, filename } = await parse_finance_data({
      filename: configForm.filename,
      sheet: configForm.sheet,
      header: configForm.header,
      parse_type: configForm.parse_type,
    })

    console.log('下载文件名:', filename)
    // 下载
    downloadBlob(blob, filename)
    message.success('解析完成')
    closeModal()
  } catch (error: any) {
    // 处理错误（注意：错误响应也可能是 blob！）
    if (error.response?.data instanceof Blob) {
      const errorText = await error.response.data.text()
      try {
        const errJson = JSON.parse(errorText)
        message.error(errJson.msg || '解析失败')
      } catch {
        message.error('服务器返回错误：' + errorText)
      }
    } else {
      message.error('网络错误')
    }
  }
    

}

</script>