<template>
  <div class="patrol-manage-container">
    <vab-card>
      <el-tabs v-model="activeTab">
        <!-- Tab 1: 巡查记录 -->
        <el-tab-pane label="巡查记录" name="record">
          <vab-query-form>
            <vab-query-form-left-panel>
              <el-form :inline="true" :model="queryForm" @submit.prevent>
                <el-form-item label="巡查时间">
                  <el-date-picker
                    v-model="queryForm.date"
                    type="date"
                    placeholder="选择日期"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
                <el-form-item label="状态">
                  <el-select v-model="queryForm.status" placeholder="全部" clearable style="width: 120px">
                    <el-option label="正常" value="normal" />
                    <el-option label="异常" value="abnormal" />
                    <el-option label="漏巡" value="missed" />
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleQuery"> <vab-icon icon="search-line" /> 查询</el-button>
                </el-form-item>
              </el-form>
            </vab-query-form-left-panel>
          </vab-query-form>
          <el-table v-loading="loading" :data="recordList" border stripe>
            <el-table-column prop="time" label="巡查时间" width="160" sortable />
            <el-table-column prop="pointName" label="巡更点" width="150" />
            <el-table-column prop="staffName" label="巡查人员" width="120" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getStatusType(row.status)">{{ getStatusLabel(row.status) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="巡查说明" min-width="200" show-overflow-tooltip />
            <el-table-column prop="location" label="打卡定位" width="180">
              <template #default="{ row }">
                <span v-if="row.location" class="text-xs text-gray">
                  <vab-icon icon="map-pin-line" /> {{ row.location }}
                </span>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column label="现场照片" width="100" align="center">
              <template #default="{ row }">
                <el-image 
                  v-if="row.image"
                  style="width: 40px; height: 40px; border-radius: 4px"
                  :src="row.image" 
                  :preview-src-list="[row.image]"
                  fit="cover"
                />
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" align="center">
              <template #default="{ row }">
                <el-button type="text" size="small" @click="handleRecordDetail(row)">详情</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <vab-pagination
            :current-page="queryForm.pageNo"
            :page-size="queryForm.pageSize"
            :total="total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
          />
        </el-tab-pane>

        <!-- Tab 2: 巡更点设置 -->
        <el-tab-pane label="巡更点设置" name="point">
          <div class="mb-20">
            <el-button type="primary" @click="handleAddPoint"> <vab-icon icon="add-line" /> 新增巡更点</el-button>
          </div>
          <el-table :data="pointList" border stripe>
            <el-table-column prop="code" label="编号" width="120" />
            <el-table-column prop="name" label="名称" width="180" />
            <el-table-column prop="location" label="位置描述" min-width="200" />
            <el-table-column label="二维码" width="120" align="center">
              <template #default="{ row }">
                <el-button type="text" size="small" @click="handleViewQr(row)"> <vab-icon icon="qr-code-line" /> 查看</el-button>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="{ row }">
                <el-button type="primary" size="small" @click="handleEditPoint(row)">编辑</el-button>
                <el-button type="danger" size="small" @click="handleDeletePoint(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </vab-card>

    <!-- 巡更点编辑弹窗 -->
    <el-dialog v-model="pointDialogVisible" :title="pointDialogTitle" width="500px">
      <el-form :model="pointForm" label-width="80px">
        <el-form-item label="名称">
          <el-input v-model="pointForm.name" placeholder="如：一号楼大厅" />
        </el-form-item>
        <el-form-item label="位置">
          <el-input v-model="pointForm.location" placeholder="详细位置描述" />
        </el-form-item>
        <el-form-item label="经纬度">
          <el-input v-model="pointForm.geo" placeholder="选填，如：120.123, 30.456" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="pointDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSavePoint">确定</el-button>
      </template>
    </el-dialog>

    <!-- 二维码查看弹窗 -->
    <el-dialog v-model="qrVisible" title="巡更点二维码" width="300px" align-center>
      <div class="qr-container">
        <div class="qr-box">
          <!-- Mock QR Code -->
          <vab-icon icon="qr-code-line" style="font-size: 150px; color: #333;" />
        </div>
        <div class="mt-10 font-bold">{{ currentPoint?.name }}</div>
        <div class="text-xs text-gray">{{ currentPoint?.code }}</div>
        <el-button type="primary" class="mt-20 w-full" @click="handleDownloadQr">下载打印</el-button>
      </div>
    </el-dialog>

    <!-- 巡查记录详情弹窗 -->
    <record-detail-dialog ref="recordDetailRef" />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import RecordDetailDialog from './components/RecordDetailDialog.vue'

defineOptions({
  name: 'PatrolManage',
})

const activeTab = ref('record')
const loading = ref(false)
const total = ref(100)
const recordDetailRef = ref()

// --- Record Logic ---
const queryForm = reactive({
  date: '',
  status: '',
  pageNo: 1,
  pageSize: 10,
})

