<template>
  <div class="relation-builder">
    <div class="w-full flex justify-between mb-10px" v-if="compact">
      <a-space :style="{ width: `calc(100% - ${isOperator ? '100' : '0'}px)`, marginBottom: '10px' }" wrap>
        <template v-for="(item, index) in items" :key="index">
          <a-input-number v-if="item.type === 'number'" v-model:value="item.value" style="width: 30px" placeholder="-" @blur="confirm" />
          <a-tag v-if="item.type === 'operand' || item.type === 'operator'" :color="tagColors[item.type]" class="expr-tag">
            {{ formatDisplay(item) }}
          </a-tag>
          <a-tag v-else-if="item.type === 'logic'" class="expr-tag">|</a-tag>
        </template>
      </a-space>
      <a-button v-if="isOperator" class="w-100px" type="primary" @click="enterAdvancedMode"> 高级编辑 </a-button>
    </div>
    <a-row v-else :gutter="8">
      <!-- 左侧：元素库 -->
      <a-col :span="12">
        <a-card title="元素库" size="small">
          <a-collapse class="relation-card" v-model:activeKey="activeKey" :bordered="false">
            <a-collapse-panel v-for="group in elementGroups" :key="group.key" :header="group.header">
              <div class="chip-container">
                <div
                  v-for="item in group.items"
                  :key="item.value"
                  class="chip"
                  :class="`chip-${group.type}`"
                  draggable="true"
                  @click="appendItem(item)"
                >
                  {{ item.label }}
                </div>
              </div>
              <div class="extra-container">
                <div v-for="item in group.extra" :key="item.type" class="mt-8px">
                  <a-input-number v-model:value="item.value" :defaultValue="0">
                    <template #addonAfter>
                      <span style="cursor: pointer" draggable="true" @click="appendItem(item)"> 追加 </span>
                    </template>
                  </a-input-number>
                </div>
              </div>
            </a-collapse-panel>
          </a-collapse>
          <template #actions>
            <div class="relation-card-footer">
              <a-typography-text class="pt-6px pb-6px" type="secondary"> <InfoCircleOutlined /> 点击追加元素 </a-typography-text>
            </div>
          </template>
        </a-card>
      </a-col>

      <!-- 中间：画布 -->
      <a-col :span="12">
        <a-card title="表达式画布" size="small">
          <template #extra>
            <a-tooltip title="清空">
              <a-button size="small" danger @click="clearCanvas">
                <DeleteOutlined />
              </a-button>
            </a-tooltip>
          </template>

          <div class="relation-card">
            <div class="canvas-container">
              <a-empty v-if="!items.length" description="从左侧点击或拖拽元素" />
              <div v-else class="expression-list">
                <a-tag v-for="(item, index) in items" :key="index" :color="tagColors[item.type]" class="expr-tag" closable @close="removeItem(index)">
                  <span class="mr-4px">{{ formatDisplay(item) }}</span>
                </a-tag>
              </div>
            </div>

            <a-divider style="margin: 12px 0" />
            <a-space direction="vertical" style="width: 100%" :size="16">
              <a-typography-text strong>当前表达式</a-typography-text>
              <span>{{ expressionString }}</span>
              <a-alert v-if="errorMessage" :message="errorMessage" type="error" show-icon closable @close="errorMessage = ''" />

              <div>
                <a-typography-text strong>快速模板</a-typography-text>
                <a-input-group compact>
                  <a-select v-model:value="selectedTemplate" :options="templateOptions" style="width: calc(100% - 100px)" />
                  <a-button class="w-100px" type="primary" @click="applyTemplate">应用模板</a-button>
                </a-input-group>
              </div>

              <div>
                <a-typography-text strong>输入表达式</a-typography-text>
                <a-input-group compact>
                  <a-input v-model:value="inputString" style="width: calc(100% - 100px)" placeholder="例如: CO > 0 && CO2 > 0" allow-clear />
                  <a-button class="w-100px" type="primary" @click="applyManualInput"> 应用到画布 </a-button>
                </a-input-group>
              </div>
            </a-space>
          </div>

          <template #actions>
            <div class="relation-card-footer" style="text-align: right">
              <a-button class="mr-10px" @click="backToCompact">普通模式</a-button>
              <a-button class="mr-10px" @click="reset">重置</a-button>
              <a-button class="mr-12px" type="primary" @click="confirm">提交</a-button>
            </div>
          </template>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script lang="ts" setup>
  import { ref, computed, watch, h } from 'vue';
  import { useRoute } from 'vue-router';
  import { cloneDeep } from 'lodash-es';
  import { message, Modal } from 'ant-design-vue';
  import { DeleteOutlined } from '@ant-design/icons-vue';
  import {
    parseExpression,
    formatDisplay as _formatDisplay,
    validateExpression,
    checkTopLevelMixed,
    addParenthesesForAnd,
    DEFAULT_TEMPLATE_OPTIONS,
    DEFAULT_ELEMENT_GROUPS,
    DEFAULT_DISPLAY_MAP,
    DEFAULT_OPERAND_SET,
  } from '../utils';
  import type { Item, ElementGroup } from '../utils';

  // 常量配置（从当前路由 meta.compact 读取，默认 false）
  const route = useRoute();
  const isOperator = computed(() => !!route.meta?.compact);
  const activeKey = ref<string[]>(['gas', 'operator', 'logic', 'number', 'paren']);

  const templateOptions = ref(DEFAULT_TEMPLATE_OPTIONS);

  const elementGroups: ElementGroup[] = DEFAULT_ELEMENT_GROUPS;

  const operandSet = DEFAULT_OPERAND_SET;

  const tagColors: Record<string, string> = {
    operand: 'blue',
    operator: 'green',
    logic: 'orange',
    number: 'purple',
    leftParen: 'default',
    rightParen: 'default',
  };

  const displayMap: Record<string, string> = DEFAULT_DISPLAY_MAP;

  // 模板调用的 formatDisplay，闭包捕获 displayMap
  const formatDisplay = (item: Item) => _formatDisplay(item, displayMap);

  // Props 和 Emits
  const props = defineProps<{ modelValue: string }>();
  const emit = defineEmits<{
    (e: 'update:modelValue', value: string): void;
    (e: 'change', value: string): void;
    (e: 'confirm', value: string): void;
  }>();

  // Reactive 状态
  const compact = ref<boolean>(true);
  const inputString = ref<string>('');
  const items = ref<Item[]>([]);
  const manualInput = ref<string>('');
  const errorMessage = ref<string>('');
  const selectedTemplate = ref<string>('');

  // Computed
  const expressionString = computed(() => items.value.map((i) => i.value).join(' '));

  /** 将表达式字符串解析并同步到画布 */
  const initializeFromExpression = (expr: string): void => {
    const parsed = parseExpression(expr, operandSet);
    items.value = parsed.length ? parsed : [];
    // 同步简易模式输入框（如果处于简易模式，显示最新表达式）
    inputString.value = expr;
    manualInput.value = ''; // 清空手动输入区
    errorMessage.value = '';
  };

  /** 追加一个元素到画布末尾 */
  const appendItem = (item: Item): void => {
    items.value.push(cloneDeep(item));
    syncAfterChange();
  };

  /** 移除指定索引处的元素 */
  const removeItem = (index: number): void => {
    items.value.splice(index, 1);
    syncAfterChange();
  };

  /** 清空画布所有元素 */
  const clearCanvas = (): void => {
    items.value = [];
    syncAfterChange();
  };

  /** 画布变更后同步到简易模式输入框（不触发提交） */
  const syncAfterChange = (): void => {
    const expr = expressionString.value;
    inputString.value = expr;
  };

  /** 提交逻辑 */
  const confirm = async (): Promise<void> => {
    const expr = expressionString.value;
    const validation = validateExpression(expr, operandSet);
    if (!validation.valid) {
      errorMessage.value = validation.message || '表达式不合法';
      return;
    }
    errorMessage.value = '';

    // 基于 items 判断最外层是否存在未加括号的 && 与 || 混合
    const hasMixed = checkTopLevelMixed(items.value);
    let finalExpr = expr;

    if (hasMixed) {
      await new Promise<void>((resolve) => {
        const originalExpr = expr;
        const suggestedExpr = addParenthesesForAnd(items.value);

        Modal.confirm({
          title: '运算符优先级提醒',
          content: h('div', [
            h('p', '表达式最外层同时包含“且(&&)”和“或(||)”，程序将优先计算“且(&&)”。'),
            h('p', { style: { margin: '8px 0' } }, [
              h('strong', '原表达式：'),
              h('code', { style: { backgroundColor: '#f5f5f5', padding: '2px 6px', borderRadius: '4px' } }, originalExpr),
            ]),
            h('p', { style: { margin: '8px 0' } }, [
              h('strong', '建议表达式：'),
              h('code', { style: { backgroundColor: '#f6ffed', padding: '2px 6px', borderRadius: '4px' } }, suggestedExpr),
            ]),
            h('p', '是否自动添加括号以明确优先级？'),
          ]),
          okText: '自动添加',
          cancelText: '保持原样',
          onOk: () => {
            finalExpr = suggestedExpr;
            // 同步到画布（仅当用户选择自动添加时才更新画布）
            const parsed = parseExpression(finalExpr, operandSet);
            if (parsed.length) items.value = parsed;
            resolve();
          },
          onCancel: () => resolve(),
        });
      });
    }

    // 统一提交
    emit('update:modelValue', finalExpr);
    emit('change', finalExpr);
    emit('confirm', finalExpr);
    inputString.value = finalExpr;
    message.success('已更新');
  };

  /** 重置整个组件状态 */
  const reset = (): void => {
    items.value = [];
    inputString.value = '';
    manualInput.value = '';
    errorMessage.value = '';
    emit('update:modelValue', '');
    emit('change', '');
  };

  /** 切换至高级编辑模式，将外部传入的表达式加载到画布 */
  const enterAdvancedMode = (): void => {
    // 将当前 modelValue 初始化到画布
    initializeFromExpression(props.modelValue);
    compact.value = false;
  };

  /** 从高级模式返回简易模式，如有变更则提示用户确认 */
  const backToCompact = async (): Promise<void> => {
    const currentExpr = expressionString.value;
    if (currentExpr === props.modelValue) {
      compact.value = true;
      return;
    }
    Modal.confirm({
      title: '确认返回',
      content: '画布内容已修改，是否应用变更？',
      okText: '应用',
      cancelText: '放弃',
      onOk: async () => {
        await confirm(); // 内部会校验、询问优先级、提交
        compact.value = true;
      },
      onCancel: () => {
        // 放弃变更：恢复为原始 modelValue
        initializeFromExpression(props.modelValue);
        compact.value = true;
      },
    });
  };

  /** 应用选中的快捷模板 */
  const applyTemplate = (): void => {
    if (!selectedTemplate.value) return;
    initializeFromExpression(selectedTemplate.value);
    selectedTemplate.value = '';
    message.success('模板已应用');
  };

  /** 应用手动输入的表达式字符串 */
  const applyManualInput = (): void => {
    const expr = manualInput.value.trim();
    if (!expr) return;
    const validation = validateExpression(expr, operandSet);
    if (!validation.valid) {
      errorMessage.value = validation.message || '表达式不合法';
      return;
    }
    initializeFromExpression(expr);
    errorMessage.value = '';
    message.success('已应用');
  };

  watch(
    () => props.modelValue,
    (newVal) => {
      if (newVal !== undefined) {
        inputString.value = newVal;
        const parsed = parseExpression(newVal, operandSet);
        items.value = parsed.length ? parsed : [];
      }
    },
    { immediate: true }
  );

  /** 对外暴露校验方法，供表单 rules 使用 */
  defineExpose({ validate: () => validateExpression(props.modelValue, operandSet) });
