<template>
  <div class="water-page device-page">
    <div class="page-heading">
      <div class="page-title">
        <span class="page-title-icon"><el-icon><component :is="pageIcon" /></el-icon></span>
        <div><h2>{{ title }}</h2><span class="muted">{{ subtitle }}</span></div>
      </div>
      <el-button :icon="Refresh" :loading="loading" @click="loadData">刷新</el-button>
    </div>

    <el-card shadow="never" class="filter-card">
      <el-form :inline="true" :model="query">
        <el-form-item label="设备名称"><el-input v-model="query.equipmentName" clearable /></el-form-item>
        <el-form-item label="设备编码"><el-input v-model="query.equipmentCode" clearable /></el-form-item>
        <el-form-item v-if="view !== 'maintain'" label="报警状态"><el-select v-model="query.alarmStatus" clearable><el-option label="正常" :value="0" /><el-option label="报警" :value="1" /></el-select></el-form-item>
        <el-form-item v-if="view !== 'maintain'" label="报警等级"><el-select v-model="query.alertLevel" clearable><el-option v-for="item in levels" :key="item.value" v-bind="item" /></el-select></el-form-item>
        <el-form-item><el-button type="primary" @click="loadData">查询</el-button><el-button @click="reset">重置</el-button></el-form-item>
      </el-form>
    </el-card>

    <el-card shadow="never" class="water-panel">
      <div class="card-title"><span><el-icon><Monitor /></el-icon> {{ title }}清单</span><el-button link type="primary" @click="exportData">导出</el-button></div>
      <el-table :data="page.records" border stripe v-loading="loading" row-key="equipmentId">
        <el-table-column type="index" label="#" width="55" /><el-table-column prop="equipmentCode" label="设备编码" min-width="130" /><el-table-column prop="equipmentName" label="设备名称" min-width="150" /><el-table-column prop="equipmentTypeName" label="设备类型" min-width="120" /><el-table-column prop="equipmentLocation" label="安装位置" min-width="180" show-overflow-tooltip />
        <el-table-column v-if="view !== 'maintain'" label="设备状态" width="100"><template #default="{ row }"><el-tag :type="Number(row.alarmStatus) === 1 ? 'danger' : 'success'">{{ row.deviceStatusText }}</el-tag></template></el-table-column>
        <el-table-column v-if="view !== 'maintain'" label="报警等级" width="110"><template #default="{ row }"><el-tag :type="alarmLevelType(row.alertLevel)">{{ row.alarmLevelText }}</el-tag></template></el-table-column>
        <el-table-column label="关联维修单" min-width="190" show-overflow-tooltip><template #default="{ row }">{{ view === 'maintain' ? (row.orderNo || '-') : row.relatedOrderNo }}</template></el-table-column>
        <el-table-column label="维修状态" min-width="110"><template #default="{ row }">{{ view === 'maintain' ? (row.status || '暂无') : row.workOrderStatusText }}</template></el-table-column>
        <el-table-column label="操作" width="190" fixed="right"><template #default="{ row }"><el-button link type="primary" @click="selectPoint(row)">详情</el-button><el-button v-if="view === 'dispatch'" link type="warning" @click="openOrder(row)">维修派单</el-button><el-button v-if="view === 'maintain'" link type="danger" @click="removeRecord(row)">删除</el-button></template></el-table-column>
      </el-table>
      <el-pagination v-model:current-page="query.pageNum" v-model:page-size="query.pageSize" :total="page.total" layout="total, sizes, prev, pager, next" :page-sizes="[10, 20, 50]" @change="loadData" />
    </el-card>

    <el-drawer v-model="detailVisible" class="detail-drawer device-detail-drawer" title="设备详情" direction="rtl" size="680px" append-to-body>
      <div class="detail-summary"><span class="detail-name">{{ detail.equipmentName || '-' }}</span><el-tag :type="Number(detail.alarmStatus) === 1 ? 'danger' : 'success'">{{ detail.deviceStatusText || '-' }}</el-tag></div>
      <el-descriptions :column="2" border>
        <el-descriptions-item v-for="item in detailFields" :key="item.label" :label="item.label">{{ item.value }}</el-descriptions-item>
      </el-descriptions>
      <template #footer><el-button @click="detailVisible = false">关闭</el-button></template>
    </el-drawer>
    <el-dialog v-model="dispatchVisible" title="设备维修派单" width="600px"><el-form :model="dispatchForm" label-width="100px"><el-form-item label="设备"><span>{{ dispatchDevice.equipmentName }}（{{ dispatchDevice.equipmentCode }}）</span></el-form-item><el-form-item label="问题描述" required><el-input v-model="dispatchForm.description" type="textarea" :rows="4" maxlength="500" show-word-limit placeholder="请输入故障或异常描述" /></el-form-item><el-form-item label="接单责任人" required><el-select v-model="dispatchForm.receiveUserId" filterable clearable placeholder="请选择责任人" :loading="userLoading" style="width:100%"><el-option v-for="user in users" :key="user.userId" :label="user.nickName || user.userName" :value="user.userId" /></el-select></el-form-item></el-form><template #footer><el-button @click="dispatchVisible = false">取消</el-button><el-button type="primary" :loading="dispatching" @click="submitDispatch">确认派单</el-button></template></el-dialog>
  </div>
</template>

<script setup>
import { computed, onMounted, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Monitor, Refresh } from '@element-plus/icons-vue'
import { listUser } from '@/api/system/user'
import { createAbnormalOrder, exportAbnormalDevices, exportDeviceLedger, listAbnormalDevices, listDeviceLedger, listMaintainRecords, deleteMaintainRecord } from '@/api/pipeNetwork/waterSupply'
import { normalizePage } from '@/utils/waterSupplyModel'
import { buildMaintainOrderPayload, normalizeDeviceRow } from '@/utils/waterSupplyUiModel'

