<template>
  <el-dialog class="api-edit" v-model="showDialog" :title="`${formData.id ? '编辑' : '新增'}`" width="600px" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form ref="formRef" :model="formData" :rules="ruleForm" label-width="80px">
      <el-form-item label="名称" prop="name">
        <el-input v-model.trim="formData.name" placeholder="输入名称" />
      </el-form-item>
      <el-form-item label="主规则链" prop="types">
        <el-switch v-model="formData.types" :active-value="1" :inactive-value="0" active-text="关闭：为创建子链"></el-switch>
      </el-form-item>
      <el-form-item label="调试模式" prop="status">
        <el-switch v-model="formData.status" :active-value="2" :inactive-value="0"></el-switch>
        开启后会覆盖节点的调试模式配置，所有节点会打印调试日志
      </el-form-item>
      <el-form-item label="说明" prop="expound">
        <el-input v-model="formData.expound" type="textarea" :rows="5" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="onSubmit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, nextTick } from "vue";
import api from "/@/api/rule";
import axios from "axios";
import { ruleRequired } from "/@/utils/validator";
import { ElMessage } from "element-plus";
import { getToken } from "/@/utils/auth";
import { v4 as uuid } from "uuid";

const emit = defineEmits(["getList"]);

const props = defineProps({
  model: {
    type: String,
    default: "sagoo-rule", // sagoo-rule 、node-red
  },
});

const headers = {
  Authorization: "Bearer " + getToken(),
};
const flowsUrl = window.location.origin + "/rule-engine/flow";
// const flowsUrl = 'http://zhgy.sagoo.cn/rule-engine/flow';

const showDialog = ref(false);
const formRef = ref();

const baseForm = {
  id: undefined,
  name: "",
  types: 1,
  flowId: "",
  expound: "",
  status: 0,
};

const formData = reactive({
  ...baseForm,
});

const ruleForm = {
  name: [ruleRequired("规则名称不能为空")],
};

const onSubmit = async () => {
  await formRef.value.validate();

  // 不同引擎，用不同处理方式
  if (props.model === "sagoo-rule") {
    if (!formData.id) {
      const id = uuid();
      await axios.post(
        import.meta.env.VITE_RULE_SERVER_URL + "/api/v1/rules/" + id,
        {
          ruleChain: {
            id: id,
            name: formData.name,
            root: formData.types === 1,
            debugMode: formData.status === 2,
            additionalInfo: {
              description: formData.expound,
              layoutX: "130",
              layoutY: "220",
            },
          },
          metadata: {
            nodes: [],
            endpoints: [],
            connections: [],
          },
        },
        { headers }
      );
      formData.flowId = id;
    } else {
      // 找到规则
      const { data } = (await axios.get(import.meta.env.VITE_RULE_SERVER_URL + "/api/v1/rules/" + formData.flowId, { headers }).catch(() => {
        ElMessage.error("规则不存在");
      })) as any;

      // 修改名称和说明
      data.ruleChain.name = formData.name;
      data.ruleChain.additionalInfo.description = formData.expound;

      // 保存
      await axios.post(import.meta.env.VITE_RULE_SERVER_URL + "/api/v1/rules/" + formData.flowId, data, { headers });
    }
  } else if (props.model === "node-red") {
    if (!formData.id) {
      const { data } = await axios.post(
        flowsUrl,
        {
          label: formData.name,
          disabled: true,
          info: "",
          env: [],
          nodes: [],
        },
        {
          headers,
        }
      );
      formData.flowId = data.id;
    } else {
      // 找到所有规则
      const { data: flows } = await axios.get(flowsUrl + "s", { headers });

      const flow = flows.find((item: any) => item.id === formData.flowId);

      if (!flow) {
        ElMessage.error("规则不存在");
        return;
      }

      flow.label = formData.name;

      // 设置规则状态
      await axios.post(flowsUrl + "s", flows, { headers });
    }
  }

  const theApi = formData.id ? api.edit : api.add;

  await theApi(formData);

  ElMessage.success("操作成功");
  resetForm();
  showDialog.value = false;
  emit("getList");
};

const resetForm = async () => {
  Object.assign(formData, { ...baseForm });
  formRef.value && formRef.value.resetFields();
};

const open = async (row: any) => {
  resetForm();
  showDialog.value = true;
  nextTick(() => {
    Object.assign(formData, { ...row });
  });
};

defineExpose({ open });
</script>
