<template>
  <div class="p-2">
    <div v-loading="loading">
      <el-scrollbar max-height="400px">
        <div v-for="(card, cardIndex) in cards" :key="cardIndex" style="display: inline-block; margin-right: 15px">
          <el-scrollbar wrap-class="scrollbar-wrapper" :view-style="{ width: 'max-content' }">
            <div class="content" style="white-space: nowrap">
              <el-row>
                <el-card>
                  <template #header>
                    <div class="card-header">
                      <el-button circle size="small" type="primary">{{ card.label }}</el-button>
                      <el-text size="small">设置判断表达式</el-text>
                      <!-- 记录nextNodeId -->
                      <el-text v-if="false">{{ card.nextNodeId }}</el-text>
                    </div>
                  </template>
                  <!-- 表单循环 -->
                  <el-form ref="queryFormRef" :inline="true" label-width="10px">
                    <div v-for="(item, index) in card.formItemsWithIndex" :key="index" style="margin-top: 15px">
                      <el-row>
                        <el-form-item prop="rulesInputParams">
                          <el-select v-model="item.inputParams" size="small" placeholder="请选择变量" style="width: 140px">
                            <el-option
                              v-for="option in paramsList"
                              :key="option.fieldName"
                              :label="option.fieldDescription"
                              :value="option.fieldName"
                              style="width: 180px"
                            >
                              <span style="float: left">{{ option.fieldDescription }}</span>
                              <span style="float: right; font-size: 0px">
                                <el-tag>{{ option.parmsType }}</el-tag>
                              </span>
                            </el-option>
                          </el-select>
                        </el-form-item>
                        <el-form-item prop="rulesComOperator">
                          <el-select v-model="item.comOperator" size="small" placeholder="判断符" style="width: 140px">
                            <el-option
                              v-for="option in OperatorOptions"
                              :key="option.value"
                              :label="option.label"
                              :value="option.value"
                              style="width: 230px"
                            >
                              <span style="float: left">{{ option.label }}</span>
                              <span style="float: right; color: var(--el-text-color-secondary); font-size: 13px"> {{ option.tag }} </span>
                            </el-option>
                          </el-select>
                        </el-form-item>
                        <el-form-item prop="rulesDataType">
                          <el-select v-model="item.dataType" size="small" placeholder="类型" style="width: 140px">
                            <el-option v-for="option in DataTypeOptions" :key="option.value" :label="option.label" :value="option.value" />
                          </el-select>
                        </el-form-item>
                        <el-form-item v-if="item.dataType === 'variable'" prop="rulesOutSelect">
                          <el-select
                            v-model="item.outSelect"
                            size="small"
                            :multiple="item.comOperator === 'in' || item.comOperator === 'notIn'"
                            placeholder="请选择变量"
                            style="width: 140px"
                          >
                            <el-option
                              v-for="option in paramsList"
                              :key="option.fieldName"
                              :label="option.fieldDescription"
                              :value="option.fieldName"
                              style="width: 180px"
                            >
                              <span style="float: left">{{ option.fieldDescription }}</span>
                              <span style="float: right; font-size: 0px">
                                <el-tag>{{ option.parmsType }}</el-tag>
                              </span>
                            </el-option>
                          </el-select>
                        </el-form-item>
                        <el-form-item v-if="item.dataType === 'fixed'" prop="rulesOutEntry">
                          <el-input v-model="item.outEntry" size="small" placeholder="请输入值" style="width: 140px" />
                        </el-form-item>
                        <el-button size="small" icon="Minus" circle @click="minusItem(cardIndex, index)"></el-button>
                      </el-row>
                      <el-row v-if="index !== card.formItemsWithIndex.length - 1">
                        <el-select v-model="card.connectors[index]" size="small" placeholder="连接符" style="width: 140px">
                          <el-option v-for="option in connectorOptions" :key="option.value" :label="option.label" :value="option.value" />
                        </el-select>
                      </el-row>
                    </div>
                    <el-row>
                      <el-button v-if="showSaveflag" size="small" @click="addFormItem(cardIndex)">增加</el-button>
                    </el-row>
                  </el-form>
                </el-card>
              </el-row>
            </div>
          </el-scrollbar>
        </div>
      </el-scrollbar>
    </div>
    <el-button
      v-if="showSaveCard && showSaveflag"
      icon="Check"
      type="primary"
      size="small"
      style="margin-left: 20px; margin-top: 10px"
      @click="saveCards"
      >保存</el-button
    >
    <el-divider></el-divider>
    <el-form :inline="true">
      <el-button size="small" circle type="primary" icon="Connection" />
      <el-text size="small">设置参数 </el-text>
      <el-button size="small" type="primary" v-if="showSaveflag" icon="CirclePlusFilled">添加参数</el-button>
    </el-form>

    <el-table :data="paramsList">
      <el-table-column label="变量解释" align="center" prop="fieldDescription" />
      <el-table-column label="变量" align="center" prop="fieldName" />
      <el-table-column label="数据类型" align="center" prop="fieldType" />
      <el-table-column label="变量类型" align="center" prop="parmsType" />
    </el-table>
  </div>
</template>