const recordList = ref([
  {
    id: 1,
    time: '2026-01-24 10:05:23',
    pointName: '一号楼大厅',
    staffName: '保安张三',
    status: 'normal',
    remark: '设施完好，无异常人员',
    location: '120.5432, 30.1234',
    image: 'https://picsum.photos/200/200?random=10'
  },
  {
    id: 2,
    time: '2026-01-24 09:30:00',
    pointName: '二号楼消防通道',
    staffName: '保安李四',
    status: 'abnormal',
    remark: '发现杂物堆积，已清理',
    location: '120.5435, 30.1236',
    image: 'https://picsum.photos/200/200?random=11'
  },
  {
    id: 3,
    time: '2026-01-24 08:00:00',
    pointName: '北区大门',
    staffName: '保安王五',
    status: 'normal',
    remark: '早班交接巡查',
    location: '120.5440, 30.1240',
    image: ''
  }
])

const getStatusLabel = (status) => {
  const map = { normal: '正常', abnormal: '异常', missed: '漏巡' }
  return map[status]
}
const getStatusType = (status) => {
  const map = { normal: 'success', abnormal: 'danger', missed: 'warning' }
  return map[status]
}

const generateRecords = () => {
  return [
    {
      id: 1,
      time: '2026-01-24 10:05:23',
      pointName: '一号楼大厅',
      staffName: '保安张三',
      status: 'normal',
      remark: '设施完好，无异常人员',
      location: '120.5432, 30.1234',
      image: 'https://picsum.photos/200/200?random=10'
    },
    {
      id: 2,
      time: '2026-01-24 09:30:00',
      pointName: '二号楼消防通道',
      staffName: '保安李四',
      status: 'abnormal',
      remark: '发现杂物堆积，已清理',
      location: '120.5435, 30.1236',
      image: 'https://picsum.photos/200/200?random=11'
    },
    {
      id: 3,
      time: '2026-01-24 08:00:00',
      pointName: '北区大门',
      staffName: '保安王五',
      status: 'normal',
      remark: '早班交接巡查',
      location: '120.5440, 30.1240',
      image: ''
    }
  ]
}

const handleQuery = () => {
  loading.value = true
  setTimeout(() => {
    let list = generateRecords()
    if (queryForm.date) {
      list = list.filter((item) => item.time.includes(queryForm.date))
    }
    if (queryForm.status) {
      list = list.filter((item) => item.status === queryForm.status)
    }
    recordList.value = list
    total.value = list.length
    loading.value = false
  }, 500)
}

const handleRecordDetail = (row) => {
  recordDetailRef.value.open(row)
}

const handleCurrentChange = (val) => {
  queryForm.pageNo = val
  handleQuery()
}
const handleSizeChange = (val) => {
  queryForm.pageSize = val
  handleQuery()
}

// --- Point Logic ---
const pointList = ref([
  { id: 1, code: 'P001', name: '一号楼大厅', location: '一号楼正门入口处', geo: '120.5432, 30.1234' },
  { id: 2, code: 'P002', name: '二号楼消防通道', location: '二号楼东侧消防梯', geo: '120.5435, 30.1236' },
  { id: 3, code: 'P003', name: '北区大门', location: '园区北侧车辆出入口', geo: '120.5440, 30.1240' },
])

const pointDialogVisible = ref(false)
const pointDialogTitle = ref('')
const pointForm = reactive({
  id: '',
  name: '',
  location: '',
  geo: ''
})

const handleAddPoint = () => {
  pointDialogTitle.value = '新增巡更点'
  pointForm.id = ''
  pointForm.name = ''
  pointForm.location = ''
  pointForm.geo = ''
  pointDialogVisible.value = true
}

const handleEditPoint = (row) => {
  pointDialogTitle.value = '编辑巡更点'
  Object.assign(pointForm, row)
  pointDialogVisible.value = true
}

const handleSavePoint = () => {
  if (!pointForm.name) {
    ElMessage.warning('请输入名称')
    return
  }
  if (pointForm.id) {
    const index = pointList.value.findIndex(p => p.id === pointForm.id)
    if (index !== -1) Object.assign(pointList.value[index], pointForm)
  } else {
    pointList.value.push({
      id: Date.now(),
      code: `P00${pointList.value.length + 1}`,
      ...pointForm
    })
  }
  pointDialogVisible.value = false
  ElMessage.success('保存成功')
}

const handleDeletePoint = (row) => {
  ElMessageBox.confirm('确认删除该巡更点？', '删除确认').then(() => {
    const index = pointList.value.findIndex(p => p.id === row.id)
    if (index !== -1) pointList.value.splice(index, 1)
    ElMessage.success('删除成功')
  })
}

// --- QR Logic ---
const qrVisible = ref(false)
const currentPoint = ref(null)

const handleViewQr = (row) => {
  currentPoint.value = row
  qrVisible.value = true
}

const handleDownloadQr = () => {
  ElMessage.success('二维码已下载')
}

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

<style lang="scss" scoped>
.patrol-manage-container {
  .mb-20 { margin-bottom: 20px; }
  .mt-10 { margin-top: 10px; }
  .mt-20 { margin-top: 20px; }
  .w-full { width: 100%; }
  .text-xs { font-size: 12px; }
  .text-gray { color: #909399; }
  .font-bold { font-weight: bold; }
  
  .qr-container {
    text-align: center;
    .qr-box {
      border: 1px solid #eee;
      padding: 10px;
      display: inline-block;
      border-radius: 8px;
    }
  }
}
</style>
