<template>
  <div class="officer-container">
<!--    &lt;!&ndash; 页面标题 &ndash;&gt;-->
<!--    <div class="page-header">-->
<!--      <h2 class="page-title">电表监测管理</h2>-->
<!--      <div class="header-actions">-->
<!--        -->
<!--      </div>-->
<!--    </div>-->

    <!-- 搜索区域 -->
    <el-card shadow="never" class="search-card">
      <el-form :model="searchForm" inline>
<!--        <el-form-item label="设备编号">-->
<!--          <el-input v-model="searchForm.deviceCode" placeholder="请输入设备编号" clearable />-->
<!--        </el-form-item>-->
        <el-form-item label="设备名称">
          <el-select v-model="searchForm.deviceName" placeholder="请选择设备名称" clearable style="width: 200px">
            <el-option label="一号电表" value="一号电表" />
            <el-option label="二号电表" value="二号电表" />
          </el-select>
        </el-form-item>
        <el-form-item label="位置">
          <el-input v-model="searchForm.location" placeholder="请输入位置" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="在线" value="online" />
            <el-option label="离线" value="offline" />
            <el-option label="维护" value="maintenance" />
          </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-button type="primary" @click="handleAdd">
            <Icon icon="mdi:plus" class="mr-4px" />
            新增
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="never" class="table-card">
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        style="width: 100%"
      >
