<template>
  <MyLayout>
    <el-card v-show="showQuery" class="my-query-box mt8" shadow="never" :body-style="{ paddingBottom: '0' }">
      <el-form :inline="true" label-width="auto" @submit.stop.prevent>
        <el-form-item label="关键词">
          <el-input v-model="searchForm.keyWord" placeholder="培养基名称" @keyup.enter="loadData" />
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker
            v-model="searchForm.stDate"
            type="datetime"
            placeholder="选择开始时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
            v-model="searchForm.edDate"
            type="datetime"
            placeholder="选择结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="ele-Search" @click="loadData">查询</el-button>
          <el-button type="primary" icon="ele-Plus" @click="handleAdd" v-permission="'api:admin:item-def-basic-medium:add'">新增</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="my-fill mt8" shadow="never">
      <div class="my-tools-box mb8 my-flex my-flex-between">
        <div>
        </div>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        border
      >
        <el-table-column prop="mediumName" label="培养基名称" min-width="300" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="200" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status ? 'success' : 'danger'">
              {{ row.status ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdTime" label="创建时间" width="200" show-overflow-tooltip>
          <template #default="{ row }">
            {{ formatDateTime(row.createdTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="modifiedTime" label="修改时间" width="200" show-overflow-tooltip>
          <template #default="{ row }">
            {{ formatDateTime(row.modifiedTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right" header-align="center" align="center">
          <template #default="{ row }">
            <el-button type="primary" icon="ele-EditPen" size="small" text @click="handleEdit(row)" v-permission="'api:admin:item-def-basic-medium:get'">编辑</el-button>
            <el-button
              type="danger"
              icon="ele-Delete"
              size="small"
              text
              @click="handleDelete(row)"
              v-permission="'api:admin:item-def-basic-medium:soft-delete'"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="my-flex my-flex-end" style="margin-top: 10px">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          size="small"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </el-card>

    <basic-liquid-form
      v-model:visible="formVisible"
      :form-data="formData"
      @success="handleSuccess"
    />
  </MyLayout>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ItemDefBasicMediumApi } from '/@/api/admin/item-def-basic-medium'
import type { BasicMediumDto } from '/@/types/data-contracts'
import MyLayout from '/@/components/my-layout/index.vue'
import BasicLiquidForm from './components/BasicLiquidForm.vue'

const api = new ItemDefBasicMediumApi()
const loading = ref(false)
const tableData = ref<BasicMediumDto[]>([])
const formVisible = ref(false)
const formData = ref<Partial<BasicMediumDto>>({})
const showQuery = ref(true)

const searchForm = reactive({
  keyWord: '',
  stDate: '',
  edDate: ''
})

const pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 10
})

// 格式化日期时间
const formatDateTime = (dateTime: string | undefined) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const res = await api.getPage({
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
      filter: searchForm
    })
    if (res.success) {
      tableData.value = res.data?.list || []
      pagination.total = res.data?.total || 0
    } else {
      ElMessage.error(res.msg || '加载数据失败')
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

const handleAdd = () => {
  formData.value = {}
  formVisible.value = true
}

const handleEdit = (row: BasicMediumDto) => {
  formData.value = { ...row }
  formVisible.value = true
}

const handleDelete = async (row: BasicMediumDto) => {
  ElMessageBox.confirm('确定要删除该记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await api.softDelete({ id: row.id })
      if (res.success) {
        ElMessage.success('删除成功')
        loadData()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

const handleSuccess = () => {
  formVisible.value = false
  loadData()
}

const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  loadData()
}

const handleCurrentChange = (val: number) => {
  pagination.current = val
  loadData()
}

onMounted(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
.my-query-box {
  :deep(.el-form-item) {
    margin-bottom: 16px;
  }
}

.my-fill {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.my-tools-box {
  margin-bottom: 16px;
}

.my-flex {
  display: flex;
}

.my-flex-between {
  justify-content: space-between;
}

.my-flex-end {
  justify-content: flex-end;
}

.mt8 {
  margin-top: 8px;
}

.mb8 {
  margin-bottom: 8px;
}
</style>
