<template>
  <div class="p-2">
    <el-row :gutter="10">
      <el-col :span="5">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>分项系统</span>
              <el-icon color="#409EFF" @click="addSystem">
                <Plus />
              </el-icon>
            </div>
          </template>
          <div>
            <el-input v-model="filterText" style="width: 200px" placeholder="请输入关键字" />
            <el-tree ref="treeRef" style="max-width: 600px; margin-top: 5px" class="filter-tree" :props="defaultProps"
              :data="treeData" node-key="id" default-expand-all highlight-current :expand-on-click-node="false"
              :filter-node-method="filterNode" @node-click="handleNodeClick">
              <template #default="{ node, data }">
                <div class="custom-tree-node">
                  <span>{{ node.label }}</span>
                  <el-popover placement="bottom" :popper-style="{ 'width': '70px', 'min-width': '70px' }"
                    trigger="click">
                    <div class="node-operateBtns">
                      <div @click="addSystem(data)">新增</div>
                      <div @click="editSystem(node, data)">编辑</div>
                      <div @click="delSystem(node, data)">删除</div>
                    </div>
                    <template #reference>
                      <el-icon>
                        <Setting />
                      </el-icon>
                    </template>
                  </el-popover>
                </div>
              </template>
            </el-tree>
          </div>
        </el-card>
      </el-col>
      <el-col :span="19">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
          :leave-active-class="proxy?.animate.searchAnimate.leave">
          <div v-show="showSearch" class="mb-[10px]">
            <el-card shadow="hover">
              <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="100px">
                <el-form-item label="设备类型名称" prop="name">
                  <el-input v-model="queryParams.name" placeholder="请输入设备类型名称" clearable @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-card>
          </div>
        </transition>

        <el-card shadow="never">
          <template #header>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button v-hasPermi="['jdyw:deviceType:add']" type="primary" plain icon="Plus" @click="handleAdd"> 新增
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button v-hasPermi="['jdyw:deviceType:edit']" type="success" plain icon="Edit" :disabled="single"
                  @click="handleUpdate">
                  修改
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button v-hasPermi="['jdyw:deviceType:remove']" type="danger" plain icon="Delete"
                  :disabled="multiple" @click="handleDelete">
                  删除
                </el-button>
              </el-col>
              <right-toolbar v-model:showSearch="showSearch" @query-table="getList" />
            </el-row>
          </template>

          <el-table v-loading="loading" :data="deviceTypeList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="设备类型名称" align="center" prop="name" />
            <el-table-column label="设备等级" align="center" prop="deviceLevel" />
            <el-table-column label="分项系统" align="center" show-overflow-tooltip prop="ext1.systemName" />
            <el-table-column label="备注" align="center" prop="remark" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-button v-hasPermi="['jdyw:deviceType:edit']" size="small" link type="primary"
                  @click="handleUpdate(scope.row)">修改</el-button>
                <el-button v-hasPermi="['jdyw:deviceType:edit']" size="small" link type="primary"
                  @click="handleModel(scope.row)">物模型</el-button>
                <el-button v-hasPermi="['jdyw:deviceType:remove']" size="small" link type="danger"
                  @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
            :total="total" @pagination="getList" />
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加或修改设备类型信息对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" append-to-body>
      <el-form ref="deviceTypeFormRef" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="设备类型名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入设备类型名称" />
        </el-form-item>
        <el-form-item label="设备等级" prop="deviceLevel">
          <el-select v-model="form.deviceLevel" placeholder="请选择设备等级">
            <el-option v-for="dict in device_level" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分项系统" prop="systemId">
          <el-tree-select v-model="form.systemId" :props="defaultProps" node-key="id" :data="treeData" default-expand-all
            :check-strictly="true" :render-after-expand="false" @change="getSystemName" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm"> 确 定 </el-button>
          <el-button @click="cancel"> 取 消 </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="systemDialog.visible" :title="systemDialog.title" width="500px" append-to-body>
      <el-form ref="deviceSystemFormRef" :model="systemForm" label-width="120px">
        <el-form-item label="上级分项系统" prop="parentName" required>
          <el-input v-model="systemForm.parentName" disabled placeholder="请选择上级分项系统" />
        </el-form-item>
        <el-form-item label="系统名称" prop="name" required :rules="[{ required: true, message: '请输入系统名称' }]">
          <el-input v-model="systemForm.name" placeholder="请输入系统名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitSystemForm"> 确 定 </el-button>
          <el-button @click="systemDialog.visible = false"> 取 消 </el-button>
        </div>
      </template>
    </el-dialog>
    <el-drawer v-model="rightDrawer" size="70%" class="customDrawer">
      <template #header>
        <div class="drawer-title">
          <div class="title-name">物模型</div>
          <el-descriptions style="margin-top: 10px" direction="vertical" title="" :column="4" border>
            <el-descriptions-item label="设备名称">{{ curRow.name }}</el-descriptions-item>
            <el-descriptions-item label="分项系统">{{ curRow.ext1&&curRow.ext1.systemName}}</el-descriptions-item>
            <el-descriptions-item label="设备等级">{{ curRow.deviceLevel }}</el-descriptions-item>
          </el-descriptions>
        </div>
      </template>
      <el-tabs v-model="activeName" class="demo-tabs">
        <el-tab-pane label="属性定义" name="dataPoints">
          <el-button size="small" type="primary" @click="addModel">新增</el-button>
          <el-table :data="modelData.dataPoints" style="margin-top: 10px">
            <el-table-column label="属性" align="center" prop="name" />
            <el-table-column label="属性值" align="center" prop="value" />
            <el-table-column label="单位" align="center" prop="unit" />
            <el-table-column label="描述" align="center" prop="remark" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-button size="small" link type="primary" @click="editModel(scope.$index)">修改</el-button>
                <el-button size="small" link type="danger" @click="delModel(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="能力定义" name="controlFuncs">
          <el-button size="small" type="primary" @click="addModel">新增</el-button>
          <el-table :data="modelData.controlFuncs" style="margin-top: 10px">
            <el-table-column label="能力名称" align="center" prop="name" />
            <el-table-column label="下发参数" align="center" prop="value" />
            <el-table-column label="描述" align="center" prop="remark" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-button size="small" link type="primary" @click="editModel(scope.$index)">修改</el-button>
                <el-button size="small" link type="danger" @click="delModel(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="事件定义" name="events">
          <el-button size="small" type="primary" @click="addModel">新增</el-button>
          <el-table :data="modelData.events" style="margin-top: 10px">
            <el-table-column label="事件名称" align="center" prop="name" />
            <el-table-column label="事件类型" align="center" prop="type" />
            <el-table-column label="事件代码" align="center" prop="code" />
            <el-table-column label="外部事件代码" align="center" prop="outerCode" />
            <el-table-column label="描述" align="center" prop="remark" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-button size="small" link type="primary" @click="editModel(scope.$index)">修改</el-button>
                <el-button size="small" link type="danger" @click="delModel(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-drawer>
    <el-dialog v-model="modelDialog.visible" :title="modelDialog.title" width="500px" append-to-body>
      <el-form v-if="activeName == 'dataPoints'" ref="modelFormRef" :model="modelData.dataPointsForm"
        label-width="120px">
        <el-form-item label="属性名称" prop="name" :rules="[{ required: true, message: '请输入属性名称' }]">
          <el-input v-model="modelData.dataPointsForm.name" placeholder="请输入属性名称" />
        </el-form-item>
        <el-form-item label="属性值" prop="value" :rules="[{ required: true, message: '请输入属性值' }]">
          <el-input v-model="modelData.dataPointsForm.value" placeholder="请输入属性值" />
        </el-form-item>
        <el-form-item label="单位" prop="unit" :rules="[{ required: true, message: '请输入单位' }]">
          <el-input v-model="modelData.dataPointsForm.unit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="描述" prop="remark">
          <el-input v-model="modelData.dataPointsForm.remark" placeholder="请输入描述" />
        </el-form-item>
      </el-form>
      <el-form v-else-if="activeName == 'controlFuncs'" ref="modelFormRef" :model="modelData.controlFuncsForm"
        label-width="120px">
        <el-form-item label="能力名称" prop="name" :rules="[{ required: true, message: '请输入能力名称' }]">
          <el-input v-model="modelData.controlFuncsForm.name" placeholder="请输入能力名称" />
        </el-form-item>
        <el-form-item label="下发参数" prop="value" :rules="[{ required: true, message: '请输入下发参数' }]">
          <el-input v-model="modelData.controlFuncsForm.value" placeholder="请输入下发参数" />
        </el-form-item>
        <el-form-item label="描述" prop="remark">
          <el-input v-model="modelData.controlFuncsForm.unit" placeholder="请输入描述" />
        </el-form-item>
      </el-form>
      <el-form v-else-if="activeName == 'events'" ref="modelFormRef" :model="modelData.eventsForm" label-width="120px">
        <el-form-item label="事件名称" prop="name" :rules="[{ required: true, message: '请输入事件名称' }]">
          <el-input v-model="modelData.eventsForm.name" placeholder="请输入事件名称" />
        </el-form-item>
        <el-form-item label="事件类型" prop="type" :rules="[{ required: true, message: '请输入事件类型' }]">
          <el-input v-model="modelData.eventsForm.type" placeholder="请输入事件类型" />
        </el-form-item>
        <el-form-item label="事件代码" prop="code" :rules="[{ required: true, message: '请输入事件代码' }]">
          <el-input v-model="modelData.eventsForm.code" placeholder="请输入事件代码" />
        </el-form-item>
        <el-form-item label="外部事件代码" prop="outerCode" :rules="[{ required: true, message: '请输入外部事件代码' }]">
          <el-input v-model="modelData.eventsForm.outerCode" placeholder="请输入外部事件代码" />
        </el-form-item>
        <el-form-item label="描述" prop="remark">
          <el-input v-model="modelData.eventsForm.remark" placeholder="请输入描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitModelForm"> 确 定 </el-button>
          <el-button @click="modelDialog.visible = false"> 取 消 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="DeviceType" lang="ts">
