<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { reportExportApi } from '@/api/report.js'

// ─── State ────────────────────────────────────────────────────────────────────

const tableData = ref([])
const total = ref(0)
const loading = ref(false)
const dialogVisible = ref(false)
const submitLoading = ref(false)

const searchForm = reactive({ type: '', status: '' })
const pagination = reactive({ page: 1, per_page: 20 })

const formRef = ref(null)
const form = reactive({ name: '', type: '', params: '' })
const formRules = {
  name: [{ required: true, message: '请输入报表名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择报表类型', trigger: 'change' }]
}

const typeOptions = [
  { label: '经营概览', value: 'overview' },
  { label: '营收报表', value: 'revenue' },
  { label: '入住率报表', value: 'occupancy' },
  { label: 'CRM转化报表', value: 'crm' }
]

const statusMap = { 0: '生成中', 1: '已完成', 2: '失败' }
const statusType = { 0: 'warning', 1: 'success', 2: 'danger' }

// ─── Methods ──────────────────────────────────────────────────────────────────

async function fetchList() {
  loading.value = true
  try {
    const res = await reportExportApi.getList({ ...searchForm, ...pagination })
    tableData.value = res.data?.list || res.data?.data || []
    total.value = res.data?.total || 0
  } finally { loading.value = false }
}

function handleSearch() { pagination.page = 1; fetchList() }
function handleReset() { Object.assign(searchForm, { type: '', status: '' }); handleSearch() }

function handleAdd() {
  Object.assign(form, { name: '', type: '', params: '' })
  dialogVisible.value = true
}

async function handleSubmit() {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    submitLoading.value = true
    try {
      const payload = { ...form }
      if (payload.params) {
        try { payload.params = JSON.parse(payload.params) } catch { /* send as string */ }
      }
      await reportExportApi.create(payload)
      ElMessage.success('导出任务已创建')
      dialogVisible.value = false
      fetchList()
    } finally { submitLoading.value = false }
  })
}

function handleDownload(row) {
  if (row.file_path) {
    window.open(row.file_path, '_blank')
  }
}

function handlePageChange(val) { pagination.page = val; fetchList() }
function handleSizeChange(val) { pagination.per_page = val; pagination.page = 1; fetchList() }

onMounted(fetchList)
</script>

<template>
  <div class="p-6 space-y-4">
    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 flex items-center flex-wrap gap-3">
      <el-input v-model="searchForm.type" placeholder="报表类型" style="width: 160px" clearable @keydown.enter="handleSearch" />
      <el-select v-model="searchForm.status" placeholder="状态" clearable style="width: 130px">
        <el-option v-for="(v, k) in statusMap" :key="k" :label="v" :value="Number(k)" />
      </el-select>
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button @click="handleReset">重置</el-button>
    </div>

    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm">
      <div class="flex items-center justify-between px-5 py-4 border-b border-gray-50">
        <div class="flex items-center gap-3">
          <span class="font-medium text-gray-700">导出记录列表</span>
        </div>
        <el-button type="primary" @click="handleAdd">新建导出</el-button>
      </div>
      <div class="px-2">
        <el-table v-loading="loading" :data="tableData" style="width: 100%">
          <el-table-column prop="name" label="报表名称" min-width="160" />
          <el-table-column prop="type" label="类型" min-width="120" />
          <el-table-column label="状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="statusType[row.status]" size="small">{{ statusMap[row.status] || '-' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作人" min-width="100">
            <template #default="{ row }">{{ row.operator?.name || '-' }}</template>
          </el-table-column>
          <el-table-column prop="created_at" label="创建时间" min-width="160" />
          <el-table-column label="操作" width="100" fixed="right" align="center">
            <template #default="{ row }">
              <el-button
                v-if="row.status === 1 && row.file_path"
                size="small"
                type="primary"
                text
                @click="handleDownload(row)"
              >下载</el-button>
              <span v-else class="text-muted">-</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="px-5 py-3 border-t border-gray-50">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.per_page"
          :total="total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          background
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>

    <!-- Create Dialog -->
    <el-dialog v-model="dialogVisible" title="新建导出" width="550px" destroy-on-close>
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="90px">
        <el-form-item label="报表名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入报表名称" />
        </el-form-item>
        <el-form-item label="报表类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择报表类型" style="width: 100%">
            <el-option
              v-for="opt in typeOptions"
              :key="opt.value"
              :label="opt.label"
              :value="opt.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="参数">
          <el-input
            v-model="form.params"
            type="textarea"
            :rows="4"
            placeholder="可选，JSON 格式参数"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.text-muted {
  color: var(--color-text-secondary);
  font-size: 13px;
}
</style>
