<!-- 物联感知设备管理 -->
<template>
  <div class="app-container">
    <el-form ref="queryRef" :model="queryParams" :inline="true" v-show="showSearch">
      <el-form-item label="设备编码" prop="equipmentCode">
        <el-input
          v-model="queryParams.equipmentCode"
          placeholder="请输入设备编码"
          clearable
          style="width: 220px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备名称" prop="equipmentName">
        <el-input
          v-model="queryParams.equipmentName"
          placeholder="请输入设备名称"
          clearable
          style="width: 220px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备型号" prop="equipmentModel">
        <el-input
          v-model="queryParams.equipmentModel"
          placeholder="请输入设备型号"
          clearable
          style="width: 220px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="制造商" prop="manufacturer">
        <el-input
          v-model="queryParams.manufacturer"
          placeholder="请输入制造商"
          clearable
          style="width: 220px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()">
          修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()">
          删除
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="equipmentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="设备编码" align="center" prop="equipmentCode" min-width="140" />
      <el-table-column label="设备名称" align="center" prop="equipmentName" min-width="160" show-overflow-tooltip />
      <el-table-column label="设备型号" align="center" prop="equipmentModel" min-width="120" />
      <el-table-column label="设备类型" align="center" min-width="140">
        <template #default="scope">
          {{ typeNameMap[scope.row.equipmentTypeId] || scope.row.equipmentTypeId || "-" }}
        </template>
      </el-table-column>
      <el-table-column label="当前状态" align="center" width="110">
        <template #default="scope">
          <el-tag :type="getStatusTagType(getRowStatus(scope.row.equipmentId))">
            {{ getStatusText(getRowStatus(scope.row.equipmentId)) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="制造商" align="center" prop="manufacturer" min-width="140" show-overflow-tooltip />
      <el-table-column label="设备位置" align="center" prop="equipmentLocation" min-width="180" show-overflow-tooltip />
      <el-table-column label="维护人员" align="center" prop="maintainer" min-width="100" />
      <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleView(scope.row)">详情</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="warning" icon="Tools" @click="openStatusDialog(scope.row)">状态维护</el-button>
          <el-button link type="success" icon="Aim" @click="openTestDialog(scope.row)">测试验证</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="title" v-model="open" width="860px" append-to-body>
      <el-form ref="equipmentRef" :model="form" :rules="rules" label-width="110px">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="设备编码" prop="equipmentCode">
              <el-input v-model="form.equipmentCode" placeholder="请输入设备编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备名称" prop="equipmentName">
              <el-input v-model="form.equipmentName" placeholder="请输入设备名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备型号" prop="equipmentModel">
              <el-input v-model="form.equipmentModel" placeholder="请输入设备型号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备类型" prop="equipmentTypeId">
              <el-select v-model="form.equipmentTypeId" placeholder="请选择设备类型" style="width: 100%">
                <el-option
                  v-for="item in equipmentTypeOptions"
                  :key="item.typeId"
                  :label="item.typeName"
                  :value="item.typeId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="制造商" prop="manufacturer">
              <el-input v-model="form.manufacturer" placeholder="请输入制造商" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生产日期" prop="productionDate">
              <el-date-picker
                v-model="form.productionDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择生产日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="规格参数" prop="equipmentSpec">
              <el-input v-model="form.equipmentSpec" placeholder="请输入设备规格参数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资产价值(元)" prop="assetValue">
              <el-input-number v-model="form.assetValue" :precision="2" :step="100" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="使用年限(年)" prop="useLife">
              <el-input-number v-model="form.useLife" :precision="0" :step="1" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="设备位置" prop="equipmentLocation">
              <el-input v-model="form.equipmentLocation" placeholder="请输入设备位置" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经度" prop="longitude">
              <el-input-number v-model="form.longitude" :precision="6" :step="0.000001" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纬度" prop="latitude">
              <el-input-number v-model="form.latitude" :precision="6" :step="0.000001" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="安装时间" prop="installTime">
              <el-date-picker
                v-model="form.installTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择安装时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="维护人员" prop="maintainer">
              <el-input v-model="form.maintainer" placeholder="请输入维护人员" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="maintainerPhone">
              <el-input v-model="form.maintainerPhone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="设备详情" v-model="detailOpen" width="980px" append-to-body>
      <el-descriptions :column="2" border v-if="detailForm.equipmentInfo">
        <el-descriptions-item label="设备编码">{{ detailForm.equipmentInfo.equipmentCode || "-" }}</el-descriptions-item>
        <el-descriptions-item label="设备名称">{{ detailForm.equipmentInfo.equipmentName || "-" }}</el-descriptions-item>
        <el-descriptions-item label="设备型号">{{ detailForm.equipmentInfo.equipmentModel || "-" }}</el-descriptions-item>
        <el-descriptions-item label="设备类型">{{ detailForm.typeInfo?.typeName || "-" }}</el-descriptions-item>
        <el-descriptions-item label="制造商">{{ detailForm.equipmentInfo.manufacturer || "-" }}</el-descriptions-item>
        <el-descriptions-item label="当前状态">{{ getStatusText(detailForm.statusInfo?.currentStatus) }}</el-descriptions-item>
        <el-descriptions-item label="设备位置" :span="2">{{ detailForm.equipmentInfo.equipmentLocation || "-" }}</el-descriptions-item>
        <el-descriptions-item label="规格参数" :span="2">{{ detailForm.equipmentInfo.equipmentSpec || "-" }}</el-descriptions-item>
        <el-descriptions-item label="维护人员">{{ detailForm.equipmentInfo.maintainer || "-" }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ detailForm.equipmentInfo.maintainerPhone || "-" }}</el-descriptions-item>
        <el-descriptions-item label="安装时间">{{ detailForm.equipmentInfo.installTime || "-" }}</el-descriptions-item>
        <el-descriptions-item label="生产日期">{{ detailForm.equipmentInfo.productionDate || "-" }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ detailForm.equipmentInfo.remark || "-" }}</el-descriptions-item>
      </el-descriptions>

      <el-divider content-position="left">关联监测点</el-divider>
      <el-table :data="detailForm.pointRelList || []" border>
        <el-table-column label="监测点ID" prop="pointId" min-width="200" show-overflow-tooltip />
        <el-table-column label="设备ID" prop="equipmentId" min-width="200" show-overflow-tooltip />
      </el-table>

      <el-divider content-position="left">测试记录</el-divider>
      <el-table :data="detailForm.testList || []" border>
        <el-table-column label="测试时间" prop="testTime" min-width="170" />
        <el-table-column label="测试类型" prop="testType" min-width="120" />
        <el-table-column label="测试结果" prop="testResult" width="100" />
        <el-table-column label="测试人员" prop="testUser" width="120" />
        <el-table-column label="测试详情" prop="testDetail" min-width="220" show-overflow-tooltip />
      </el-table>
    </el-dialog>

    <el-dialog title="设备状态维护" v-model="statusOpen" width="420px" append-to-body>
      <el-form label-width="90px">
        <el-form-item label="设备名称">
          <span>{{ currentRow.equipmentName || "-" }}</span>
        </el-form-item>
        <el-form-item label="当前状态">
          <el-select v-model="statusForm.currentStatus" style="width: 100%">
            <el-option
              v-for="item in equipmentStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitStatus">确 定</el-button>
          <el-button @click="statusOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="设备测试验证" v-model="testOpen" width="520px" append-to-body>
      <el-form ref="testRef" :model="testForm" label-width="90px">
        <el-form-item label="设备名称">
          <span>{{ currentRow.equipmentName || "-" }}</span>
        </el-form-item>
        <el-form-item label="测试类型">
          <el-input v-model="testForm.testType" placeholder="例如：通信测试" />
        </el-form-item>
        <el-form-item label="测试人员">
          <el-input v-model="testForm.testUser" placeholder="请输入测试人员" />
        </el-form-item>
        <el-form-item label="测试详情">
          <el-input v-model="testForm.testDetail" type="textarea" :rows="4" placeholder="请输入测试详情" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitTest">确 定</el-button>
          <el-button @click="testOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { computed, getCurrentInstance, onMounted, reactive, ref, toRefs } from "vue";
