<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="800px" style="height: 60vh">
    <div class="form-header">
      <el-button
        v-no-more-click
        type="danger"
        plain
        pageSize="small"
        :disabled="!hasSelection"
        @click="handleDeleteFaceOrFinger"
        v-hasPermi="['system:user:delete']"
      >
        <Icon icon="ep:delete" />删除
      </el-button>
    </div>

    <el-table
      :data="tableData"
      height="450"
      @selection-change="handleSelectionChange"
      v-loading="formLoading"
      border
      stripe
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="序号" width="80" align="center" prop="orderNum"/>
      <el-table-column
        :label="dialogTitle === '人员指纹数据' ? '指纹' : '人脸'"
        align="center"
        prop="imageUrl"
      >
        <template #default="{ row }">
          <div class="img-box">
            <el-image
              style="width: 60px; height: 60px;"
              :preview-teleported="true"
              class="images"
              :hide-on-click-modal="true"
              :src="row.imageUrl"
              :zoom-rate="1.2"
              :preview-src-list="[row.imageUrl]"
              :initial-index="1"
              fit="cover"
            />
            <el-icon class="eye-icon"><ZoomIn /></el-icon>
          </div>
        </template>
      </el-table-column>

      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
        :formatter="dateFormatter"
      />

      <el-table-column
        label="操作"
        align="center"
        width="120"
        class-name="small-padding fixed-width"
      >
        <template #default="{ row }">
          <el-button
            v-no-more-click
            pageSize="small"
            type="text"
            icon="Delete"
            @click="handleDeleteFaceOrFinger(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>

    </el-table>
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getFaceOrFingerList"
    />
  </Dialog>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue'
import { ZoomIn } from '@element-plus/icons-vue'
import { ElMessageBox } from 'element-plus'
import { dateFormatter } from '@/utils/formatTime'
import { getUserType, deleteUserFaceOrFinger } from '@/api/system/user'

defineOptions({ name: 'FaceOrFingerForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

// 定义接口类型
interface CharacteristicData {
  pageNo: number
  pageSize: number
  userId: number
  type: string
}

interface CharacteristicResponse {
  data: {
    records: CharacteristicItem[]
    total: number
  }
}

interface CharacteristicItem {
  id: number
  imageUrl: string
  userId: number
  type: string
  createTime: string
  [key: string]: any
}

interface UserRow {
  userId: number
  [key: string]: any
}

// 定义事件
const emit = defineEmits(['success'])

// 响应式数据
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中
const tableData = ref<CharacteristicItem[]>([])
const selectedRows = ref<CharacteristicItem[]>([])
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
})
const userId = ref<number>()
const userType = ref<string>()

// 计算属性
const hasSelection = computed(() => selectedRows.value.length > 0)

/** 打开弹窗 */
const open = async (type: string, id?: number,row?:any) => {
  dialogVisible.value = true

  if (type === 'finger') {
    dialogTitle.value = '人员指纹数据'
  } else if (type === 'face') {
    dialogTitle.value = '人员面部数据'
  }

  userId.value = row.id
  userType.value = type === 'finger' ? '1' : '2'

  // 重置分页
  queryParams.pageNo = 1
  total.value = 0

  await getFaceOrFingerList()
}

// 获取指纹或人脸列表
const getFaceOrFingerList = async () => {
  if (!userId.value || !userType.value) return

  formLoading.value = true
  try {
    const data: CharacteristicData = {
      pageNo: queryParams.pageNo,
      pageSize: queryParams.pageSize,
      userId: userId.value,
      type: userType.value
    }

    const response: CharacteristicResponse = await getUserType(data)
    tableData.value = response.list
    total.value = response.total
  } catch (error) {
    console.error('获取数据失败:', error)
    message.error('获取数据失败')
  } finally {
    formLoading.value = false
  }
}

// 选择变化处理
const handleSelectionChange = (selection: CharacteristicItem[]) => {
  selectedRows.value = selection
}

// 删除指纹或人脸
const handleDeleteFaceOrFinger = async (row?: CharacteristicItem) => {
  const itemsToDelete = row ? [row] : selectedRows.value

  if (itemsToDelete.length === 0) {
    message.warning('请选择要删除的数据')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${itemsToDelete.length} 条数据吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 执行删除操作
    const deletePromises = itemsToDelete.map(item =>
      deleteUserFaceOrFinger(item.id)
    )

    await Promise.all(deletePromises)

    message.success(t('common.delSuccess'))
    await getFaceOrFingerList() // 刷新列表
    emit('success') // 通知父组件刷新
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      message.error('删除失败')
    }
  }
}


// 暴露方法给父组件
defineExpose({ open })
</script>

<style scoped lang="scss">
.form-header {
  margin-bottom: 16px;
  display: flex;
  justify-content: flex-end;
}

.img-box {
  position: relative;
  display: inline-block;

  .eye-icon {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    color: #fff;
    font-pageSize: 16px;
    opacity: 0;
    transition: opacity 0.3s;
    cursor: pointer;
    background: rgba(0, 0, 0, 0.5);
    border-radius: 50%;
    padding: 4px;
  }

  &:hover .eye-icon {
    opacity: 1;
  }
}

.images {
  border-radius: 4px;
  border: 1px solid #dcdfe6;
}
</style>
