<template>
  <div class="check-plan-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">设备点检计划管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleAdd">
          <Icon icon="mdi:plus" class="mr-4px" />
          新增点检计划
        </el-button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <el-card shadow="never" class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="计划编号">
          <el-input v-model="searchForm.planCode" placeholder="请输入计划编号" clearable />
        </el-form-item>
        <el-form-item label="计划名称">
          <el-input v-model="searchForm.planName" placeholder="请输入计划名称" clearable />
        </el-form-item>
        <el-form-item label="设备名称">
          <el-select v-model.number="searchForm.equipmentId" filterable clearable placeholder="请选择设备"
            style="width: 140px">
            <el-option v-for="item in deviceList" :key="item.id" :label="item.deviceName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="草稿" value="draft" />
            <el-option label="启用" value="active" />
            <el-option label="暂停" value="paused" />
            <el-option label="归档" value="archived" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <Icon icon="mdi:magnify" class="mr-4px" />
            搜索
          </el-button>
          <el-button @click="handleReset">
            <Icon icon="mdi:refresh" class="mr-4px" />
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="never" class="table-card" :body-style="{ padding: '0' }">
      <el-table v-loading="loading" :data="tableData" border stripe style="width: 100%">
        <el-table-column prop="planCode" label="计划编号" width="180" />
        <el-table-column prop="planName" label="计划名称" />
        <el-table-column prop="equipmentName" label="设备名称" />
        <el-table-column prop="cycleType" label="周期类型" width="100">
          <template #default="{ row }">
            {{ cycleTypeMap[row.cycleType] || row.cycleType }}
          </template>
        </el-table-column>
        <el-table-column prop="cycleValue" label="周期数值" width="100" />
        <el-table-column prop="startDate" label="开始日期" width="110" />
        <el-table-column prop="endDate" label="结束日期" width="110" />
        <el-table-column prop="timeWindow" label="时间段" width="110" />
        <el-table-column prop="assignee" label="负责人" width="100" />
        <el-table-column prop="assigneePhone" label="负责人手机号" width="120" />
        <el-table-column prop="status" label="状态" width="90">
          <template #default="{ row }">
            <el-tag :type="statusTagType(row.status)">
              {{ statusMap[row.status] || row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="text" @click="handleEdit(row)">
              <Icon icon="mdi:pencil" class="mr-4px" />编辑
            </el-button>
            <el-button type="text" @click="handleView(row)">
              <Icon icon="mdi:eye" class="mr-4px" />查看
            </el-button>
            <el-button type="text" @click="handleDelete(row)" class="text-red-500">
              <Icon icon="mdi:delete" class="mr-4px" />删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-wrapper">
        <el-pagination v-model:current-page="pagination.current" v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]" :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" :close-on-click-modal="false"
      @close="handleDialogClose">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px">
        <el-form-item label="计划编号" prop="planCode">
          <el-input v-model="formData.planCode" placeholder="如CHK-2024-001" />
        </el-form-item>
        <el-form-item label="计划名称" prop="planName">
          <el-input v-model="formData.planName" placeholder="请输入计划名称" />
        </el-form-item>
        <el-form-item label="设备名称" prop="equipmentName">
          <el-select v-model.number="formData.equipmentName" filterable clearable placeholder="请选择设备"
            @change="onDeviceChange">
            <el-option v-for="item in deviceList" :key="item.id" :label="item.deviceName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="周期类型" prop="cycleType">
          <el-select v-model="formData.cycleType" placeholder="请选择周期类型">
            <el-option v-for="(label, value) in cycleTypeMap" :key="value" :label="label" :value="value" />
          </el-select>
        </el-form-item>
        <el-form-item label="周期数值" prop="cycleValue">
          <el-input-number v-model="formData.cycleValue" :min="1" />
        </el-form-item>
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker v-model="formData.startDate" type="date" placeholder="选择日期" />
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker v-model="formData.endDate" type="date" placeholder="选择日期" />
        </el-form-item>
        <el-form-item label="时间段" prop="timeWindow">
          <el-input v-model="formData.timeWindow" placeholder="如08:00-17:00" />
        </el-form-item>
        <el-form-item label="点检项目" prop="checkItems">
          <el-input v-model="formData.checkItems" placeholder="请输入点检项目" />
        </el-form-item>
        <el-form-item label="SOP文档" prop="sopReference">
          <el-input v-model="formData.sopReference" placeholder="操作规范文档链接" />
        </el-form-item>
        <el-form-item label="负责人" prop="assignee">
          <el-input v-model="formData.assignee" placeholder="请输入负责人" />
        </el-form-item>
        <el-form-item label="负责人手机号" prop="assigneePhone">
          <el-input v-model="formData.assigneePhone" placeholder="请输入负责人手机号" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="formData.status" placeholder="请选择状态">
            <el-option v-for="(label, value) in statusMap" :key="value" :label="label" :value="value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog v-model="viewDialogVisible" title="点检计划详情" width="500px">
      <div v-if="viewData" class="view-content">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="计划编号">{{ viewData.planCode }}</el-descriptions-item>
          <el-descriptions-item label="计划名称">{{ viewData.planName }}</el-descriptions-item>
          <el-descriptions-item label="设备名称">{{ viewData.equipmentName }}</el-descriptions-item>
          <el-descriptions-item label="周期类型">{{ cycleTypeMap[viewData.cycleType] || viewData.cycleType
            }}</el-descriptions-item>
          <el-descriptions-item label="周期数值">{{ viewData.cycleValue }}</el-descriptions-item>
          <el-descriptions-item label="开始日期">{{ viewData.startDate }}</el-descriptions-item>
          <el-descriptions-item label="结束日期">{{ viewData.endDate }}</el-descriptions-item>
          <el-descriptions-item label="时间段">{{ viewData.timeWindow }}</el-descriptions-item>
          <el-descriptions-item label="点检项目">{{ viewData.checkItems }}</el-descriptions-item>
          <el-descriptions-item label="SOP文档">{{ viewData.sopReference }}</el-descriptions-item>
          <el-descriptions-item label="负责人">{{ viewData.assignee }}</el-descriptions-item>
          <el-descriptions-item label="负责人手机号">{{ viewData.assigneePhone }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="statusTagType(viewData.status)">
              {{ statusMap[viewData.status] || viewData.status }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDate(viewData.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="最后更新时间">{{ formatDate(viewData.updateTime) }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { DeviceApi, DeviceVO } from '@/api/iot/device/device'
import { RepairOrderApi } from '@/api/iot/maintain/repairOrder'
import { CheckPlanApi, CheckPlanVO } from '@/api/iot/check/plan'
// import * as CheckPlanApi from '@/api/iot/check/plan' // 你需要实现对应的API文件

const cycleTypeMap = {
  daily: '每日',
  weekly: '每周',
  monthly: '每月',
  quarterly: '每季度',
  yearly: '每年',
  custom: '自定义',
}
const statusMap = {
  draft: '草稿',
  active: '启用',
  paused: '暂停',
  archived: '归档',
}
const statusTagType = (status: string) => {
  switch (status) {
    case 'active': return 'success'
    case 'paused': return 'warning'
    case 'archived': return 'info'
    default: return 'primary'
  }
}

// 搜索表单
const searchForm = reactive({
  planCode: '',
  planName: '',
  equipmentId: '',
  status: ''
})

// 分页
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 表格数据
const tableData = ref<any[]>([])
const loading = ref(false)

// 对话框相关
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const submitLoading = ref(false)

// 表单相关
const formRef = ref<FormInstance>()
const formData = reactive({
  planId: '',
  planCode: '',
  planName: '',
  equipmentId: '',
  equipmentName: '',
  cycleType: 'monthly',
  cycleValue: 1,
  startDate: '',
  endDate: '',
  timeWindow: '08:00-17:00',
  checkItems: '',
  sopReference: '',
  assignee: '',
  assigneePhone: '',
  status: 'active',
})

// 表单验证规则
const formRules = {
  planCode: [{ required: true, message: '请输入计划编号', trigger: 'blur' }],
  planName: [{ required: true, message: '请输入计划名称', trigger: 'blur' }],
  equipmentName: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
  cycleType: [{ required: true, message: '请选择周期类型', trigger: 'change' }],
  cycleValue: [{ required: true, message: '请输入周期数值', trigger: 'blur' }],
  startDate: [{ required: true, message: '请选择开始日期', trigger: 'change' }],
  timeWindow: [{ required: true, message: '请输入时间段', trigger: 'blur' }],
  checkItems: [{ required: true, message: '请输入点检项目', trigger: 'blur' }],
  assignee: [{ required: true, message: '请输入负责人', trigger: 'blur' }],
  assigneePhone: [{ required: true, message: '请输入负责人手机号', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
}

// 查看相关
const viewData = ref<any | null>(null)

// 设备列表
const deviceList = ref<any[]>([])

const dialogTitle = computed(() => {
  return dialogType.value === 'add' ? '新增点检计划' : '编辑点检计划'
})

const handleSearch = () => {
  pagination.current = 1
  fetchData()
}
const handleReset = () => {
  Object.assign(searchForm, {
    planCode: '',
    planName: '',
    equipmentId: '',
    status: ''
  })
  handleSearch()
}

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      pageNo: pagination.current,
      pageSize: pagination.size,
      ...searchForm
    }
    const res = await CheckPlanApi.getCheckPlanPage(params)
    tableData.value = res.list
    pagination.total = res.total
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  fetchData()
}
const handleCurrentChange = (current: number) => {
  pagination.current = current
  fetchData()
}

const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}
const handleEdit = (row: any) => {
  dialogType.value = 'edit'
  Object.assign(formData, row)
  dialogVisible.value = true
}
const handleView = (row: any) => {
  viewData.value = row
  viewDialogVisible.value = true
}
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要删除该点检计划吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await CheckPlanApi.deleteCheckPlan(row.planId)
    ElMessage.success('删除成功')
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}
const resetForm = () => {
  Object.assign(formData, {
    planId: '',
    planCode: '',
    planName: '',
    equipmentId: '',
    equipmentName: '',
    cycleType: 'monthly',
    cycleValue: 1,
    startDate: '',
    endDate: '',
    timeWindow: '08:00-17:00',
    checkItems: '',
    sopReference: '',
    assignee: '',
    assigneePhone: '',
    status: 'active',
  })
  formRef.value?.clearValidate()
}
const handleDialogClose = () => {
  dialogVisible.value = false
  resetForm()
}
const handleSubmit = async () => {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
    submitLoading.value = true
    const submitData = { ...formData } as CheckPlanVO
    if (dialogType.value === 'add') {
      await CheckPlanApi.createCheckPlan(submitData)
      ElMessage.success('新增成功')
    } else {
      await CheckPlanApi.updateCheckPlan(submitData)
      ElMessage.success('编辑成功')
    }
    dialogVisible.value = false
    fetchData()
  } catch (error) {
    ElMessage.error('提交失败')
  } finally {
    submitLoading.value = false
  }
}

// 设备选择后自动填充设备名称
const onDeviceChange = (id: number) => {
  const device = deviceList.value.find(d => d.id === id)
  debugger;
  formData.equipmentName = device.deviceName
}

// 获取设备列表（来自维修接口）
const fetchDeviceList = async () => {
  try {
    const res = await RepairOrderApi.getDeviceList()
    deviceList.value = res || []
  } catch (e) {
    deviceList.value = []
  }
}

// 时间戳转日期字符串
function formatDate(ts: number | string | undefined) {
  if (!ts) return ''
  const d = new Date(Number(ts))
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}:${String(d.getSeconds()).padStart(2, '0')}`
}

onMounted(() => {
  fetchDeviceList()
  fetchData()
})
</script>

<style scoped>
.check-plan-container {
  width: 100vw;
  max-width: 88vw;
  padding: 20px;
  box-sizing: border-box;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.search-card {
  width: 100%;
  max-width: 100%;
  margin-bottom: 20px;
}

.table-card {
  width: 100%;
  max-width: 100%;
  padding: 0;
  margin-bottom: 20px;
  overflow-x: auto;
}

.el-table {
  width: 100%;
  min-width: 1200px;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}

.view-content {
  padding: 20px 0;
}
</style>