import {
  addEquipment,
  delEquipment,
  getEquipment,
  getEquipmentDetail,
  listEquipment,
  listEquipmentStatusAll,
  listEquipmentTypeAll,
  testEquipment,
  updateEquipment,
  updateEquipmentStatus
} from "@/api/pipeNetwork/pdeviceInform";

const { proxy } = getCurrentInstance();

const equipmentList = ref([]);
const equipmentTypeOptions = ref([]);
const equipmentStatusList = ref([]);
const loading = ref(false);
const open = ref(false);
const detailOpen = ref(false);
const statusOpen = ref(false);
const testOpen = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const currentRow = ref({});

const equipmentStatusOptions = [
  { label: "在用", value: 1 },
  { label: "闲置", value: 2 },
  { label: "维修", value: 3 },
  { label: "报废", value: 4 },
  { label: "待入库", value: 5 }
];

const typeNameMap = computed(() => {
  return equipmentTypeOptions.value.reduce((acc, item) => {
    acc[item.typeId] = item.typeName;
    return acc;
  }, {});
});

const statusMap = computed(() => {
  return equipmentStatusList.value.reduce((acc, item) => {
    acc[item.equipmentId] = item;
    return acc;
  }, {});
});

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    equipmentCode: undefined,
    equipmentName: undefined,
    equipmentModel: undefined,
    manufacturer: undefined
  },
  form: {},
  detailForm: {},
  statusForm: {
    currentStatus: 1
  },
  testForm: {
    testType: undefined,
    testDetail: undefined,
    testUser: undefined
  },
  rules: {
    equipmentCode: [{ required: true, message: "设备编码不能为空", trigger: "blur" }],
    equipmentName: [{ required: true, message: "设备名称不能为空", trigger: "blur" }],
    equipmentTypeId: [{ required: true, message: "设备类型不能为空", trigger: "change" }]
  }
});