</script>

<style scoped lang="less">
  .relation-builder {
    .relation-card {
      height: 680px;
      overflow-y: auto;
    }
    .relation-card-footer {
      height: 30px;
    }

    .chip-container {
      display: flex;
      flex-wrap: wrap;
      gap: 4px;
    }
    .chip {
      display: inline-block;
      padding: 4px 12px;
      border-radius: 4px;
      font-size: 14px;
      cursor: grab;
      user-select: none;
      border: 1px solid @border-color-base;
      background: @white;
      transition: all 0.2s;
      &:hover {
        // transform: translateY(-2px);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
      }
      &:active {
        cursor: grabbing;
      }
      &.chip-operand {
        background: #e6f7ff;
        border-color: #91d5ff;
        color: #0050b3;
      }
      &.chip-operator {
        background: #f6ffed;
        border-color: #b7eb8f;
        color: #135200;
      }
      &.chip-logic {
        background: #fff7e6;
        border-color: #ffd591;
        color: #ad4e00;
      }
      &.chip-number {
        background: #f9f0ff;
        border-color: #d3adf7;
        color: #531dab;
      }
      &.chip-paren {
        background: #f0f0f0;
        border-color: #bfbfbf;
        font-weight: bold;
      }
    }

    .canvas-container {
      min-height: 200px;
      max-height: 400px;
      overflow-y: auto;
      border: 2px dashed #d9d9d9;
      border-radius: 8px;
      padding: 16px;
      background: #fafafa;
      transition: all 0.2s;
      &.drag-over {
        border-color: #1890ff;
        background: #e6f7ff;
      }
      .expression-list {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        gap: 8px;
      }
    }

    .expr-tag {
      font-size: 14px;
      padding: 6px 12px;
      margin: 0;
      // :deep(.anticon-close) {
      //   margin-left: 6px;
      //   &:hover {
      //     color: #ff4d4f;
      //   }
      // }
    }
  }
</style>
