<script setup>
import { ArrowLeft } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { createPackage, getAllDataFiles, getPkgCategoryTree, previewPackage } from '@/api/packageManagement'
import DataCurve from '@/views/DataManagement/components/DataCurve.vue'

const emit = defineEmits(['cancel', 'saved'])

// ── data files ────────────────────────────────────────────────────────────────
const allFiles = ref([])
const selectedFileIds = ref([])
const fileTableRef = ref(null)
const fileSearchText = ref('')

const filteredFiles = computed(() => {
  const kw = fileSearchText.value.trim().toLowerCase()
  if (!kw) return allFiles.value
  return allFiles.value.filter(
    (f) =>
      f.filename.toLowerCase().includes(kw) ||
      (f.category_name || '').toLowerCase().includes(kw),
  )
})

const handleFileSelectionChange = (rows) => {
  selectedFileIds.value = rows.map((r) => r.id)
}

// ── categories ────────────────────────────────────────────────────────────────
const categoryOptions = ref([])

const loadCategories = async () => {
  const data = await getPkgCategoryTree()
  const source = Array.isArray(data) ? data : []
  categoryOptions.value = source
    .filter((item) => String(item?.id) !== 'all')
    .map((item) => ({ label: item.name, value: String(item.id) }))
}

// ── form ──────────────────────────────────────────────────────────────────────
const form = reactive({
  categoryId: '',
  name: '',
  remark: '',
})

// ── preview ───────────────────────────────────────────────────────────────────
const previewLoading = ref(false)
const previewRecords = ref([])
const previewTotal = ref(0)
const previewMode = ref('table')
let previewDebounceTimer = null

const triggerPreview = () => {
  clearTimeout(previewDebounceTimer)
  if (!selectedFileIds.value.length) {
    previewRecords.value = []
    previewTotal.value = 0
    return
  }
  previewDebounceTimer = setTimeout(async () => {
    previewLoading.value = true
    try {
      const result = await previewPackage({ file_ids: selectedFileIds.value }, { limit: 300 })
      previewRecords.value = result.records
      previewTotal.value = result.count
    } finally {
      previewLoading.value = false
    }
  }, 600)
}

watch(selectedFileIds, triggerPreview, { deep: true })

// ── save ──────────────────────────────────────────────────────────────────────
const saving = ref(false)

const handleGenerate = async () => {
  if (!form.name.trim()) {
    ElMessage.warning('请输入数据包名称')
    return
  }
  if (!selectedFileIds.value.length) {
    ElMessage.warning('请至少选择一个数据文件')
    return
  }

  saving.value = true
  try {
    await createPackage({
      name: form.name.trim(),
      category_id: form.categoryId || null,
      remark: form.remark.trim() || null,
      file_ids: selectedFileIds.value,
    })
    ElMessage.success('数据包创建成功')
    emit('saved')
  } finally {
    saving.value = false
  }
}

// ── init ──────────────────────────────────────────────────────────────────────
onMounted(async () => {
  const [filesData] = await Promise.all([getAllDataFiles(), loadCategories()])
  allFiles.value = filesData
})
</script>