const { queryParams, form, detailForm, statusForm, testForm, rules } = toRefs(data);

function createEmptyForm() {
  return {
    equipmentId: undefined,
    equipmentCode: undefined,
    equipmentName: undefined,
    equipmentModel: undefined,
    equipmentSpec: undefined,
    manufacturer: undefined,
    productionDate: undefined,
    equipmentTypeId: undefined,
    assetValue: undefined,
    useLife: undefined,
    longitude: undefined,
    latitude: undefined,
    equipmentLocation: undefined,
    installTime: undefined,
    maintainer: undefined,
    maintainerPhone: undefined,
    remark: undefined
  };
}

function getRowStatus(equipmentId) {
  return statusMap.value[equipmentId]?.currentStatus;
}

function getStatusText(status) {
  const found = equipmentStatusOptions.find((item) => item.value === status);
  return found?.label || "未维护";
}

function getStatusTagType(status) {
  const map = {
    1: "success",
    2: "info",
    3: "warning",
    4: "danger",
    5: ""
  };
  return map[status] || "";
}

function getList() {
  loading.value = true;
  listEquipment(queryParams.value)
    .then((response) => {
      equipmentList.value = response.records || [];
      total.value = response.total || 0;
    })
    .finally(() => {
      loading.value = false;
    });
}

function loadAssistData() {
  return Promise.all([listEquipmentTypeAll(), listEquipmentStatusAll()]).then(([typeRes, statusRes]) => {
    equipmentTypeOptions.value = typeRes.data || [];
    equipmentStatusList.value = statusRes.data || [];
  });
}

function reset() {
  form.value = createEmptyForm();
  proxy.resetForm("equipmentRef");
}

function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.equipmentId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

function handleAdd() {
  reset();
  open.value = true;
  title.value = "新增物联感知设备";
}

function handleUpdate(row) {
  reset();
  const equipmentId = row?.equipmentId || ids.value[0];
  if (!equipmentId) {
    return;
  }
  getEquipment(equipmentId).then((response) => {
    form.value = { ...createEmptyForm(), ...(response.data || {}) };
    open.value = true;
    title.value = "修改物联感知设备";
  });
}

function handleView(row) {
  getEquipmentDetail(row.equipmentId).then((response) => {
    detailForm.value = response.data || {};
    detailOpen.value = true;
  });
}

function cancel() {
  open.value = false;
  reset();
}

function submitForm() {
  proxy.$refs.equipmentRef.validate((valid) => {
    if (!valid) {
      return;
    }
    const request = form.value.equipmentId ? updateEquipment(form.value) : addEquipment(form.value);
    request.then(() => {
      proxy.$modal.msgSuccess(form.value.equipmentId ? "修改成功" : "新增成功");
      open.value = false;
      Promise.all([getList(), loadAssistData()]);
    });
  });
}

function handleDelete(row) {
  const deleteIds = row?.equipmentId ? [row.equipmentId] : ids.value;
  if (!deleteIds.length) {
    return;
  }
  proxy.$modal
    .confirm(`是否确认删除选中的 ${deleteIds.length} 台设备？`)
    .then(() => Promise.all(deleteIds.map((id) => delEquipment(id))))
    .then(() => {
      proxy.$modal.msgSuccess("删除成功");
      Promise.all([getList(), loadAssistData()]);
    });
}

function openStatusDialog(row) {
  currentRow.value = row;
  statusForm.value.currentStatus = getRowStatus(row.equipmentId) || 1;
  statusOpen.value = true;
}

function submitStatus() {
  updateEquipmentStatus(currentRow.value.equipmentId, statusForm.value.currentStatus).then(() => {
    proxy.$modal.msgSuccess("状态维护成功");
    statusOpen.value = false;
    loadAssistData();
  });
}

function openTestDialog(row) {
  currentRow.value = row;
  testForm.value = {
    testType: "通信测试",
    testDetail: undefined,
    testUser: undefined
  };
  testOpen.value = true;
}

function submitTest() {
  testEquipment(currentRow.value.equipmentId, testForm.value).then(() => {
    proxy.$modal.msgSuccess("测试记录已提交");
    testOpen.value = false;
    if (detailOpen.value && detailForm.value?.equipmentInfo?.equipmentId === currentRow.value.equipmentId) {
      handleView(currentRow.value);
    }
  });
}

onMounted(() => {
  reset();
  Promise.all([getList(), loadAssistData()]);
});
</script>
