import { ref, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
const usePoltEditorDrawer = (curNodeRef, graphRef, moduleFormRef) => {
  // 抽屉状态
  const poltDrawerRef = ref(false);
  // 当前场景数据
  const poltDataRef = ref({
    // 视频素材id
    videoId: "",
    // 图片素材id
    imageId: "",
    // 视频素材地址
    videoUrl: "",
    // 图片素材地址
    imageUrl: "",
  });
  // 问题内容
  const questionRef = ref("");
  // 当前选项数据
  const optionsRef = ref([]);
  // 切换剧情视频素材
  const handleChangePlotVideoSource = (sourceId, sourcesList) => {
    const target = sourcesList.find((item) => item.id === sourceId) || {};
    poltDataRef.value.videoId = target.id;
    poltDataRef.value.videoUrl = target.url;
  };
  // 切换剧情图片素材
  const handleChangePlotImageSource = (sourceId, sourcesList) => {
    const target = sourcesList.find((item) => item.id === sourceId) || {};
    poltDataRef.value.imageId = target.id;
    poltDataRef.value.imageUrl = target.url;
  };
  // 添加分支
  const handleAddOptions = () => {
    if (optionsRef.value.length >= 4)
      return ElMessage.warning("最多可添加四个分支选项");
    optionsRef.value.push({
      nodeId: null,
      optionType: String.fromCharCode(65 + optionsRef.value.length),
      optionName: "",
    });
  };
  // 每次输入变化之后提交，是否有相同选项
  const handleCheckSameName = (val, index) => {
    for (let i = 0; i < optionsRef.value.length; i++) {
      if (i === index) continue;
      const option = optionsRef.value[i];
      if (option.optionName === val)
        return !!ElMessage.warning("分支名称不可以有相同的");
    }
    return false;
  };

  // 更新对应节点的选项内容
  const updateOptionNode = (graph, options) => {
    if (!graph || !options || options.length <= 0) return;
    for (let i = 0; i < options.length; i++) {
      const option = options[i] || {};
      const targetNode = graph.findById(option.nodeId);
      const targetModel = targetNode.getModel();
      // 都相同表示没有变化，不需要更新
      if (
        option.optionType === targetModel.data.optionType &&
        option.optionName === targetModel.data.optionName
      )
        continue;
      // 更新当前节点
      graph.updateItem(
        targetNode,
        {
          data: {
            optionType: option.optionType,
            optionName: option.optionName,
          },
        },
        false
      );
    }
  };

  // 查找存在关联关系的跳转模块，并更新对应文本内容
  const findLinkNodeAndUpdate = (graph, node) => {
    // 获取所有的跳转节点
    const allJumpNodes = graph.findAll("node", (_node) => {
      return _node.get("model").type === "jump-node";
    });
    const curNodeModel = node.getModel();
    // 看一下是否有跳转节点的id是该节点
    allJumpNodes.forEach((jumpNode) => {
      const _model = jumpNode.getModel();
      const data = _model.data || {};
      if (data.jumpNodeId === curNodeModel.id) {
        graph.updateItem(
          jumpNode,
          {
            data: {
              jumpNodeName: curNodeModel.data.name,
            },
          },
          false
        );
      }
    });
  };

  // 保存
  const handleSave = () => {
    console.log("保存");
    if (!graphRef.value) return console.warn("画布不存在");
    const config = {
      data: {
        name: moduleFormRef.value.plotName,
        image: poltDataRef.value.imageUrl,
        uri: poltDataRef.value.videoUrl,
        videoId: poltDataRef.value.videoId,
        imageId: poltDataRef.value.imageId,
        question: questionRef.value,
        optionsList: optionsRef.value,
      },
    };
    // 更新当前节点
    graphRef.value.updateItem(curNodeRef.value, config);
    // 更新子节点
    updateOptionNode(graphRef.value, optionsRef.value);
    graphRef.value.layout(false);
    findLinkNodeAndUpdate(graphRef.value, curNodeRef.value);
    poltDrawerRef.value = false;
    curNodeRef.value = null;
  };
  // 取消更改
  const handleCancel = () => {
    ElMessageBox.confirm("是否确认取消更改?")
      .then(() => {
        poltDrawerRef.value = false;
        curNodeRef.value = null;
      })
      .catch(() => {
        // catch error
      });
  };

  // 获取节点下的选项数据
  const modelOptions = (model) => {
    const children = model.children || [];
    const result = [];
    for (let i = 0; i < children.length; i++) {
      const subNodeData = children[i].data || {};
      result.push({
        nodeId: children[i].id,
        optionType: subNodeData.optionType || "",
        optionName: subNodeData.optionName || "",
      });
    }
    return result;
  };

  // 根据传入的节点初始化内容
  const init = (node) => {
    const model = node.getModel();
    const data = model.data || {};
    moduleFormRef.value = {
      plotName: data.name,
      plotVideoSource: data.videoId,
      plotImageSource: data.imageId,
    };
    poltDataRef.value = {
      videoId: data.videoId,
      imageId: data.imageId,
      videoUrl: data.uri,
      imageUrl: data.image,
    };
    optionsRef.value = modelOptions(model);
    questionRef.value = data.question || "";
  };

  watch(
    () => curNodeRef.value,
    (node) => {
      if (!node) return;
      init(node);
    }
  );

  return {
    poltDrawerRef,
    poltDataRef,
    optionsRef,
    questionRef,
    handleChangePlotVideoSource,
    handleChangePlotImageSource,
    handleAddOptions,
    handleCheckSameName,
    handleSave,
    handleCancel,
  };
};

export default usePoltEditorDrawer;