<!--        <el-table-column prop="deviceCode" label="设备编号" width="200" />-->
        <el-table-column prop="deviceName" label="设备名称" width="200" />
        <el-table-column prop="location" label="位置" width="200" />
        <el-table-column prop="currentKWh" label="当前读数(KWh)" width="150" />
        <el-table-column prop="lastKWh" label="上次读数(KWh)" width="150" />
        <el-table-column prop="lastDate" label="抄表时间" width="200">
          <template #default="{ row }">
            {{ formatDate(row.lastDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="200">
          <template #default="{ row }">
            {{ row.createTime ? dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss') : '-' }}
          </template>
        </el-table-column>
<!--        <el-table-column prop="text1" label="备用字段1" width="150" />-->
<!--        <el-table-column prop="text2" label="备用字段2" width="150" />-->
<!--        <el-table-column prop="text3" label="备用字段3" width="150" />-->
        <el-table-column label="操作"  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
          :current-page="pagination.current"
          :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="500px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
<!--        <el-form-item label="设备编号" prop="deviceCode">-->
<!--          <el-input v-model="formData.deviceCode" placeholder="请输入设备编号" />-->
<!--        </el-form-item>-->
        <el-form-item label="设备名称" prop="deviceName">
          <el-select v-model="formData.deviceName" placeholder="请选择设备名称" style="width: 100%">
            <el-option label="一号电表" value="一号电表" />
            <el-option label="二号电表" value="二号电表" />
          </el-select>
        </el-form-item>
        <el-form-item label="位置" prop="location">
          <el-input v-model="formData.location" placeholder="请输入位置" />
        </el-form-item>
        <el-form-item label="当前读数(KWh)" prop="currentKWh">
          <el-input-number
            v-model="formData.currentKWh"
            placeholder="请输入当前读数"
            :precision="3"
            :min="0"
            :controls="true"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="上次读数(KWh)" prop="lastKWh">
          <el-input-number
            v-model="formData.lastKWh"
            placeholder="请输入上次读数"
            :precision="3"
            :min="0"
            :controls="true"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="抄表时间" prop="lastDate">
          <el-date-picker
            v-model="formData.lastDate"
            type="datetime"
            placeholder="选择抄表时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="formData.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="在线" value="online" />
            <el-option label="离线" value="offline" />
            <el-option label="维护" value="maintenance" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
<!--        <el-form-item label="备用字段1" prop="text1">-->
<!--          <el-input v-model="formData.text1" placeholder="请输入备用字段1" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="备用字段2" prop="text2">-->
<!--          <el-input v-model="formData.text2" placeholder="请输入备用字段2" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="备用字段3" prop="text3">-->
<!--          <el-input v-model="formData.text3" placeholder="请输入备用字段3" />-->
<!--        </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="400px"
    >
      <div v-if="viewData" class="view-content">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="ID">{{ viewData.id }}</el-descriptions-item>
<!--          <el-descriptions-item label="设备编号">{{ viewData.deviceCode }}</el-descriptions-item>-->
          <el-descriptions-item label="设备名称">{{ viewData.deviceName }}</el-descriptions-item>
          <el-descriptions-item label="位置">{{ viewData.location }}</el-descriptions-item>
          <el-descriptions-item label="当前读数(KWh)">{{ viewData.currentKWh }}</el-descriptions-item>
          <el-descriptions-item label="上次读数(KWh)">{{ viewData.lastKWh }}</el-descriptions-item>
          <el-descriptions-item label="抄表时间">
            {{ viewData.lastDate ? dayjs(viewData.lastDate).format('YYYY-MM-DD HH:mm:ss') : '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(viewData.status)">
              {{ getStatusText(viewData.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ viewData.createTime ? dayjs(viewData.createTime).format('YYYY-MM-DD HH:mm:ss') : '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="备注">{{ viewData.remark }}</el-descriptions-item>
<!--          <el-descriptions-item label="备用字段1">{{ viewData.text1 }}</el-descriptions-item>-->
<!--          <el-descriptions-item label="备用字段2">{{ viewData.text2 }}</el-descriptions-item>-->
<!--          <el-descriptions-item label="备用字段3">{{ viewData.text3 }}</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 * as ElectricityApi from '@/api/energy/electricity'
import dayjs from 'dayjs'

defineOptions({ name: 'ElectricityMonitoringManage' })

// 搜索表单
const searchForm = reactive({
  deviceCode: '',
  deviceName: '',
  location: '',
  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({
  id: '',
  deviceCode: '',
  deviceName: '',
  location: '',
  currentKWh: 0,
  lastKWh: 0,
  lastDate: '',
  status: 'online',
  remark: '',
  text1: '',
  text2: '',
  text3: ''
})

// 自定义验证器：当前读数必须大于上次读数
const validateCurrentKWh = (_rule: any, value: any, callback: any) => {
  if (value === null || value === undefined || value === '') {
    callback(new Error('请输入当前读数'))
  } else if (typeof value !== 'number') {
    callback(new Error('请输入数字'))
  } else if (formData.lastKWh && value <= formData.lastKWh) {
    callback(new Error('当前读数必须大于上次读数'))
  } else {
    callback()
  }
}

// 表单验证规则
const formRules = {
  // deviceCode: [{ required: true, message: '请输入设备编号', trigger: 'blur' }],
  deviceName: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
  currentKWh: [
    { required: true, validator: validateCurrentKWh, trigger: 'blur' }
  ],
  lastKWh: [
    { type: 'number' as const, message: '请输入数字', trigger: 'blur' }
  ],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

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

// 计算属性
const dialogTitle = computed(() => {
  return dialogType.value === 'add' ? '新增电表监测' : '编辑电表监测'
})

// 方法
const handleSearch = () => {
  pagination.current = 1
  fetchData()
}

const handleReset = () => {
  Object.assign(searchForm, {
    deviceCode: '',
    deviceName: '',
    location: '',
    status: ''
  })
  handleSearch()
}

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      pageNo: pagination.current,
      pageSize: pagination.size,
      deviceCode: searchForm.deviceCode || undefined,
      deviceName: searchForm.deviceName || undefined,
      location: searchForm.location || undefined,
      status: searchForm.status || undefined
    }
    const res = await ElectricityApi.getElectricityMonitoringPage(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()
  // 如果列表有数据，用第一条数据的当前读数作为上次读数
  if (tableData.value && tableData.value.length > 0) {
    const firstRow = tableData.value[0]
    formData.lastKWh = firstRow.currentKWh || 0
  }
  // 抄表时间默认为当前时间
  formData.lastDate = dayjs().format('YYYY-MM-DD HH:mm:ss')
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: any) => {
  dialogType.value = 'edit'
  Object.assign(formData, {
    ...row,
    lastDate: row.lastDate ? dayjs(row.lastDate).format('YYYY-MM-DD HH:mm:ss') : ''
  })
  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 ElectricityApi.deleteElectricityMonitoring(row.id)
    ElMessage.success('删除成功')
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 表单相关
const resetForm = () => {
  Object.assign(formData, {
    id: '',
    deviceCode: '',
    deviceName: '',
    location: '',
    currentKWh: 0,
    lastKWh: 0,
    lastDate: '',
    status: 'online',
    remark: '',
    text1: '',
    text2: '',
    text3: ''
  })
  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,
      status: formData.status as 'online' | 'offline' | 'maintenance'
    }
    if (dialogType.value === 'add') {
      await ElectricityApi.createElectricityMonitoring(submitData)
      ElMessage.success('新增成功')
    } else {
      await ElectricityApi.updateElectricityMonitoring(submitData)
      ElMessage.success('编辑成功')
    }
    dialogVisible.value = false
    fetchData()
  } catch (error) {
    ElMessage.error('提交失败')
  } finally {
    submitLoading.value = false
  }
}

// 状态处理方法
const getStatusType = (status: string) => {
  switch (status) {
    case 'online':
      return 'success'
    case 'offline':
      return 'info'
    case 'maintenance':
      return 'warning'
    default:
      return 'info'
  }
}

const getStatusText = (status: string) => {
  switch (status) {
    case 'online':
      return '在线'
    case 'offline':
      return '离线'
    case 'maintenance':
      return '维护'
    default:
      return '未知'
  }
}

const formatDate = (val: any) => {
  if (!val) return ''
  // 支持时间戳和字符串
  return dayjs(val).format('YYYY-MM-DD HH:mm:ss')
}

// 生命周期
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.officer-container {
    padding: 20px;
  width: 100%;
  max-width: 100%;
  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 {
    margin-bottom: 20px;
  width: 100%;
  max-width: 100%;
  }
  .table-card {
    margin-bottom: 20px;
  width: 100%;
  max-width: 100%;
  overflow-x: auto;
}
.el-table {
  width: 100%;
  min-width: 1000px;
}
  .pagination-wrapper {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
  }
  .dialog-footer {
    text-align: right;
  }
  .view-content {
    padding: 20px 0;
  }
</style>
