<template>
  <div class="dlt-container">
    <el-card class="filter-card">
      <template #header>
        <div class="card-header">
          <span>查询条件</span>
          <el-button type="primary" @click="handleImport">导入数据</el-button>
        </div>
      </template>
      <el-form :inline="true" :model="queryForm" class="filter-form">
        <el-form-item label="期号">
          <el-input v-model="queryForm.issue" placeholder="请输入期号"></el-input>
        </el-form-item>
        <el-form-item label="开奖日期">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" @click="handleExport">导出</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>开奖记录</span>
          <el-button type="primary" @click="handleAdd">添加记录</el-button>
        </div>
      </template>
      <el-table :data="tableData" style="width: 100%" v-loading="loading">
        <el-table-column prop="issue" label="期号" width="120"></el-table-column>
        <el-table-column prop="open_time" label="开奖日期" width="120"></el-table-column>
        <el-table-column label="开奖号码">
          <template #default="{ row }">
            <div class="lottery-numbers">
              <span v-for="i in 5" :key="i" class="front-ball">{{ row[`front_ball_${i}`] }}</span>
              <span v-for="i in 2" :key="i" class="back-ball">{{ row[`back_ball_${i}`] }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          :current-page="currentPage.value"
          :page-size="pageSize.value"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加记录' : '编辑记录'"
      width="500px"
    >
      <el-form :model="form" label-width="100px">
        <el-form-item label="期号">
          <el-input v-model="form.issue"></el-input>
        </el-form-item>
        <el-form-item label="开奖日期">
          <el-date-picker
            v-model="form.open_time"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="前区号码">
          <el-input-number
            v-for="i in 5"
            :key="i"
            v-model="form[`front_ball_${i}`]"
            :min="1"
            :max="35"
            :controls="false"
            class="number-input"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="后区号码">
          <el-input-number
            v-for="i in 2"
            :key="i"
            v-model="form[`back_ball_${i}`]"
            :min="1"
            :max="12"
            :controls="false"
            class="number-input"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog
      v-model="importDialogVisible"
      title="导入数据"
      width="400px"
    >
      <el-upload
        class="upload-demo"
        drag
        action="#"
        :auto-upload="false"
        :on-change="handleFileChange"
        accept=".json"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            只能上传json文件
          </div>
        </template>
      </el-upload>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="importDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleImportSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import { lotteryApi } from '../api/lottery'
import dayjs from 'dayjs'

// 查询表单
const queryForm = reactive({
  issue: '',
  start_date: '',
  end_date: ''
})

// 日期范围
const dateRange = ref([])

// 表格数据
const tableData = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 对话框
const dialogVisible = ref(false)
const dialogType = ref('add')
const form = reactive({
  issue: '',
  open_time: '',
  front_ball_1: 1,
  front_ball_2: 1,
  front_ball_3: 1,
  front_ball_4: 1,
  front_ball_5: 1,
  back_ball_1: 1,
  back_ball_2: 1
})

// 导入对话框
const importDialogVisible = ref(false)
const importFile = ref(null)

// 查询数据
const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      ...queryForm,
      page: currentPage.value,
      page_size: pageSize.value
    }
    const response = await lotteryApi.getDLTLotteries(params)
    tableData.value = response.data
    total.value = response.headers['x-total-count']
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 监听日期范围变化
watch(dateRange, (val) => {
  if (val) {
    queryForm.start_date = val[0]
    queryForm.end_date = val[1]
  } else {
    queryForm.start_date = ''
    queryForm.end_date = ''
  }
})

// 查询
const handleQuery = () => {
  currentPage.value = 1
  fetchData()
}

// 重置
const handleReset = () => {
  queryForm.issue = ''
  dateRange.value = []
  handleQuery()
}

// 导出
const handleExport = () => {
  // TODO: 实现导出功能
}

// 添加记录
const handleAdd = () => {
  dialogType.value = 'add'
  Object.keys(form).forEach(key => {
    form[key] = key.includes('ball') ? 1 : ''
  })
  dialogVisible.value = true
}

// 编辑记录
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.keys(form).forEach(key => {
    form[key] = row[key]
  })
  dialogVisible.value = true
}

// 删除记录
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除这条记录吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      // TODO: 实现删除功能
      ElMessage.success('删除成功')
      fetchData()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

// 提交表单
const handleSubmit = async () => {
  try {
    if (dialogType.value === 'add') {
      await lotteryApi.createDLTLottery(form)
      ElMessage.success('添加成功')
    } else {
      // TODO: 实现编辑功能
      ElMessage.success('编辑成功')
    }
    dialogVisible.value = false
    fetchData()
  } catch (error) {
    ElMessage.error(dialogType.value === 'add' ? '添加失败' : '编辑失败')
  }
}

// 导入数据
const handleImport = () => {
  importDialogVisible.value = true
}

// 文件变化
const handleFileChange = (file) => {
  importFile.value = file.raw
}

// 提交导入
const handleImportSubmit = async () => {
  if (!importFile.value) {
    ElMessage.warning('请选择文件')
    return
  }
  try {
    await lotteryApi.importDLTData(importFile.value)
    ElMessage.success('导入成功')
    importDialogVisible.value = false
    fetchData()
  } catch (error) {
    ElMessage.error('导入失败')
  }
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

// 初始化
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.dlt-container {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.lottery-numbers {
  display: flex;
  gap: 10px;
}

.front-ball,
.back-ball {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: bold;
}

.front-ball {
  background-color: #f56c6c;
}

.back-ball {
  background-color: #409eff;
}

.number-input {
  width: 60px;
  margin-right: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.upload-demo {
  width: 100%;
}
</style> 