<template>
  <el-config-provider :locale="zhCn">
    <el-dialog
        v-model="visible"
        title="🔧 维修与故障日志中心"
        width="85%"
        top="5vh"
        destroy-on-close
        append-to-body
    >
      <div class="logs-container">
        <div class="toolbar">
          <div class="filter-group">
            <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                @change="fetchLogs"
                style="width: 260px"
            />

            <el-input
                v-model="keyword"
                placeholder="搜索：设备名 / 工程师 / 内容"
                style="width: 300px"
                :disabled="isSearchLocked"
                :clearable="!isSearchLocked"
                @clear="fetchLogs"
                @keyup.enter="fetchLogs"
            >
              <template #prefix><el-icon><Search /></el-icon></template>
            </el-input>

            <el-button type="primary" @click="fetchLogs" :disabled="isSearchLocked">查询</el-button>
          </div>

          <div class="action-group" v-if="userRole !== 'client'">
            <el-button type="success" icon="Plus" @click="() => openAddDialog()">新增记录</el-button>
          </div>
        </div>

        <el-table
            :data="logsList"
            border
            stripe
            v-loading="loading"
            height="550"
            style="width: 100%; margin-top: 15px"
        >
          <el-table-column prop="timestamp" label="记录时间" width="170" sortable />

          <el-table-column prop="device_name" label="设备名称" width="180">
            <template #default="{ row }">
              <el-tag effect="plain">{{ formatDisplayName(row.device_name) }}</el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="location" label="地点" width="150" show-overflow-tooltip />

          <el-table-column prop="engineer" label="工程师" width="120">
            <template #default="{ row }">
              <el-tag type="info" size="small">{{ row.engineer }}</el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="content" label="维修/故障详情" min-width="300" show-overflow-tooltip />

          <el-table-column label="操作" width="180" align="center" fixed="right" v-if="userRole !== 'client'">
            <template #default="{ row }">
              <el-button
                  type="primary"
                  link
                  icon="Edit"
                  @click="openEditDialog(row)"
              >
                修改
              </el-button>

              <el-popconfirm
                  v-if="userRole === 'admin'"
                  title="确定删除这条记录吗？"
                  @confirm="deleteLog(row.id)"
              >
                <template #reference>
                  <el-button type="danger" link icon="Delete">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <el-dialog
          v-model="logDialog.visible"
          :title="logDialog.isEdit ? '✏️ 修改维修记录' : '📝 新增维修记录'"
          width="500px"
          append-to-body
      >
        <el-form :model="logDialog.form" label-width="80px" label-position="top">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="设备名称" required>
                <el-autocomplete
                    v-model="logDialog.form.device_name"
                    :fetch-suggestions="querySearchDevice"
                    placeholder="必须选择现有设备"
                    :disabled="logDialog.isDeviceLocked || logDialog.isEdit"
                    style="width: 100%"
                    clearable
                    highlight-first-item
                    trigger-on-focus
                >
                  <template #default="{ item }">
                    <span class="name">{{ formatDisplayName(item.value) }}</span>
                  </template>
                </el-autocomplete>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工程师" required>
                <el-input
                    v-model="logDialog.form.engineer"
                    :placeholder="userRole === 'engineer' ? '' : '请输入工程师姓名'"
                    :disabled="userRole === 'engineer'"
                >
                  <template #prefix>
                    <el-icon><UserFilled /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="地点">
            <el-input v-model="logDialog.form.location" placeholder="例: 3号楼顶层" />
          </el-form-item>

          <el-form-item label="事件内容" required>
            <el-input
                v-model="logDialog.form.content"
                type="textarea"
                :rows="4"
                placeholder="描述故障原因及处理结果..."
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="logDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitLog" :loading="logDialog.submitting">
            {{ logDialog.isEdit ? '保存修改' : '提交保存' }}
          </el-button>
        </template>
      </el-dialog>

    </el-dialog>
  </el-config-provider>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import request from '../utils/request'
import { ElMessage, ElConfigProvider } from 'element-plus'
import { Search, Plus, Delete, Edit, UserFilled } from '@element-plus/icons-vue'
import zhCn from 'element-plus/es/locale/lang/zh-cn'

// --- 状态定义 ---
const visible = ref(false)
const loading = ref(false)
const logsList = ref([])
const keyword = ref('')
const dateRange = ref([])
const isSearchLocked = ref(false)

// 缓存的所有设备列表，格式 [{value: 'dev1'}, {value: 'dev2'}]
const allDevices = ref([])

const userRole = ref('')
const currentUsername = ref('')

const logDialog = reactive({
  visible: false,
  submitting: false,
  isEdit: false,
  isDeviceLocked: false,
  form: {
    id: null,
    device_name: '',
    engineer: '',
    location: '',
    content: ''
  }
})

// 统一获取认证信息
const refreshAuth = () => {
  userRole.value = localStorage.getItem('role') || 'client'
  currentUsername.value = localStorage.getItem('username') || ''
}

onMounted(() => { refreshAuth() })

