<script setup lang="ts">
import { ref, onMounted, watch, reactive, markRaw } from "vue";

import type { Node, Edge } from "@vue-flow/core";
import {
  HJMethodName,
  HJNodeData,
  HJPanelFunNameArray,
} from "@/components/MyFlow/src/types/comTypes";
import WorkFlowDrag from "@/components/MyFlow/src/leftDrags/workflow/dragData.vue";
import HJFlow from "@/components/MyFlow";

import type { ComponentSize, FormInstance, FormRules } from "element-plus";
import { getUserTree } from "@/api/system/user";
import { getFlowDataInfo, getRoleList, saveFlowData } from "@/api/flow";

const formSize = ref<ComponentSize>("default");
const ruleFormRef = ref<FormInstance>();
const formData = ref<any>({
  name: "",
  desc: "",
  userType: "",
  copyUsers: "",
  assignee: "",
  candidateUsers: "",
  candidateGroups: "",
});
const candidateGroupsOptions = ref([]); //指定角色选项
const usersOptions = ref([]);
const userTypeOption = ref([
  { label: "指定人员", value: "assignee" },
  { label: "候选人员", value: "candidateUsers" },
  { label: "指定角色", value: "candidateGroups" },
]);

const rules = reactive<FormRules<any>>({
  name: [
    { required: true, message: "请输入审核节点名称", trigger: "blur" },
  ],
  userType: [
    { required: true, message: "人员类型不能为空", trigger: "blur" },
  ],
  candidateUsers: [
    { required: true, message: "候选人员不能为空", trigger: "blur" },
  ],
  assignee: [
    { required: true, message: "指定人员不能为空", trigger: "blur" },
  ],
  candidateGroups: [
    { required: true, message: "指定角色不能为空", trigger: "blur" },
  ],
});

const submitForm =  () => {
  ruleFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      if (flowRef.value && flowRef.value.updateNodeData && selectedNode.value) {
        selectedNode.value.data.information = JSON.parse(
            JSON.stringify(formData.value)
        );
        flowRef.value.updateNodeData(
            JSON.parse(JSON.stringify(markRaw(selectedNode.value)))
        );
        cancel();
      }
    } else {
      console.log('error submit!', fields)
    }
  })
};

const cancel = () => {
  ruleFormRef.value && ruleFormRef.value.resetFields();
  selectedNode.value = null;
  infoVisible.value = false;
};

const flowRef = ref();
const nodes = ref<HJNodeData[]>([]);
const edges = ref<Edge[]>([]);

onMounted(() => {
  // 接口调用完成要初始化 ，为的是保存一个最初的数据

  getUserTree().then((res) => {
    usersOptions.value = res.data;
  });
  getFlowDataInfo(route.params.flowId).then((res) => {
    try {
      let json = JSON.parse(res.data.flowContent);
      nodes.value = json.nodes;
      edges.value = json.edges;
      flowRef.value && flowRef.value.initFlow(nodes.value, edges.value);
    } catch (e) {}
  });

  getRoleList().then((res) => {
    candidateGroupsOptions.value = res.data;
  });
});

// ======= 信息展示 =======
const infoVisible = ref(false);
const selectedNode = ref<HJNodeData | null>(null); //双击的节点数据
const closeInfo = () => {
  infoVisible.value = false;
  selectedNode.value = null;
};

const route = useRoute();
// vue 的相关操作
const onNodeOperation = async (name: HJMethodName, node: HJNodeData): void => {
  if (name === HJMethodName.EditNode) {
    selectedNode.value = null;
    infoVisible.value = true;

    selectedNode.value = JSON.parse(JSON.stringify(node));

    if (selectedNode.value) {
      if(selectedNode.value.data.information){
        formData.value = JSON.parse(
            JSON.stringify(selectedNode.value.data.information)
        );
      }else{
        formData.value = {}
      }
    }

    console.log("selectedNode", selectedNode.value);
  } else if (name === HJMethodName.SaveTemplate) {
    console.log("保存模板");
    let p = {
      nodes: markRaw(nodes.value),
      edges: markRaw(edges.value),
    };
    await saveFlowData({
      flowContent: JSON.stringify(p),
      id: route.params.flowId,
    });
    ElMessage.success("保存成功");
    cancel();
  }
};

const testGetCurrentData = () => {
  let p = {
    nodes: markRaw(nodes.value),
    edges: markRaw(edges.value),
  };
  console.log("=========当前数据======", JSON.stringify(p), p);
};
</script>

<template>
  <div class="out-box">
    <WorkFlowDrag></WorkFlowDrag>
    <HJFlow
      class="vue-flow-box"
      ref="flowRef"
      v-model:nodes-data="nodes"
      v-model:edges-data="edges"
      @hjMethod="onNodeOperation"
      :show-panel="true"
      :panel-btns="['layoutTB', 'saveTemplate']"
    ></HJFlow>
    <div class="right-message">
      <div class="flow-header-name" @click="testGetCurrentData">
        编辑节点信息
      </div>
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="formData"
        label-width="auto"
        class="demo-ruleForm"
        :size="formSize"
        status-icon
        :rules="rules"
        v-show="infoVisible"
      >
        <el-form-item label="节点名称" prop="name">
          <el-input v-model="formData.name" />
        </el-form-item>
        <el-form-item label="节点描述" prop="desc">
          <el-input v-model="formData.desc" type="textarea" />
        </el-form-item>
        <!--        <el-form-item label="抄送人员" prop="copyUsers">-->
        <!--          <el-tree-select-->
        <!--            v-model="formData.copyUsers"-->
        <!--            :data="usersOptions"-->
        <!--            filterable-->
        <!--            multiple-->
        <!--          />-->
        <!--        </el-form-item>-->
        <el-form-item label="人员类型" prop="userType">
          <el-select v-model="formData.userType" placeholder="请选择人员类型">
            <el-option
              v-for="item in userTypeOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          label="指定人员"
          prop="assignee"
          v-if="formData.userType === 'assignee'"
        >
          <el-tree-select
            v-model="formData.assignee"
            :data="usersOptions"
            filterable
          />
        </el-form-item>
        <el-form-item
          label="候选人员"
          prop="candidateUsers"
          v-if="formData.userType === 'candidateUsers'"
        >
          <el-tree-select
            v-model="formData.candidateUsers"
            :data="usersOptions"
            filterable
            multiple
          />
        </el-form-item>
        <el-form-item
          label="指定角色"
          prop="candidateGroups"
          v-if="formData.userType === 'candidateGroups'"
        >
          <el-tree-select
            v-model="formData.candidateGroups"
            :data="candidateGroupsOptions"
            :props="{ label: 'roleName', value: 'roleName' }"
            filterable
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">
            确定
          </el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style scoped lang="less">
.out-box {
  width: 100%;
  height: calc(100vh - 120px);
  border: 1px solid #ccc;
  display: flex;
}

.vue-flow-box {
  flex: 1;
  flex-shrink: 0;
  height: 100%;
  border: 3px solid red;
  //width: 300px;
  //height: 500px;
}

.right-message {
  width: 400px;
  height: 100%;
  border: 1px solid #ccc;
  background-color: white;
  padding: 10px;
  display: flex;
  flex-direction: column;
  justify-content: start;
  align-items: start;

  .flow-header-name {
    font-size: 18px;
    font-weight: bold;
    margin-top: 10px;
    margin-bottom: 10px;
  }
}
</style>
