<template>
  <div class="page-container">
    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :model="searchForm" inline data-id="search-form">
        <el-form-item :label="t('机器ID')">
          <el-input
            v-model.trim="searchForm.machineId"
            placeholder="请输入机器ID"
            clearable
            data-id="search-machine-id"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item :label="t('名称')">
          <el-input
            v-model.trim="searchForm.name"
            placeholder="请输入名称"
            clearable
            data-id="search-name"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item :label="t('启用状态')">
          <el-select v-model="searchForm.enabled" placeholder="全部" clearable data-id="search-enabled">
            <el-option label="全部" value="" />
            <el-option label="已启用" :value="true" />
            <el-option label="已禁用" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item :label="t('创建时间')">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            data-id="search-date-range"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" data-id="btn-search" @click="handleSearch">
            {{ t('查询') }}
          </el-button>
          <el-button :icon="RefreshRight" data-id="btn-reset" @click="handleReset">{{ t('重置') }}</el-button>
          <el-button type="primary" :icon="Plus" data-id="btn-add-machine" @click="handleAdd">
            {{ t('新增') }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 批量操作栏 -->
    <div v-if="selectedRows.length > 0" class="batch-actions">
      <span class="batch-info">{{ t('已选择') }} {{ selectedRows.length }} {{ t('项') }}</span>
      <el-button type="danger" :icon="Delete" :loading="deleteLoading" @click="handleBatchDelete">
        {{ t('批量删除') }}
      </el-button>
      <el-button @click="clearSelection">{{ t('取消选择') }}</el-button>
    </div>

    <!-- 数据表格 -->
    <div class="table-wrapper">
      <el-table
        ref="tableRef"
        v-loading="loading"
        :data="sortedList"
        stripe
        size="default"
        data-id="machine-table"
        height="100%"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column type="index" :label="t('序号')" width="60" align="center" />
        <el-table-column
          prop="machineId"
          :label="t('机器ID')"
          min-width="120"
          sortable="custom"
          show-overflow-tooltip
        />
        <el-table-column prop="name" :label="t('名称')" min-width="120" sortable="custom" show-overflow-tooltip>
          <template #default="{ row }">
            <el-link type="primary" :data-id="`link-edit-${row.machineId}`" @click="handleEdit(row)">
              {{ row.name }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="location" :label="t('位置')" min-width="120" show-overflow-tooltip />
        <el-table-column prop="description" :label="t('描述')" min-width="150" show-overflow-tooltip />
        <el-table-column prop="cameraCount" :label="t('摄像头数')" sortable="custom" align="center">
          <template #default="{ row }">
            <el-tag type="info">{{ row.cameraCount || 0 }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="enabled" :label="t('启用')" sortable="custom" align="center">
          <template #default="{ row }">
            <el-tag :type="row.enabled ? 'success' : 'info'">
              {{ row.enabled ? t('是') : t('否') }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" :label="t('创建时间')" width="160" sortable="custom" align="center">
          <template #default="{ row }">
            {{ formatDateTime(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column :label="t('操作')" min-width="90" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link :icon="Edit" :data-id="`btn-edit-${row.machineId}`" @click="handleEdit(row)">
              {{ t('编辑') }}
            </el-button>
            <el-button
              type="danger"
              link
              :icon="Delete"
              :disabled="deleteLoading"
              :data-id="`btn-delete-${row.machineId}`"
              @click="handleDelete(row)"
            >
              {{ t('删除') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" destroy-on-close data-id="dialog-machine">
      <div class="form-container">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="auto" data-id="form-machine">
          <el-form-item :label="t('机器ID')" prop="machineId">
            <el-input
              v-model="form.machineId"
              placeholder="请输入机器ID"
              :disabled="isEdit"
              data-id="input-machine-id"
            />
          </el-form-item>
          <el-form-item :label="t('名称')" prop="name">
            <el-input v-model="form.name" placeholder="请输入名称" data-id="input-name" />
          </el-form-item>
          <el-form-item :label="t('位置')" prop="location">
            <el-input v-model="form.location" placeholder="请输入位置" data-id="input-location" />
          </el-form-item>
          <el-form-item :label="t('描述')" prop="description">
            <el-input
              v-model="form.description"
              type="textarea"
              :rows="3"
              placeholder="请输入描述"
              data-id="input-description"
            />
          </el-form-item>
          <el-form-item v-if="isEdit" :label="t('启用状态')">
            <el-switch v-model="form.enabled" data-id="switch-enabled" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button data-id="btn-cancel" @click="dialogVisible = false">{{ t('取消') }}</el-button>
        <el-button type="primary" :loading="submitLoading" data-id="btn-submit" @click="handleSubmit">
          {{ t('确定') }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules, type TableInstance } from 'element-plus'
import { Plus, Edit, Delete, Search, RefreshRight } from '@element-plus/icons-vue'
import { listMachines, addMachine, updateMachine, deleteMachine } from '@/api/machine'
import type { MachineDTO, MachineAddRequest, MachineUpdateRequest } from '@/types'
import dayjs from 'dayjs'
import { useI18n } from 'vue-i18n'

const { t } = useI18n({ useScope: 'global' })

// 格式化时间
function formatDateTime(dateStr: string | undefined): string {
  if (!dateStr) return '-'
  return dayjs(dateStr).format('YYYY-MM-DD HH:mm')
}

const loading = ref(false)
const submitLoading = ref(false)
const deleteLoading = ref(false)
const machineList = ref<MachineDTO[]>([])
const dialogVisible = ref(false)
const formRef = ref<FormInstance>()
const tableRef = ref<TableInstance>()

// 选中的行
const selectedRows = ref<MachineDTO[]>([])

// 排序状态
const sortState = reactive<{
  prop: string
  order: 'ascending' | 'descending' | null
}>({
  prop: '',
  order: null
})

// 搜索表单
const searchForm = reactive<{
  machineId: string
  name: string
  enabled: boolean | ''
  dateRange: [string, string] | null
}>({
  machineId: '',
  name: '',
  enabled: '',
  dateRange: null
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 过滤后的数据
const filteredList = computed(() => {
  return machineList.value.filter((item) => {
    // 机器ID过滤
    if (searchForm.machineId && !item.machineId.toLowerCase().includes(searchForm.machineId.toLowerCase())) {
      return false
    }
    // 名称过滤
    if (searchForm.name && !item.name.toLowerCase().includes(searchForm.name.toLowerCase())) {
      return false
    }
    // 启用状态过滤
    if (searchForm.enabled !== '' && item.enabled !== searchForm.enabled) {
      return false
    }
    // 时间范围过滤
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      const itemDate = item.createdAt ? item.createdAt.split('T')[0] : ''
      const [startDate, endDate] = searchForm.dateRange
      if (itemDate < startDate || itemDate > endDate) {
        return false
      }
    }
    return true
  })
})

// 排序后的数据（后端已分页，前端只做排序）
const sortedList = computed(() => {
  const list = [...machineList.value]
  if (sortState.prop && sortState.order) {
    list.sort((a, b) => {
      const aVal = a[sortState.prop as keyof MachineDTO]
      const bVal = b[sortState.prop as keyof MachineDTO]

      // 处理空值
      if (aVal == null && bVal == null) return 0
      if (aVal == null) return sortState.order === 'ascending' ? -1 : 1
      if (bVal == null) return sortState.order === 'ascending' ? 1 : -1

      // 比较
      let result = 0
      if (typeof aVal === 'number' && typeof bVal === 'number') {
        result = aVal - bVal
      } else if (typeof aVal === 'boolean' && typeof bVal === 'boolean') {
        result = aVal === bVal ? 0 : aVal ? 1 : -1
      } else {
        result = String(aVal).localeCompare(String(bVal))
      }

      return sortState.order === 'ascending' ? result : -result
    })
  }
  return list
})

const form = reactive<{
  id?: number
  machineId: string
  name: string
  location: string
  description: string
  enabled: boolean
}>({
  machineId: '',
  name: '',
  location: '',
  description: '',
  enabled: true
})

const isEdit = computed(() => !!form.id)
const dialogTitle = computed(() => (isEdit.value ? t('编辑机器') : t('新增机器')))

const rules: FormRules = {
  machineId: [{ required: true, message: t('请输入机器ID'), trigger: 'blur' }],
  name: [{ required: true, message: t('请输入名称'), trigger: 'blur' }]
}

async function getList() {
  loading.value = true
  try {
    // 构建查询参数
    const params: Record<string, any> = {
      page: currentPage.value,
      size: pageSize.value
    }
    // 搜索关键词（机器ID或名称）
    if (searchForm.machineId || searchForm.name) {
      params.keyword = searchForm.machineId || searchForm.name
    }
    // 启用状态过滤
    if (searchForm.enabled !== '') {
      params.enabled = searchForm.enabled
    }
    // 排序
    if (sortState.prop && sortState.order) {
      params.sortBy = sortState.prop
      params.sortDir = sortState.order === 'ascending' ? 'ASC' : 'DESC'
    }

    const res = await listMachines(params)
    if (res.success) {
      machineList.value = res.data.list
      total.value = res.data.total || 0
    }
  } finally {
    loading.value = false
  }
}

function handleSearch() {
  currentPage.value = 1 // 搜索时重置到第一页
  getList()
}

function handleReset() {
  searchForm.machineId = ''
  searchForm.name = ''
  searchForm.enabled = ''
  searchForm.dateRange = null
  currentPage.value = 1
  // 重置排序
  sortState.prop = ''
  sortState.order = null
  getList()
}

// 排序变化处理
function handleSortChange({ prop, order }: { prop: string; order: 'ascending' | 'descending' | null }) {
  sortState.prop = prop || ''
  sortState.order = order
  getList()
}

// 选择变化处理
function handleSelectionChange(rows: MachineDTO[]) {
  selectedRows.value = rows
}

// 清除选择
function clearSelection() {
  tableRef.value?.clearSelection()
}

// 批量删除
async function handleBatchDelete() {
  if (selectedRows.value.length === 0) return

  try {
    await ElMessageBox.confirm(`${t('确定要删除选中的')} ${selectedRows.value.length} ${t('台机器吗？')}`, t('提示'), {
      type: 'warning'
    })
    deleteLoading.value = true
    // 逐个删除
    const deletePromises = selectedRows.value.map((row) => deleteMachine(row.id))
    await Promise.all(deletePromises)
    ElMessage.success(`${t('成功删除')} ${selectedRows.value.length} ${t('台机器')}`)
    clearSelection()
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error(t('批量删除失败'), error)
      ElMessage.error(t('批量删除失败'))
    }
  } finally {
    deleteLoading.value = false
  }
}

function handleAdd() {
  Object.assign(form, {
    id: undefined,
    machineId: '',
    name: '',
    location: '',
    description: '',
    enabled: true
  })
  dialogVisible.value = true
}

function handleEdit(row: MachineDTO) {
  Object.assign(form, {
    id: row.id,
    machineId: row.machineId,
    name: row.name,
    location: row.location || '',
    description: row.description || '',
    enabled: row.enabled
  })
  dialogVisible.value = true
}

async function handleDelete(row: MachineDTO) {
  if (deleteLoading.value) return

  try {
    await ElMessageBox.confirm(`${t('确定要删除机器')} "${row.name}" ${t('吗？')}`, t('提示'), {
      type: 'warning'
    })
    deleteLoading.value = true
    const res = await deleteMachine(row.id)
    if (res.success) {
      ElMessage.success(t('删除成功'))
      getList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error(t('删除失败'), error)
    }
  } finally {
    deleteLoading.value = false
  }
}

async function handleSubmit() {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        if (isEdit.value) {
          const updateData: MachineUpdateRequest = {
            id: form.id!,
            name: form.name,
            location: form.location || undefined,
            description: form.description || undefined,
            enabled: form.enabled
          }
          const res = await updateMachine(updateData)
          if (res.success) {
            ElMessage.success(t('修改成功'))
            dialogVisible.value = false
            getList()
          }
        } else {
          const addData: MachineAddRequest = {
            machineId: form.machineId,
            name: form.name,
            location: form.location || undefined,
            description: form.description || undefined
          }
          const res = await addMachine(addData)
          if (res.success) {
            ElMessage.success(t('新增成功'))
            dialogVisible.value = false
            getList()
          }
        }
      } finally {
        submitLoading.value = false
      }
    }
  })
}

function handleSizeChange(val: number) {
  pageSize.value = val
  currentPage.value = 1
  getList()
}

function handleCurrentChange(val: number) {
  currentPage.value = val
  getList()
}

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

<style lang="scss" scoped>
.page-container {
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}

.form-container {
  padding-top: 18px;
}

// 批量操作栏
.batch-actions {
  flex-shrink: 0;
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
  padding: 12px 16px;
  background: #fef3c7;
  border: 1px solid #f59e0b;

  .batch-info {
    font-size: 14px;
    color: #92400e;
    font-weight: 500;
  }

  :deep(.el-button--danger) {
    background-color: #dc2626;
    border-color: #dc2626;

    &:hover {
      background-color: #ef4444;
      border-color: #ef4444;
    }
  }
}

.search-form {
  flex-shrink: 0;
  margin-bottom: 16px;
  padding: 16px 16px 4px 16px;
  background: #f5f7fa;

  :deep(.el-form-item) {
    margin-bottom: 12px;
    margin-right: 16px;
  }

  :deep(.el-input),
  :deep(.el-select) {
    width: 160px;
  }

  :deep(.el-date-editor--daterange) {
    width: 280px;

    .el-range-input {
      width: 90px;
    }

    .el-range-separator {
      width: 30px;
    }
  }

  // Indigo 主题按钮
  :deep(.el-button--primary) {
    background-color: #4f46e5;
    border-color: #4f46e5;

    &:hover,
    &:focus {
      background-color: #6366f1;
      border-color: #6366f1;
    }
  }
}

.table-wrapper {
  flex: 1;
  min-height: 0;
  overflow: hidden;
}

.pagination-container {
  flex-shrink: 0;
  display: flex;
  justify-content: flex-end;
  padding-top: 16px;

  // Indigo 主题分页
  :deep(.el-pagination) {
    .el-pager li.is-active {
      background-color: #4f46e5;
      color: #fff;
    }

    .el-pager li:not(.is-active):hover {
      color: #4f46e5;
    }

    .btn-prev:hover,
    .btn-next:hover {
      color: #4f46e5;
    }
  }
}

// 表格样式
:deep(.el-table) {
  // 斑马纹对比度
  --el-table-row-hover-bg-color: #f0f0ff;

  .el-table__row--striped td.el-table__cell {
    background-color: #f8f9fc;
  }

  // 表头样式
  .el-table__header th {
    background-color: #f5f7fa;
    color: #333;
    font-weight: 600;
  }

  // 链接颜色
  .el-link--primary {
    color: #4f46e5;

    &:hover {
      color: #6366f1;
    }
  }

  // 主要按钮颜色
  .el-button--primary.is-link {
    color: #4f46e5;

    &:hover {
      color: #6366f1;
    }
  }

  // 排序图标颜色
  .el-table__column-filter-trigger,
  .caret-wrapper {
    .sort-caret.ascending {
      border-bottom-color: #4f46e5;
    }

    .sort-caret.descending {
      border-top-color: #4f46e5;
    }
  }

  // Checkbox Indigo 主题
  .el-checkbox__input.is-checked .el-checkbox__inner {
    background-color: #4f46e5;
    border-color: #4f46e5;
  }

  .el-checkbox__input.is-indeterminate .el-checkbox__inner {
    background-color: #4f46e5;
    border-color: #4f46e5;
  }
}

// 弹窗 Indigo 主题
:deep(.el-dialog) {
  .el-dialog__header {
    border-bottom: 1px solid #e5e7eb;
    padding-bottom: 16px;
  }

  .el-dialog__footer {
    border-top: 1px solid #e5e7eb;
    padding-top: 16px;
  }

  .el-button--primary {
    background-color: #4f46e5;
    border-color: #4f46e5;

    &:hover,
    &:focus {
      background-color: #6366f1;
      border-color: #6366f1;
    }
  }

  // Switch Indigo 主题
  .el-switch.is-checked .el-switch__core {
    background-color: #4f46e5;
    border-color: #4f46e5;
  }
}
</style>