<script setup name="RuleRankNodeForm" lang="ts">
import { Graph } from '@antv/x6';
import { emitter } from '@/utils/eventBus';
import { getConditionRulesDecisionTreeDetail, quryRulesParms, saveRulesDecisionTreeDetail } from '@/api/rule/definition/index';
import { connectorOptions, DataTypeOptions, OperatorOptions } from '@/api/rule/definition/Options';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const props = defineProps({
  nodeData: Object,
  graphData: Graph,
  rulesId: Object,
  showSave: Boolean
});

// 定义响应式数据
const formData = ref({});
const nodeGraph = ref(Graph);
const fromRulesId = ref(null);
const paramsList = ref([]);
const showSaveCard = ref(false);
const loading = ref(false);
const showSaveflag = ref(true);
// 定义响应式数据
const cards = ref([]);

function addFormItem(cardIndex) {
  const newItem = {
    index: cards.value[cardIndex].formItemsWithIndex.length,
    inputParams: '',
    comOperator: '',
    dataType: '',
    outSelect: '',
    outEntry: ''
  };
  cards.value[cardIndex].formItemsWithIndex.push(newItem);
  if (cards.value[cardIndex].formItemsWithIndex.length > 1) {
    cards.value[cardIndex].connectors.push('');
  }
}

function minusItem(cardIndex, index) {
  cards.value[cardIndex].formItemsWithIndex.splice(index, 1);
  if (cards.value[cardIndex].formItemsWithIndex.length <= 1 && cards.value[cardIndex].connectors.length > 0) {
    cards.value[cardIndex].connectors.pop();
  }
  // 重新设置序号
  cards.value[cardIndex].formItemsWithIndex.forEach((item, i) => {
    item.index = i;
  });
}

// 初始化逻辑
onMounted(async () => {
  // 监听主界面的 edge 变化事件
  emitter.on('edgesUpdated', (edges) => {
    updateFromProps();
  });
});

async function updateFromProps() {
  loading.value = true;
  const { nodeData, graphData, rulesId, showSave } = props;
  formData.value = nodeData || {};
  (nodeGraph.value as unknown as Graph) = graphData;
  fromRulesId.value = rulesId;
  showSaveflag.value = showSave;
  // 获取选中节点连接的边数
  const node = (nodeGraph.value as unknown as Graph).getCellById(formData.value.id);
  const edges = (nodeGraph.value as unknown as Graph).getOutgoingEdges(node);
  if (edges) {
    cards.value = edges.map((edge, edgeIndex) => {
      let labelText;
      const labels = edge.getLabels();
      if (labels && labels.length > 0) {
        // 假设我们只关心第一个标签的文字内容
        const label = labels[0];
        // 根据实际情况调整以下行，例如使用 get 或者其他方法
        labelText = label.attrs.label.text; // 或者 label.attributes.text
      }
      let TargetNodeId = edge.getTargetCell().id;
      return {
        nextNodeId: TargetNodeId,
        label: labelText,
        formItemsWithIndex: [],
        connectors: []
      };
    });
    showSaveCard.value = true;
  } else {
    cards.value = null;
    showSaveCard.value = false;
  }

  // 更新列表和下拉
  const res = await quryRulesParms(rulesId);
  paramsList.value = res.data;
  if (edges) {
    await getCondition();
  }
  loading.value = false;
}

async function getCondition() {
  for (const card of cards.value) {
    const res = await getConditionRulesDecisionTreeDetail(fromRulesId.value, formData.value.id, card.nextNodeId);
    if (res.code === 200 && res.data.nodeData) {
      const nodeData = res.data.nodeData;
      card.formItemsWithIndex = nodeData.formItemsWithIndex;
      card.connectors = nodeData.connectors;
    } else {
      proxy?.$modal.msgError(res.msg);
    }
  }
  loading.value = false;
}

async function saveCards() {
  const inEdges = (nodeGraph.value as unknown as Graph).getIncomingEdges(formData.value.id);
  const outEdges = (nodeGraph.value as unknown as Graph).getOutgoingEdges(formData.value.id);
  if (inEdges.length == 0 || outEdges.length == 0) {
    proxy?.$modal.msgError('请设置连接线');
    return;
  }
  const savedCards = JSON.stringify(cards.value);
  const res = await saveRulesDecisionTreeDetail(fromRulesId.value, 'condition', formData.value.id, savedCards);
  if (res.code === 200) {
    proxy?.$modal.msgSuccess('保存成功');
  } else {
    proxy?.$modal.msgError(res.msg);
  }
}

// 使用深度监听来捕捉 props 内部属性的变化
watch(
  () => ({ nodeData: props.nodeData, graph: props.graphData, rulesId: props.rulesId, showSave: props.showSave }),
  ({ nodeData, graph, rulesId, showSave }) => {
    updateFromProps();
  },
  { deep: true, immediate: true } // 添加 immediate 选项以确保首次渲染时也执行监听器
);
</script>

<style scoped lang="scss">
.scrollbar-wrapper {
  white-space: nowrap; /* 防止内容换行 */
}

.content {
  display: inline-block; /* 让内容在同一行显示 */
  padding: 10px;
}
</style>
