<template>
  <div class="app-container">
    <!-- 搜索框 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="auto">

      <el-form-item label="设备名称" prop="equipmentName">
        <el-input v-model="queryParams.equipmentName" placeholder="请输入设备名" clearable @keyup.enter="handleQuery"
          style="width: 110px;" />
      </el-form-item>
      <el-form-item label="设备地址" prop="address">
        <el-input v-model="queryParams.address" placeholder="请输入设备地址" clearable @keyup.enter="handleQuery"
          style="width: 123px;" type="number" />
      </el-form-item>
      <!-- <el-form-item label="单位类型" prop="unitType">
        <el-select v-model="queryParams.unitType" placeholder="请选择单位类型" clearable style="width: 145px;">
          <el-option v-for="dict in dcs_unit_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="数据类型" prop="dataType">
        <el-select v-model="queryParams.dataType" placeholder="请选择数据类型" clearable style="width: 145px;">
          <el-option v-for="dict in dcs_data_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <!-- 设备类型 -->
      <el-form-item label="设备类型" prop="equipmentType">
        <el-select v-model="queryParams.equipmentType" placeholder="请选择设备类型" clearable style="width: 145px;">
          <el-option v-for="dict in dcs_equipment_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <!-- 流程id -->
      <el-form-item label="流程" prop="flowId">
        <el-select v-model="queryParams.flowId" placeholder="请选择对应流程" clearable style="width: 150px;">
          <el-option v-for="dict in flowOptions" :key="dict.flowId" :label="dict.flowName" :value="dict.flowId" />
        </el-select>
      </el-form-item>
      <el-form-item label="设备标识" prop="equipmentCode">
        <el-input v-model="queryParams.equipmentCode" placeholder="请输入设备标识" clearable @keyup.enter="handleQuery"
          style="width: 130px;" />
      </el-form-item>
      <el-form-item label="寄存器类型" prop="registerCode">
        <el-select v-model="queryParams.registerCode" placeholder="请选择寄存器类型" clearable style="width: 165px;">
          <el-option v-for="dict in dcs_register_code" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </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" v-hasPermi="['dcs:equipment:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Sort" @click="toggleExpandAll">展开/折叠</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <!-- 表单列表 -->
    <el-table v-if="refreshTable" v-loading="loading" :data="equipmentList" row-key="equipmentId"
      :default-expand-all="isExpandAll" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
      <el-table-column label="设备名" prop="equipmentName" :show-overflow-tooltip="true" width="160" />
      <el-table-column label="设备地址" prop="address" />
      <!-- <el-table-column label="单位类型" align="center" prop="unitType">
        <template #default="scope">
          <dict-tag :options="dcs_unit_type" :value="scope.row.unitType" />
        </template>
</el-table-column>
<el-table-column label="数据类型" align="center" prop="dataType">
  <template #default="scope">
          <dict-tag :options="dcs_data_type" :value="scope.row.dataType" />
        </template>
</el-table-column> -->
      <el-table-column label="设备类型" align="center" prop="equipmentType">
        <template #default="scope">
          <dict-tag :options="dcs_equipment_type" :value="scope.row.equipmentType" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="父设备id" align="center" prop="parentsId" /> -->
      <!-- <el-table-column label="父设备id" align="center">
        <template v-slot:default="scope">
          <span v-if="scope.row.parentsId !== 0">{{ scope.row.parentsId }}</span>
          <span v-else></span>
        </template>
      </el-table-column> -->
      <el-table-column label="流程归属" align="center" prop="flowName" />
      <el-table-column label="设备标识" align="center" prop="equipmentCode" />
      <el-table-column label="寄存器类型" align="center" prop="registerCode">
        <template #default="scope">
          <dict-tag :options="dcs_register_code" :value="scope.row.registerCode" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="200">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['dcs:equipment:edit']">修改</el-button>
          <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)"
            v-hasPermi="['dcs:equipment:add']">新增</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['dcs:equipment:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页插件 -->
    <Pagination v-model:page="currentPage" v-model:limit="pageSize" :total="total" @pagination="getList" />

    <!-- 添加或修改设备管理对话框 -->
    <el-dialog :title="title" v-model="open" width="680px" append-to-body>
      <el-form ref="equipmentRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="父设备" prop="parentsId">
              <el-tree-select v-model="form.parentsId" :data="equipmentOptions"
                :props="{ value: 'equipmentId', label: 'equipmentName', children: 'children' }" value-key="equipmentId"
                placeholder="请选择父设备" check-strictly />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="设备类型" prop="equipmentType">
              <el-radio-group v-model="form.equipmentType">
                <el-radio v-for="dict in dcs_equipment_type" :key="dict.value" :value="dict.value">{{ dict.label
                }}</el-radio>
              </el-radio-group>
            </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" v-if="form.equipmentType == '2'">
            <el-form-item label="寄存器地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入寄存器地址" type="number" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.equipmentType == '2'">
            <el-form-item label="数据类型" prop="dataType">
              <el-select v-model="form.dataType" placeholder="请选择单位类型" clearable>
                <el-option v-for="dict in dcs_data_type" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item> </el-col>
          <el-col :span="12" v-if="form.equipmentType == '2'">
            <el-form-item label="寄存器类型" prop="registerCode">
              <el-select v-model="form.registerCode" placeholder="请选择寄存器类型" clearable>
                <el-option v-for="dict in dcs_register_code" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item> </el-col>
          <el-col :span="12" v-if="form.equipmentType == '2'">
            <el-form-item label="单位类型" prop="unitType">
              <el-select v-model="form.unitType" placeholder="请选择单位类型" clearable>
                <el-option v-for="dict in dcs_unit_type" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item> </el-col>
          <!-- <el-col :span="12"> <el-form-item label="设备类型" prop="equipmentType">
              <el-select v-model="form.equipmentType" placeholder="请选择设备类型" clearable>
                <el-option v-for="dict in dcs_equipment_type" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item> </el-col> -->
          <el-col :span="12">
            <el-form-item label="流程分配" prop="flowId" v-if="form.equipmentType == '1'">
              <el-select v-model="form.flowId" multiple placeholder="请选择对应流程" clearable>
                <el-option v-for="dict in flowOptions" :key="dict.flowId" :label="dict.flowName"
                  :value="dict.flowId"></el-option>
              </el-select>
            </el-form-item> </el-col>

          <el-col :span="12">
            <el-form-item label="设备标识" prop="equipmentCode">
              <el-input v-model="form.equipmentCode" 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>
  </div>
</template>

<script setup name="Equipment">
import { listEquipment, getEquipment, delEquipment, addEquipment, updateEquipment } from "@/api/dcs/equipment";
import { getFlowList} from "@/api/dcs/flow";
import { onMounted } from "vue";

onMounted(() => {
  getFlowOptions();
});
const { proxy } = getCurrentInstance();
const { dcs_register_code, dcs_unit_type, dcs_data_type, dcs_equipment_type } = proxy.useDict('dcs_register_code', 'dcs_unit_type', 'dcs_data_type', 'dcs_equipment_type');

const equipmentList = ref([]);
const equipmentOptions = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const title = ref("");
const isExpandAll = ref(false);//是否展开所有节点
const refreshTable = ref(true);

const data = reactive({
  form: {},
  queryParams: {
    // pageNum: 1,
    // pageSize: 10,
    address: null,
    equipmentName: null,
    unitType: null,
    dataType: null,
    equipmentType: null,
    parentsId: null,
    flowId: null,
    equipmentCode: null,
    registerCode: null
  },
  rules: {
    equipmentName: [
      { required: true, message: "请输入设备名", trigger: "blur" },
      { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" }
    ],
    flowId: [
      { required: true, message: "请选择对应流程", trigger: "blur" }
    ],
    address: [
      // 限定范围0-65535
      {
        validator: (rule, value, callback) => {
          if (value && (value < 0 || value > 65535)) {
            callback(new Error("请输入0-65535之间的数字"));
          } else {
            callback();
          }
        }, trigger: "blur"
      }
    ],
    equipmentCode: [
      { validator: genericRequiredValidator('equipmentCode', '请填写对应设备标识'), trigger: "blur" }
    ],
    registerCode: [
      { validator: genericRequiredValidator('registerCode', '请选择对应寄存器类型'), trigger: "blur" }
    ],
    unitType: [
      { validator: genericRequiredValidator('unitType', '请填写对应单位类型'), trigger: "blur" }
    ],
    dataType: [
      { validator: genericRequiredValidator('dataType', '请填写对应数据类型'), trigger: "blur" }
    ],
    equipmentType: [
      { required: true, message: "请选择设备类型", trigger: "blur" }
    ]
  }
});
//自定义验证器
function genericRequiredValidator(field, message) {
  return (rule, value, callback) => {
    if (data.form.parentsId !== 0 && !value) {
      callback(new Error(message));
    } else {
      callback();
    }
  };
}
const { queryParams, form, rules } = toRefs(data);
const flowOptions = ref([]);// 流程下拉树结构
/** 获取流程列表 */
function getFlowOptions() {
  getFlowList().then(response => {
    flowOptions.value = response.data;
  });
}

const currentPage = ref(1);//当前页
const pageSize = ref(10);//每页条数
const total = ref(0);

/** 查询设备管理列表 */
// function getList() {
//   loading.value = true;
//   listEquipment(queryParams.value).then(response => {
//     equipmentList.value = proxy.handleTree(response.data, "equipmentId", "parentsId");
//     loading.value = false;
//     // console.log(equipmentList.value);
//   });
// }

//获取设备管理列表（树状，分页）
function getList() {
  loading.value = true;
  listEquipment(queryParams.value).then(response => {
    handleTreeData(response.data);
    loading.value = false;
  });
}

//对拿到的数据进行树状结构转换，并分页处理
function handleTreeData(data) {
  const allData = data
  const equipmentMap = {}
  allData.forEach(item => {
    equipmentMap[item.equipmentId] = item
  })

  // 1. 找到命中的根节点
  const matchedRoots = new Map()
  allData.forEach(item => {
    if (!queryParams.value.equipmentName || item.equipmentName.includes(queryParams.value.equipmentName)) {
      const root = findRoot(equipmentMap, item)
      matchedRoots.set(root.equipmentId, root)
    }
  })

  const rootList = Array.from(matchedRoots.values())
  total.value = rootList.length

  // 2. 分页根节点
  const pagedRoots = rootList.slice(
    (currentPage.value - 1) * pageSize.value,
    currentPage.value * pageSize.value
  )

  const rootIds = pagedRoots.map(item => item.equipmentId)

  // 3. 构建要展示的数据
  const filteredData = allData.filter(item => {
    let current = item
    while (current.parentsId && equipmentMap[current.parentsId]) {
      current = equipmentMap[current.parentsId]
    }
    return rootIds.includes(current.equipmentId)
  })

  // 4. 构建树结构
  equipmentList.value = proxy.handleTree(filteredData, 'equipmentId', 'parentsId')
}

/** 递归获取顶级父节点 */
function findRoot(equipmentMap, node) {
  while (node.parentsId && equipmentMap[node.parentsId]) {
    node = equipmentMap[node.parentsId]
  }
  return node
}

/** 查询设备管理下拉树结构 */
function getTreeselect() {
  listEquipment().then(response => {
    equipmentOptions.value = [];
    const data = { equipmentId: 0, equipmentName: '顶级节点', children: [] };
    data.children = proxy.handleTree(response.data, "equipmentId", "parentsId");
    equipmentOptions.value.push(data);
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    equipmentId: null,
    address: null,
    equipmentName: null,
    unitType: null,
    dataType: null,
    equipmentType: "1",
    parentsId: null,
    flowId: null,
    equipmentCode: null,
    registerCode: null
  };
  proxy.resetForm("equipmentRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  currentPage.value = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd(row) {
  // console.log("新增按钮操作",form.value);
  reset();
  getTreeselect();
  if (row != null && row.equipmentId) {
    form.value.parentsId = row.equipmentId;
  } else {
    form.value.parentsId = 0;
  }
  open.value = true;
  title.value = "添加设备管理";
}

/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();
  await getTreeselect();
  if (row != null) {
    form.value.parentsId = row.parentsId;
  }
  getEquipment(row.equipmentId).then(response => {
    form.value = response.data;
    //字符串转整型数组
    if (form.value.flowId) {
      form.value.flowId = form.value.flowId.split(',').map(Number);
    }
    open.value = true;
    title.value = "修改设备管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["equipmentRef"].validate(valid => {
    // console.log(form.value);
    if (valid) {
      if (form.value.flowId) {
        //数组转字符串
        form.value.flowId = form.value.flowId.join(',');
      }
      if (form.value.equipmentId != null) {
        updateEquipment(form.value).then(response => {
          console.log(response);
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        }).catch(error => {
          form.value.flowId = form.value.flowId.split(',').map(Number);
        });
      } else {
        addEquipment(form.value).then(response => {
          console.log(response);
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }).catch(error => {
          form.value.flowId = form.value.flowId.split(',').map(Number);
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除设备管理编号为"' + row.equipmentId + '"的数据项？').then(function () {
    return delEquipment(row.equipmentId);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

getList();
</script>
<style lang="scss" scoped>
.option_col {
  min-width: 200px;
}
</style>