<template>
  <div class="add-pkg-page">
    <!-- header -->
    <div class="add-pkg-header">
      <el-button :icon="ArrowLeft" plain @click="emit('cancel')">返回列表</el-button>
      <span class="add-pkg-title">新增数据包</span>
    </div>

    <!-- top: file selection -->
    <div class="section-card file-section">
      <div class="section-title">
        选择数据文件
        <span class="section-hint">已选 {{ selectedFileIds.length }} 个文件</span>
      </div>
      <div class="file-search-bar">
        <el-input
          v-model="fileSearchText"
          placeholder="按文件名或分类搜索"
          clearable
          style="width: 280px"
        />
      </div>
      <el-table
        ref="fileTableRef"
        :data="filteredFiles"
        border
        stripe
        height="220"
        @selection-change="handleFileSelectionChange"
      >
        <el-table-column type="selection" width="46" />
        <el-table-column prop="filename" label="文件名" min-width="200" show-overflow-tooltip />
        <el-table-column prop="category_name" label="所属分类" width="130" show-overflow-tooltip />
        <el-table-column prop="data_count" label="数据量" width="80" align="center" />
        <el-table-column prop="uploaded_at" label="上传时间" width="160" />
      </el-table>
    </div>

    <!-- bottom: form + preview -->
    <div class="section-bottom">
      <!-- left: form -->
      <div class="section-card form-section">
        <div class="section-title">生成数据包</div>
        <el-form label-position="top" class="pkg-form">
          <el-form-item label="数据包分类">
            <el-select v-model="form.categoryId" placeholder="请选择（可选）" clearable style="width: 100%">
              <el-option
                v-for="item in categoryOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="数据包名称" required>
            <el-input v-model="form.name" maxlength="100" show-word-limit placeholder="请输入数据包名称" />
          </el-form-item>
          <el-form-item label="备注">
            <el-input
              v-model="form.remark"
              type="textarea"
              :rows="3"
              maxlength="500"
              show-word-limit
              placeholder="备注（可选）"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              :loading="saving"
              style="width: 100%"
              @click="handleGenerate"
            >
              生成数据包
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- right: preview -->
      <div class="section-card preview-section">
        <div class="section-title">
          生成结果预览
          <span v-if="previewTotal" class="section-hint">共 {{ previewTotal }} 条（展示前 300 条）</span>
          <el-radio-group v-model="previewMode" size="small" style="margin-left: auto">
            <el-radio-button value="table">表格</el-radio-button>
            <el-radio-button value="curve">曲线</el-radio-button>
          </el-radio-group>
        </div>

        <div class="preview-content" v-loading="previewLoading">
          <el-empty
            v-if="!previewLoading && !previewRecords.length"
            description="请在上方选择数据文件，预览将自动更新"
            :image-size="80"
          />

          <el-table
            v-else-if="previewMode === 'table'"
            :data="previewRecords"
            border
            stripe
            height="100%"
          >
            <el-table-column prop="time" label="时间" min-width="140" />
            <el-table-column prop="current" label="电流" min-width="80" />
            <el-table-column prop="voltage" label="电压" min-width="80" />
            <el-table-column prop="set_temperature" label="设定温度" min-width="100" />
            <el-table-column prop="actual_temperature" label="实际温度" min-width="100" />
          </el-table>

          <DataCurve v-else :records="previewRecords" />
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.add-pkg-page {
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 0;
  overflow: hidden;
}

.add-pkg-header {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 12px 20px;
  background: rgba(255, 255, 255, 0.9);
  border-bottom: 1px solid #e8edf3;
  flex-shrink: 0;
}

.add-pkg-title {
  font-size: 16px;
  font-weight: 600;
  color: #0f172a;
}

.section-card {
  background: #fff;
  border: 1px solid #e8edf3;
  border-radius: 8px;
  padding: 16px;
  overflow: hidden;
}

.section-title {
  font-size: 14px;
  font-weight: 600;
  color: #0f172a;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.section-hint {
  font-size: 12px;
  font-weight: 400;
  color: #64748b;
}

.file-search-bar {
  margin-bottom: 10px;
}

.file-section {
  flex-shrink: 0;
  margin: 12px 12px 0;
}

.section-bottom {
  flex: 1;
  display: flex;
  gap: 12px;
  padding: 12px;
  overflow: hidden;
  min-height: 0;
}

.form-section {
  width: 320px;
  flex-shrink: 0;
  overflow-y: auto;
}

.preview-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-width: 0;
  overflow: hidden;

  .section-title {
    flex-shrink: 0;
  }
}

.preview-content {
  flex: 1;
  overflow: hidden;
  min-height: 0;
}

.pkg-form {
  :deep(.el-form-item) {
    margin-bottom: 16px;
  }
}
</style>