import {
  listDeviceType,
  getDeviceType,
  delDeviceType,
  addDeviceType,
  updateDeviceType,
  getDeviceSystemTree,
  addDeviceSystem,
  editDeviceSystem,
  delDeviceSystem,
  addModels,
  editModels,
  getModels
} from '@/api/deviceManage/deviceType';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const deviceTypeList = ref([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const queryFormRef = ref<ElFormInstance>();
const deviceTypeFormRef = ref<ElFormInstance>();
const deviceSystemFormRef = ref<ElFormInstance>();
const modelFormRef = ref<ElFormInstance>();
const filterText = ref('');
const treeRef = ref<ElTreeInstance>();
const filterNode = (value: string, data) => {
  if (!value) return true;
  return data.name.includes(value);
};
watch(filterText, (val) => {
  treeRef.value!.filter(val);
});
const defaultProps = {
  children: 'children',
  label: 'name'
};
const treeData = ref([]);
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const systemDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const { device_level } = toRefs<any>(proxy?.useDict('device_level'));
const rightDrawer = ref(false);
const curRow = ref<any>({});
const activeName = ref('dataPoints');
const systemForm = reactive({
  id: '',
  name: '',
  parentId: 0,
  parentName: ''
});

const modelData = reactive<any>({
  id: '',
  name: '',
  dataPoints: [],
  controlFuncs: [],
  events: [],
  dataPointsForm: {
    name: '',
    value: '',
    unit: '',
    remark: ''
  },
  controlFuncsForm: {
    name: '',
    value: '',
    remark: ''
  },
  eventsForm: {
    name: '',
    type: '',
    code: '',
    outerCode: '',
    remark: ''
  }
});
const editIndex = ref(null);
const modelDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const initFormData = {
  id: undefined,
  name: undefined,
  deviceLevel: undefined,
  systemId: null,
  modeId: undefined,
  remark: undefined,
  ext1: {
    systemName:'',
  },
  ext2: undefined
};
const formData = reactive({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    systemId: undefined,
    params: {}
  },
  rules: {
    name: [{ required: true, message: '设备类型名称不能为空', trigger: 'blur' }],
    deviceLevel: [{ required: true, message: '设备等级不能为空', trigger: 'change' }],
    systemId: [{ required: true, message: '分项系统不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(formData);

/** 查询设备类型信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listDeviceType(queryParams.value);
  deviceTypeList.value = res.rows.map((item) => ({
    ...item,
    ext1: item.ext1 ? JSON.parse(item.ext1) : {}
  }));;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  deviceTypeFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '新增设备类型信息';
};

/** 修改按钮操作 */
const handleUpdate = async (row) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getDeviceType(_id);
  res.data.ext1 = JSON.parse(res.data.ext1||'{}');
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改设备类型信息';
};

/** 提交按钮 */
const submitForm = () => {
  deviceTypeFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      const { ext1 } = form.value;
      const params = Object.assign(form.value, { ext1: JSON.stringify(ext1) });
      if (form.value.id) {
        await updateDeviceType(params).finally(() => (buttonLoading.value = false));
      } else {
        await addDeviceType(params).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除设备类型信息编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delDeviceType(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

const getTreeData = async () => {
  getDeviceSystemTree({}).then(({ code, rows }) => {
    if (code === 200) {
      treeData.value = convertToTree(rows);
      if (treeData.value.length === 0) {
        treeData.value = [];
      }
    }
  });
};
const convertToTree = (list) => {
  let map = new Map();
  let root = [];
  for (let item of list) {
    map.set(item.id, { ...item });
  }
  for (let item of list) {
    if (item.parentId !== 0) {
      let parent = map.get(item.parentId);
      if (!parent.children) {
        parent.children = [];
      }
      parent.children.push(map.get(item.id));
    } else {
      root.push(map.get(item.id));
    }
  }
  return root;
};
const findNameWithParents = (data, idToFind, parentName = '') => {
  for (let item of data) {
    let fullName = parentName ? `${parentName}/${item.name}` : item.name;
    if (item.id === idToFind) {
      return fullName;
    }
    if (item.children && Array.isArray(item.children)) {
      let result = findNameWithParents(item.children, idToFind, fullName);
      if (result) {
        return result;
      }
    }
  }
  return null; // 如果没有找到对应的 ID，则返回 null
};
const getSystemName = (val) => {
  form.value.ext1.systemName = findNameWithParents(treeData.value, val, '')
}
const addSystem = (data) => {
  systemDialog.visible = true;
  systemDialog.title = '新增分项系统';
  deviceSystemFormRef.value?.resetFields();
  Object.keys(systemForm).forEach((key) => {
    systemForm[key] = '';
  });
  if (data.name) {
    systemForm.parentName = data.name;
    systemForm.parentId = data.id;
  } else {
    systemForm.parentName = '根节点';
    systemForm.parentId = 0;
  }
};
const editSystem = (node, data) => {
  systemDialog.visible = true;
  systemDialog.title = '修改分项系统';
  deviceSystemFormRef.value?.resetFields();
  Object.keys(systemForm).forEach((key) => {
    systemForm[key] = data[key];
  });
  if (data.parentId === 0) {
    systemForm.parentName = '根节点';
  } else {
    systemForm.parentName = node.parent.data.name;
  }
};
const delSystem = async (node, data) => {
  if (node.childNodes.length) return proxy?.$modal.msgWarning('存在子节点，请先删除子节点');
  await delDeviceSystem(data.id);
  proxy?.$modal.msgSuccess('删除成功');
  await getTreeData();
};
const handleNodeClick = (data, node) => {
  queryParams.value.systemId = data.id;
  handleQuery();
};
const submitSystemForm = () => {
  deviceSystemFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (systemForm.id) {
        await editDeviceSystem(systemForm).finally(() => (buttonLoading.value = false));
      } else {
        await addDeviceSystem(systemForm).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      systemDialog.visible = false;
      await getTreeData();
    }
  });
};
const resetModelData = () => {
  modelData.id=''
  modelData.name=''
  modelData.dataPoints=[]
  modelData.controlFuncs=[]
  modelData.events=[]
}
const handleModel = (row) => {
  rightDrawer.value = true;
  curRow.value = row;
  resetModelData();
  if (row.modeId) {
    getModels(row.modeId).then(({ code, data }) => {
      if (code === 200) {
        modelData.id = data.id;
        modelData.name = data.name;
        modelData.dataPoints = JSON.parse(data.dataPoints || '[]');
        modelData.controlFuncs = JSON.parse(data.controlFuncs || '[]');
        modelData.events = JSON.parse(data.events || '[]');
      }
    });
  }
};
const addModel = () => {
  modelDialog.visible = true;
  modelDialog.title = activeName.value === 'dataPoints' ? '新增属性' : activeName.value === 'controlFuncs' ? '新增能力' : '新增事件';
  editIndex.value = null;
  modelFormRef.value?.resetFields();
  Object.keys(modelData[`${activeName.value}Form`]).forEach((key) => {
    modelData[`${activeName.value}Form`][key] = '';
  });
};
const editModel = (index) => {
  modelDialog.visible = true;
  modelDialog.title = activeName.value === 'dataPoints' ? '修改属性' : activeName.value === 'controlFuncs' ? '修改能力' : '修改事件';
  editIndex.value = index;
  modelFormRef.value?.resetFields();
  Object.assign(modelData[`${activeName.value}Form`], modelData[`${activeName.value}`][index]);
};
const delModel = async (index) => {
  modelData[activeName.value].splice(index, 1);
  const params = {};
  params[activeName.value] = JSON.stringify(modelData[activeName.value]);
  await editModels({ id: modelData.id, ...params });
  proxy?.$modal.msgSuccess('删除成功');
};
const submitModelForm = () => {
  modelFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      if (editIndex.value !== null) {
        modelData[activeName.value].splice(editIndex.value, 1, modelData[`${activeName.value}Form`]);
      } else {
        modelData[activeName.value].push(modelData[`${activeName.value}Form`]);
      }
      const params = { name: `${curRow.value.name}物模型` };
      params[activeName.value] = JSON.stringify(modelData[activeName.value]);
      buttonLoading.value = true;
      if (modelData.id) {
        await editModels({ id: modelData.id, ...params });
        proxy?.$modal.msgSuccess('修改成功');
      } else {
        await addModels(params).then(({ code, data }) => {
          if (code === 200) {
            updateDeviceType({ id: curRow.value.id, modeId: data.id });
          }
        });
        proxy?.$modal.msgSuccess('新增成功');
      }
      modelDialog.visible = false;
      buttonLoading.value = false;
    }
  });
};
onMounted(() => {
  getList();
  getTreeData();
});
</script>
<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;

  .el-icon {
    cursor: pointer;
  }
}

.custom-tree-node {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-right: 5px;
}

.node-operateBtns {
  div {
    margin-top: 3px;
    text-align: center;
    cursor: pointer;

    &:hover {
      color: #409eff;
    }
  }
}
</style>
<style lang="scss">
.customDrawer {
  .el-drawer__header {
    align-items: flex-start !important;
    margin-bottom: 10px;

    .drawer-title {
      .title-name {
        color: #000;
      }
    }
  }

  .el-drawer__body {
    padding-top: 0;
  }
}
</style>