// 1. 打开主列表
const open = (prefillData = null) => {
  refreshAuth()
  visible.value = true
  isSearchLocked.value = false
  keyword.value = ''

  // 🟢 必须：打开时立即加载设备库，否则无法校验
  fetchAllDevices()

  if (prefillData && prefillData.deviceName) {
    keyword.value = prefillData.deviceName
    if (userRole.value !== 'admin') {
      isSearchLocked.value = true
    }
  }
  fetchLogs()
}

// 🟢 获取设备库（核心）
const fetchAllDevices = async () => {
  try {
    const res = await request.get('/api/devices_overview')
    if (res.data && res.data.data) {
      allDevices.value = res.data.data.map(d => ({ value: d.name }))
    }
  } catch (e) {
    console.error('无法加载设备列表', e)
  }
}

// 自动补全过滤
const querySearchDevice = (queryString, cb) => {
  const results = queryString
      ? allDevices.value.filter(createFilter(queryString))
      : allDevices.value
  cb(results)
}
const createFilter = (queryString) => {
  return (item) => {
    return (item.value.toLowerCase().indexOf(queryString.toLowerCase()) !== -1)
  }
}

// 2. 获取日志列表
const fetchLogs = async () => {
  loading.value = true
  try {
    const params = { keyword: keyword.value }
    if (dateRange.value && dateRange.value.length === 2) {
      params.start_date = dateRange.value[0]
      params.end_date = dateRange.value[1]
    }
    const res = await request.get('/api/logs/list', { params })
    logsList.value = res.data.data
  } catch (e) {
    ElMessage.error('获取日志失败')
  } finally {
    loading.value = false
  }
}

// 3. 打开新增
const openAddDialog = () => {
  refreshAuth()
  logDialog.isEdit = false

  let autoEngineer = ''
  if (userRole.value === 'engineer') {
    autoEngineer = currentUsername.value
  }

  // 逻辑：如果搜索栏锁定了(从设备卡片进来的)，直接锁定设备名
  let prefillDevice = ''
  let lockDevice = false

  if (isSearchLocked.value && keyword.value) {
    prefillDevice = keyword.value
    lockDevice = true
  }

  logDialog.isDeviceLocked = lockDevice

  logDialog.form = {
    id: null,
    device_name: prefillDevice,
    engineer: autoEngineer,
    location: '',
    content: ''
  }
  logDialog.visible = true
}

// 4. 编辑
const openEditDialog = (row) => {
  refreshAuth()
  logDialog.isEdit = true
  // 编辑模式禁止修改设备名（防止关联错误）
  logDialog.isDeviceLocked = true

  logDialog.form = {
    id: row.id,
    device_name: row.device_name,
    engineer: userRole.value === 'engineer' ? currentUsername.value : row.engineer,
    location: row.location,
    content: row.content
  }
  logDialog.visible = true
}

// 5. 🟢 提交保存 (核心修改区)
const submitLog = async () => {
  refreshAuth()

  const inputDeviceName = logDialog.form.device_name;

  // A. 基础非空校验
  if (!inputDeviceName || !logDialog.form.content) {
    return ElMessage.warning('请填写 设备名称 和 事件内容')
  }

  // B. 🔴 关键逻辑：校验设备名是否存在于设备库中
  // 如果当前设备列表还没加载完(极少情况)，尝试重新加载一次或者报错
  if (allDevices.value.length === 0) {
    await fetchAllDevices();
  }

  // 检查输入的设备名是否能在 allDevices 数组里找到 exact match
  const isDeviceExist = allDevices.value.some(d => d.value === inputDeviceName);

  // 如果设备名不在库中，且也不是空，直接拒绝
  if (!isDeviceExist) {
    return ElMessage.error(`设备 "${inputDeviceName}" 不存在！请从下拉列表中选择有效的设备。`);
  }

  // C. 身份校验
  if (userRole.value !== 'engineer' && !logDialog.form.engineer) {
    return ElMessage.warning('请填写工程师姓名')
  }
  if (userRole.value === 'engineer') {
    logDialog.form.engineer = currentUsername.value
  }

  logDialog.submitting = true
  try {
    const endpoint = logDialog.isEdit ? '/api/logs/update' : '/api/logs/add'
    await request.post(endpoint, logDialog.form)

    ElMessage.success(logDialog.isEdit ? '记录已更新' : '记录已添加')
    logDialog.visible = false
    fetchLogs()
  } catch (e) {
    ElMessage.error(e.response?.data?.msg || '保存失败')
  } finally {
    logDialog.submitting = false
  }
}

// 6. 删除
const deleteLog = async (id) => {
  try {
    await request.post('/api/logs/delete', { id })
    ElMessage.success('已删除')
    fetchLogs()
  } catch (e) {
    ElMessage.error('无权删除')
  }
}

const formatDisplayName = (n) => n ? n.toUpperCase().replace(/_/g, ' ') : ''

defineExpose({ open })
</script>

<style scoped>
.logs-container { padding: 10px; }
.toolbar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; }
.filter-group { display: flex; gap: 12px; }

.name {
  font-weight: bold;
  color: #333;
}

:deep(.el-input.is-disabled .el-input__inner) {
  color: #303133 !important;
  -webkit-text-fill-color: #303133 !important;
  font-weight: bold;
}
</style>
