<script setup lang="ts">
import HJFlow from "@/components/hjflow/src/hjflow/index.vue";
import {
  HJFlowInstance,
  HJMethodName,
  HJNodeData,
} from "@/components/hjflow/src/types/comTypes";
import { Edge } from "@vue-flow/core";

import ProjectMessage from "./com/project-message.vue";
import FunctionModule from "./com/function-col.vue";
import TitleHeader from "@/views/modules/project-config/com/titleHeader.vue";
import { AutoTestNodeData, InforPropertyModel } from "./configs/properites";
import type { FormInstance } from "element-plus";
import {
  getProjectGlobalConfig,
  getTestProjectInfo,
  updateTestModule,
} from "@/api/project";

import { useCommonStoreHook } from "@/store";

const { currentTestItemId } = toRefs(useCommonStoreHook());

const route = useRoute();

const flowRef = ref<HJFlowInstance>();
const nodes = ref<HJNodeData[]>([]);
const edges = ref<Edge[]>([]);
// vue 的相关操作
const onNodeOperation = (name: HJMethodName, node: HJNodeData): void => {
  if (name === HJMethodName.EditNode) {
    selectedNode.value = null;
    selectedNode.value = JSON.parse(JSON.stringify(node));
    infoVisible.value = true;
  } else if (name === HJMethodName.SaveTemplate) {
    //   如果没有选测试项目 给提示
    if (!currentTestItemId.value) {
      ElMessage.warning("请选择测试项目");
      return;
    }

    if (nodes.value.length === 0) {
      ElMessage.warning("请编辑功能");
      return;
    }

    if (selectedNode.value) {
      ElMessage.warning("请先保存节点信息");
      return;
    }

    //   保存模版数据
    let flowData = {
      nodes: nodes.value,
      edges: edges.value,
    };
    console.log("dddddd", flowData);
    let p = {
      id: currentTestItemId.value,
      routeData: JSON.stringify(flowData),
    };
    updateTestModule(p).then(() => {
      ElMessage.success("保存模版成功");
      flowRef.value && flowRef.value.clearStatus();
    });
  }
};

// 右侧信息
// ======= 信息展示 =======
const infoVisible = ref(false);
const selectedNode = ref<AutoTestNodeData | null>(null); //双击的节点数据
const onSaveConfigs = () => {
  console.log("onSaveConfigs", selectedNode.value);
  if (!selectedNode.value) {
    return;
  }
  flowRef.value &&
    flowRef.value.updateNodeData(
      JSON.parse(JSON.stringify(selectedNode.value))
    );
  infoVisible.value = false;
  selectedNode.value = null;
};

onMounted(async () => {
  //   如果选择的测试项目id有值，就获取数据
  if (currentTestItemId.value) {
    getFlowData();
  }

  let res = await getProjectGlobalConfig(route?.params?.engineerId as string);
  configData.value = res.data;
});

const getFlowData = () => {
  nodes.value = [];
  edges.value = [];
  getTestProjectInfo(currentTestItemId.value).then((result) => {
    if (result.data.routeData) {
      let data = JSON.parse(result.data.routeData);
      nodes.value = data.nodes;
      edges.value = data.edges;
      // 接口调用完成要初始化 ，为的是保存一个最初的数据
      flowRef.value && flowRef.value.initFlow([], []);
    }
  });
};

//选择测试项目相关  每次点击需要重新获取中间的流程的数据
const onSelectTestPro = () => {
  flowRef.value && flowRef.value.clearStatus();
  selectedNode.value = null;
  infoVisible.value = false;
  getFlowData();
};

// 全局变量和仪器列表选择相关
const configData: Record<string, any[]> = ref({});
const configOptions = ref([]);

const handleSearch = (_: string, prefix: string) => {
  configOptions.value = configData.value[prefix] || [];
};
</script>

<template>
  <div class="project-config-container">
    <ProjectMessage @onClickItem="onSelectTestPro" />
    <FunctionModule />
    <HJFlow
      class="hjflow-box"
      ref="flowRef"
      v-model:nodes-data="nodes"
      v-model:edges-data="edges"
      :show-panel="true"
      :panel-btns="['toSnake', 'layoutTB', 'saveTemplate']"
      @hjMethod="onNodeOperation"
    />
    <div class="right-message-box">
      <TitleHeader>属性配置</TitleHeader>
      <div class="form-box" v-if="infoVisible">
        <el-form rer="formRef" label-position="top">
          <el-form-item label="节点标识名称">
            <el-input
              v-model="selectedNode!.data.information.nodeName"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-text class="mx-1" type="warning">
              输入@选择全局变量或#选择仪器
            </el-text>
          </el-form-item>
          <el-form-item
            v-for="property in selectedNode?.data?.information?.properties"
            :label="property.proName"
            :key="property.proName"
          >
            <el-mention
              v-model="property.bindLabel"
              :options="configOptions"
              :prefix="['@', '#']"
              whole
              @search="handleSearch"
              @select="
                (opt) => {
                  property.bingObjJson = JSON.stringify(opt);
                }
              "
              @blur="
                () => {
                  if (property.bindLabel === '') {
                    property.bingObjJson = '';
                  }
                }
              "
            />
          </el-form-item>
        </el-form>
      </div>
      <div class="bottom-box">
        <div class="save-btn" @click="onSaveConfigs">
          <svg-icon icon-class="save" />
          保存节点信息
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.project-config-container {
  display: flex;
  width: 100%;
  height: calc(100vh - $main-header-height);
}

.hjflow-box {
  //width: 100%;
  flex: 1;
  height: 100%;
}

.right-message-box {
  width: 296px;
  flex-shrink: 0;
  background-color: rgba(80, 80, 80, 1);
  height: calc(100vh - $main-header-height);
  position: relative;

  .form-box {
    width: 100%;
    padding: 24px;
  }

  .bottom-box {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    //height: 80px;
    padding: 10px 0;
    background-color: $hj-black-2;

    .save-btn {
      width: 130px;
      height: 36px;
      line-height: 36px;
      margin: 0 auto;
      background: var(--fc-color-7);
      color: var(--hj-white-1);
      text-align: center;
      border-radius: 4px 4px 4px 4px;
      cursor: pointer;
    }
  }
}

:deep(.el-form-item--label-top .el-form-item__label) {
  height: 18px;
  font-weight: 400;
  font-size: 14px;
  color: #ffffff;
  line-height: 16px;
  text-align: left;
}

:deep(.el-collapse-item__wrap) {
  border: 0;
}
</style>