const props = defineProps({ title: { type: String, required: true }, subtitle: { type: String, default: '设备信息、运行状态与维护过程管理' }, view: { type: String, default: 'ledger' } })
const { title, subtitle, view } = props
const query = ref({ pageNum: 1, pageSize: 10, equipmentName: '', equipmentCode: '', alarmStatus: undefined, alertLevel: undefined })
const page = ref({ records: [], total: 0 }); const loading = ref(false); const detailVisible = ref(false); const detail = ref({}); const dispatchVisible = ref(false); const dispatching = ref(false); const dispatchDevice = ref({}); const dispatchForm = ref({ description: '', receiveUserId: undefined }); const users = ref([]); const userLoading = ref(false)
const levels = [{ label: '一级', value: 1 }, { label: '二级', value: 2 }, { label: '三级', value: 3 }, { label: '四级', value: 4 }]; const pageIcon = Monitor; const alarmLevelType = level => ({ 1: 'danger', 2: 'warning', 3: 'primary', 4: 'success' }[Number(level)] || 'info')
const detailFields = computed(() => [['设备编码', detail.value.equipmentCode], ['设备类型', detail.value.equipmentTypeName || detail.value.typeName], ['安装位置', detail.value.equipmentLocation], ['设备状态', detail.value.deviceStatusText], ['报警等级', detail.value.alarmLevelText], ['在线状态', Number(detail.value.onlineStatus) === 1 ? '在线' : '离线'], ['关联维修单', detail.value.relatedOrderNo || detail.value.orderNo], ['维修状态', detail.value.workOrderStatusText || detail.value.status], ['状态更新时间', detail.value.statusUpdateTime]].map(([label, value]) => ({ label, value: value ?? '-' })))

async function loadData() { loading.value = true; try { let response; if (view === 'maintain') response = await listMaintainRecords({ ...query.value }); else if (view === 'dispatch' || view === 'abnormal') response = await listAbnormalDevices({ ...query.value }); else response = await listDeviceLedger({ ...query.value }); const normalized = normalizePage(response); page.value = { ...normalized, records: normalized.records.map(normalizeDeviceRow) } } catch (error) { page.value = { records: [], total: 0 }; console.warn(`[${title}] 数据加载失败`, error) } finally { loading.value = false } }
function reset() { query.value = { pageNum: 1, pageSize: 10, equipmentName: '', equipmentCode: '', alarmStatus: undefined, alertLevel: undefined }; loadData() }
function selectPoint(row) { detail.value = normalizeDeviceRow(row); detailVisible.value = true }
async function loadUsers() { if (users.value.length) return; userLoading.value = true; try { const response = await listUser({ pageNum: 1, pageSize: 200 }); users.value = response.rows || response.data?.rows || [] } catch (error) { ElMessage.error('责任人列表加载失败') } finally { userLoading.value = false } }
async function openOrder(row) { dispatchDevice.value = row; dispatchForm.value = { description: row.abnormalDescription || row.description || '', receiveUserId: undefined }; await loadUsers(); dispatchVisible.value = true }
async function submitDispatch() { if (!dispatchForm.value.description?.trim()) return ElMessage.warning('请填写问题描述'); if (!dispatchForm.value.receiveUserId) return ElMessage.warning('请选择接单责任人'); dispatching.value = true; try { await createAbnormalOrder(buildMaintainOrderPayload(dispatchDevice.value, dispatchForm.value)); ElMessage.success('维修派单已提交'); dispatchVisible.value = false; await loadData() } catch (error) { ElMessage.error('派单失败，请检查权限或服务状态') } finally { dispatching.value = false } }
async function removeRecord(row) { try { await deleteMaintainRecord(row.maintainId || row.id); ElMessage.success('记录已删除'); await loadData() } catch (error) { ElMessage.error('删除失败') } }
async function exportData() { try { await (view === 'dispatch' || view === 'abnormal' ? exportAbnormalDevices : exportDeviceLedger)({ ...query.value }); ElMessage.success('导出请求已提交') } catch (error) { ElMessage.error('导出失败') } }
onMounted(loadData)
</script>

<style scoped>
.device-page{padding:20px;background:#f5f7fa;min-height:calc(100vh - 84px)}.page-heading{display:flex;justify-content:space-between;align-items:center;margin-bottom:16px}.page-title{display:flex;gap:12px;align-items:center}.page-title h2{margin:0 0 5px;font-size:20px}.page-title-icon{display:grid;place-items:center;width:38px;height:38px;color:#2563eb;background:#eaf2ff;border-radius:8px}.muted{font-size:13px;color:#909399}.filter-card{margin-bottom:16px}.filter-card :deep(.el-form-item){margin-bottom:0}.card-title{display:flex;justify-content:space-between;align-items:center;font-weight:600;margin-bottom:14px}.el-pagination{justify-content:flex-end;margin-top:16px}.detail-summary{display:flex;align-items:center;gap:12px;margin-bottom:16px}.detail-name{font-size:18px;font-weight:700;color:#17324d}.device-detail-drawer :deep(.el-drawer__body){overflow:auto}.device-detail-drawer :deep(.el-descriptions__label){white-space:nowrap}.device-detail-drawer :deep(.el-descriptions__content){word-break:break-word;overflow-wrap:anywhere}
</style>
<style lang="scss">
@use './waterSupplyPageTheme.scss';
@media(max-width:768px){.device-detail-drawer{width:100%!important}}
</style>
