<template>
  <div class="p-4">
    <h2 class="text-xl font-bold text-blue-400 mb-4">巡检日志管理</h2>
    
    <!-- 工具栏 -->
    <div class="flex justify-between items-center mb-4">
      <div class="flex gap-4">
        <el-button type="primary" @click="handleAddLog" icon="Plus">新增日志</el-button>
        <el-button @click="handleRefresh" icon="Refresh">刷新</el-button>
      </div>
      
      <!-- 搜索框 -->
      <el-input
        v-model="searchKeyword"
        placeholder="搜索日志信息"
        prefix-icon="Search"
        style="width: 240px"
        @input="handleSearch"
      />
    </div>
    
    <!-- 日志列表表格 -->
    <el-table
      v-loading="loading"
      :data="logList"
      style="width: 100%"
      @row-click="handleRowClick"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="CreateDate" label="记录日期时间" width="200" align="center" />
      <el-table-column prop="PersonNames" label="巡检人员" min-width="200" align="center">
        <template #default="scope">
          <div v-for="name in scope.row.PersonNames" :key="name" class="text-sm">
            {{ name }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="DeviceName" label="记录点位设备" min-width="200" />
      <el-table-column prop="ScheduleTitle" label="对应排班记录" min-width="200" />
      <el-table-column label="操作" width="150" align="center">
        <template #default="scope">
          <div class="flex gap-2 justify-center">
            <el-button
              size="small"
              @click="handleEdit(scope.row)"
              icon="Edit"
            >编辑</el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
              icon="Delete"
            >删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div class="flex justify-end mt-4">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 日志编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑巡检日志' : '新增巡检日志'"
      width="70%"
      max-width="900px"
      destroy-on-close
      @closed="handleClose"
    >
      <!-- 表单容器 -->
      <el-form
        ref="logFormRef"
        :model="logForm"
        label-width="120px"
        :rules="formRules"
      >
        <!-- 第一行：人员选择和日期时间 -->
        <div class="grid grid-cols-1 gap-4 mb-4">
          <el-form-item label="人员1" prop="UserID1">
            <el-select
              v-model="logForm.UserID1"
              placeholder="选择巡检人员"
              style="width: 100%"
            >
              <el-option
                v-for="user in userList"
                :key="user.value"
                :label="user.label"
                :value="user.value"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="人员2" prop="UserID2">
            <el-select
              v-model="logForm.UserID2"
              placeholder="选择巡检人员（可选）"
              style="width: 100%"
            >
              <el-option
                v-for="user in userList"
                :key="user.value"
                :label="user.label"
                :value="user.value"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="人员3" prop="UserID3">
            <el-select
              v-model="logForm.UserID3"
              placeholder="选择巡检人员（可选）"
              style="width: 100%"
            >
              <el-option
                v-for="user in userList"
                :key="user.value"
                :label="user.label"
                :value="user.value"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="记录日期时间" prop="CreateDate">
            <el-date-picker
              v-model="logForm.CreateDate"
              type="datetime"
              placeholder="选择日期时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
            />
          </el-form-item>
        </div>
        
        <!-- 第二行：设备和排班记录 -->
        <div class="grid grid-cols-1 gap-4">
          <el-form-item label="记录点位设备" prop="PointDeviceID">
            <el-select
              v-model="logForm.PointDeviceID"
              placeholder="选择点位设备"
              style="width: 100%"
            >
              <el-option
                v-for="device in deviceList"
                :key="device.value"
                :label="device.label"
                :value="device.value"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="对应排班记录" prop="PatrolScheduleID">
            <el-select
              v-model="logForm.PatrolScheduleID"
              placeholder="选择对应排班记录"
              style="width: 100%"
            >
              <el-option
                v-for="schedule in scheduleList"
                :key="schedule.value"
                :label="schedule.label"
                :value="schedule.value"
              />
            </el-select>
          </el-form-item>
        </div>
      </el-form>
      
      <!-- 对话框底部按钮 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
/**
 * 巡检日志管理组件
 * 用于管理巡检日志信息，包含人员、时间、设备和排班记录配置
 */
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 响应式数据
const loading = ref(false)
const logList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchKeyword = ref('')

// 编辑对话框相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const logFormRef = ref()
const logForm = reactive({
  UserID1: '',
  UserID2: '',
  UserID3: '',
  CreateDate: '',
  PointDeviceID: '',
  PatrolScheduleID: ''
})

// 表单验证规则
const formRules = {
  UserID1: [
    { required: true, message: '请选择第一位巡检人员', trigger: 'blur' }
  ],
  CreateDate: [
    { required: true, message: '请选择记录日期时间', trigger: 'blur' }
  ],
  PointDeviceID: [
    { required: true, message: '请选择记录点位设备', trigger: 'blur' }
  ],
  PatrolScheduleID: [
    { required: true, message: '请选择对应排班记录', trigger: 'blur' }
  ]
}

// 人员列表、设备列表和排班记录列表（模拟数据）
const userList = ref([
  { label: '张三', value: '1' },
  { label: '李四', value: '2' },
  { label: '王五', value: '3' },
  { label: '赵六', value: '4' },
  { label: '钱七', value: '5' }
])

const deviceList = ref([
  { label: '生产线A-设备1', value: '1' },
  { label: '生产线A-设备2', value: '2' },
  { label: '生产线B-设备1', value: '3' },
  { label: '仓库-设备1', value: '4' },
  { label: '办公区-设备1', value: '5' },
  { label: '办公区-设备2', value: '6' }
])

const scheduleList = ref([
  { label: '周一生产线A例行巡检', value: '1' },
  { label: '周三仓库安全巡检', value: '2' },
  { label: '周五办公区环境巡检', value: '3' },
  { label: '周二生产线B例行巡检', value: '4' },
  { label: '周四全厂区安全巡检', value: '5' }
])

// 获取选中人员的姓名
const getPersonNames = (userIds: string[]) => {
  return userIds
    .filter(id => id)
    .map(id => {
      const user = userList.value.find(u => u.value === id)
      return user ? user.label : ''
    })
    .filter(name => name)
}

// 初始化数据
const initData = () => {
  loading.value = true
  // 模拟数据获取
  setTimeout(() => {
    logList.value = [
      {
        id: 1,
        UserID1: '1',
        UserID2: '2',
        UserID3: '',
        CreateDate: '2024-04-17 09:30:00',
        PointDeviceID: '1',
        PatrolScheduleID: '1',
        PersonNames: ['张三', '李四'],
        DeviceName: '生产线A-设备1',
        ScheduleTitle: '周一生产线A例行巡检'
      },
      {
        id: 2,
        UserID1: '2',
        UserID2: '',
        UserID3: '',
        CreateDate: '2024-04-17 14:15:00',
        PointDeviceID: '3',
        PatrolScheduleID: '4',
        PersonNames: ['李四'],
        DeviceName: '生产线B-设备1',
        ScheduleTitle: '周二生产线B例行巡检'
      },
      {
        id: 3,
        UserID1: '3',
        UserID2: '4',
        UserID3: '5',
        CreateDate: '2024-04-17 16:45:00',
        PointDeviceID: '5',
        PatrolScheduleID: '3',
        PersonNames: ['王五', '赵六', '钱七'],
        DeviceName: '办公区-设备1',
        ScheduleTitle: '周五办公区环境巡检'
      }
    ]
    total.value = logList.value.length
    loading.value = false
  }, 500)
}

// 刷新数据
const handleRefresh = () => {
  currentPage.value = 1
  initData()
}

// 搜索功能
const handleSearch = () => {
  // 简单的前端搜索实现
  const filtered = logList.value.filter(item => {
    const searchStr = searchKeyword.value.toLowerCase()
    return item.DeviceName.toLowerCase().includes(searchStr) ||
           item.ScheduleTitle.toLowerCase().includes(searchStr) ||
           item.PersonNames.some(name => name.toLowerCase().includes(searchStr)) ||
           item.CreateDate.toLowerCase().includes(searchStr)
  })
  logList.value = filtered
}

// 分页处理
const handleSizeChange = (size: number) => {
  pageSize.value = size
}

const handleCurrentChange = (current: number) => {
  currentPage.value = current
}

// 行点击事件
const handleRowClick = (row: any) => {
  // 可以添加行点击后的处理逻辑
}

// 选择框变化事件
const handleSelectionChange = (selection: any[]) => {
  // 可以添加选择框变化后的处理逻辑
}

// 新增日志
const handleAddLog = () => {
  isEdit.value = false
  // 重置表单
  logForm.UserID1 = ''
  logForm.UserID2 = ''
  logForm.UserID3 = ''
  logForm.CreateDate = ''
  logForm.PointDeviceID = ''
  logForm.PatrolScheduleID = ''
  
  // 打开对话框
  dialogVisible.value = true
}

// 编辑日志
const handleEdit = (row: any) => {
  isEdit.value = true
  // 填充表单数据
  logForm.UserID1 = row.UserID1 || ''
  logForm.UserID2 = row.UserID2 || ''
  logForm.UserID3 = row.UserID3 || ''
  logForm.CreateDate = row.CreateDate || ''
  logForm.PointDeviceID = row.PointDeviceID || ''
  logForm.PatrolScheduleID = row.PatrolScheduleID || ''
  
  // 打开对话框
  dialogVisible.value = true
}

// 删除日志
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `确定要删除ID为${row.id}的巡检日志吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 模拟删除操作
    const index = logList.value.findIndex(item => item.id === row.id)
    if (index !== -1) {
      logList.value.splice(index, 1)
      total.value = logList.value.length
      ElMessage.success('删除成功')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 保存日志
const handleSave = async () => {
  if (!logFormRef.value) return
  
  try {
    await logFormRef.value.validate()
    
    // 模拟保存操作
    const userIds = [logForm.UserID1, logForm.UserID2, logForm.UserID3]
    const personNames = getPersonNames(userIds)
    
    const device = deviceList.value.find(d => d.value === logForm.PointDeviceID)
    const schedule = scheduleList.value.find(s => s.value === logForm.PatrolScheduleID)
    
    const newLog = {
      id: isEdit.value ? logList.value.find(item => 
        item.UserID1 === logForm.UserID1 && 
        item.CreateDate === logForm.CreateDate
      )?.id : Date.now(),
      UserID1: logForm.UserID1,
      UserID2: logForm.UserID2,
      UserID3: logForm.UserID3,
      CreateDate: logForm.CreateDate,
      PointDeviceID: logForm.PointDeviceID,
      PatrolScheduleID: logForm.PatrolScheduleID,
      PersonNames: personNames,
      DeviceName: device ? device.label : '',
      ScheduleTitle: schedule ? schedule.label : ''
    }
    
    if (isEdit.value) {
      // 编辑模式
      const index = logList.value.findIndex(item => 
        item.UserID1 === logForm.UserID1 && 
        item.CreateDate === logForm.CreateDate
      )
      if (index !== -1) {
        logList.value[index] = newLog
      }
    } else {
      // 新增模式
      logList.value.unshift(newLog)
      total.value = logList.value.length
    }
    
    ElMessage.success(isEdit.value ? '编辑成功' : '新增成功')
    dialogVisible.value = false
  } catch (error) {
    // 表单验证失败
  }
}

// 对话框关闭处理
const handleClose = () => {
  if (logFormRef.value) {
    logFormRef.value.resetFields()
  }
}

// 组件挂载时初始化数据
onMounted(() => {
  initData()
})
</script>

<style scoped>
/* 表单样式 */
:deep(.el-form) {
  background: transparent !important;
}

:deep(.el-form-item__label) {
  color: #68c9ff !important;
  font-weight: 500;
}

/* 表格样式 - 设置为透明背景 */
:deep(.el-table) {
  background: transparent !important;
}

:deep(.el-table tr){
  background: transparent !important;
}

:deep(.el-table__header-wrapper) {
  background: transparent !important;
}

:deep(.el-table__header) {
  background: transparent !important;
}

:deep(.el-table__header) th {
  background: transparent !important;
  background-color: transparent !important;
  color: #68c9ff !important;
  border-color: rgba(104, 201, 255, 0.3) !important;
}

/* 确保表头在各种状态下都保持透明 */
:deep(.el-table th.is-leaf) {
  background: transparent !important;
  background-color: transparent !important;
}

:deep(.el-table__body-wrapper) {
  background: transparent !important;
}

:deep(.el-table__row) {
  background: transparent !important;
}

:deep(.el-table__row:nth-child(2n)) {
  background: rgba(0, 58, 97, 0.1) !important;
}

:deep(.el-table__row:hover) {
  background: rgba(0, 58, 97, 0.2) !important;
}

:deep(.el-table__body) td {
  border-color: rgba(104, 201, 255, 0.2) !important;
  color: #91d5ff !important;
}

/* 对话框样式 */
:deep(.el-dialog) {
  background-color: rgba(0, 58, 97, 0.4) !important; /* 空军蓝，透明度40% */
  backdrop-filter: blur(8px); /* 高斯模糊效果 */
  border: 1px solid rgba(104, 201, 255, 0.3);
}

:deep(.el-dialog__header) {
  background-color: rgba(0, 58, 97, 0.6) !important;
  border-bottom: 1px solid rgba(104, 201, 255, 0.3);
}

:deep(.el-dialog__title) {
  color: #91d5ff !important;
  font-weight: 600;
}

:deep(.el-dialog__footer) {
  background-color: rgba(0, 58, 97, 0.6) !important;
  border-top: 1px solid rgba(104, 201, 255, 0.3);
  padding-bottom: 20px;
}
</style>