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

import { ExternalLink, Plus } from '@vben/icons';
import { $t } from '@vben/locales';

import {
  ElAlert,
  ElButton,
  ElForm,
  ElFormItem,
  ElInput,
  ElInputNumber,
  ElOption,
  ElSelect,
  ElSwitch,
  ElTag,
} from 'element-plus';

import { getWorkflowListApi } from '#/api/ai-platform/ai-platform';

import SmartInput from '../components/SmartInput.vue';

const props = defineProps<{ data: any; nodeId: string }>();
const emit = defineEmits(['update']);

const label = ref(
  props.data.label || $t('ai-platform.workflow.panels.subflow.label'),
);
const subflowId = ref(props.data.subflow_id || '');
const subflowName = ref(props.data.subflow_name || '');
const varPassMode = ref(props.data.var_pass_mode || 'all');
const varMappings = ref<Array<{ name: string; value: string }>>(
  props.data.var_mappings || [],
);
const resultPassMode = ref(props.data.result_pass_mode || 'all');
const resultVars = ref<string[]>(props.data.result_vars || []);
const resultVariable = ref(props.data.result_variable || 'subflow_result');
const maxDepth = ref(props.data.max_depth || 5);
const showSubflowMessages = ref(props.data.show_subflow_messages ?? false);
const forwardInteractive = ref(props.data.forward_interactive ?? false);

// 可用的子流程列表
const subflowList = ref<Array<{ code: string; id: string; name: string }>>([]);
const loadingSubflows = ref(false);

// 新变量输入
const newResultVar = ref('');

// 加载可用的子流程列表
const loadSubflows = async () => {
  loadingSubflows.value = true;
  try {
    const response = await getWorkflowListApi({
      status: 'published',
      pageSize: 100,
    });
    subflowList.value = (response.items || []).map((w: any) => ({
      id: w.id,
      name: w.name,
      code: w.code,
    }));
  } catch (error) {
    console.error('加载子流程列表失败:', error);
  } finally {
    loadingSubflows.value = false;
  }
};

// 选择子流程
const handleSubflowChange = (id: string) => {
  const selected = subflowList.value.find((s) => s.id === id);
  if (selected) {
    subflowName.value = selected.name;
  }
};

// 添加变量映射
const addVarMapping = () => {
  varMappings.value.push({
    name: '',
    value: '',
  });
};

// 移除变量映射
const removeVarMapping = (index: number) => {
  varMappings.value.splice(index, 1);
};

// 添加结果变量
const addResultVar = () => {
  if (newResultVar.value && !resultVars.value.includes(newResultVar.value)) {
    resultVars.value.push(newResultVar.value);
    newResultVar.value = '';
  }
};

// 移除结果变量
const removeResultVar = (index: number) => {
  resultVars.value.splice(index, 1);
};

// 在新标签页打开子流程
const openSubflow = () => {
  if (subflowId.value) {
    window.open(`/ai-platform/workflow/editor/${subflowId.value}`, '_blank');
  }
};

watch(
  [
    label,
    subflowId,
    subflowName,
    varPassMode,
    varMappings,
    resultPassMode,
    resultVars,
    resultVariable,
    maxDepth,
    showSubflowMessages,
    forwardInteractive,
  ],
  ([
    labelVal,
    subflowIdVal,
    subflowNameVal,
    varPassModeVal,
    varMappingsVal,
    resultPassModeVal,
    resultVarsVal,
    resultVariableVal,
    maxDepthVal,
    showSubflowMessagesVal,
    forwardInteractiveVal,
  ]) => {
    emit('update', {
      ...props.data,
      label: labelVal,
      subflow_id: subflowIdVal,
      subflow_name: subflowNameVal,
      var_pass_mode: varPassModeVal,
      var_mappings: varMappingsVal,
      result_pass_mode: resultPassModeVal,
      result_vars: resultVarsVal,
      result_variable: resultVariableVal,
      max_depth: maxDepthVal,
      show_subflow_messages: showSubflowMessagesVal,
      forward_interactive: forwardInteractiveVal,
    });
  },
  { deep: true },
);

onMounted(() => {
  loadSubflows();
});
</script>

<template>
  <ElForm label-position="top" size="small" class="space-y-4">
    <ElFormItem :label="$t('ai-platform.workflow.panels.common.nodeName')">
      <ElInput
        v-model="label"
        :placeholder="$t('ai-platform.workflow.panels.subflow.placeholder')"
      />
    </ElFormItem>

    <ElFormItem>
      <template #label>
        <span>{{
          $t('ai-platform.workflow.panels.subflow.selectSubflow')
        }}</span>
        <span class="text-destructive ml-1">*</span>
      </template>
      <div class="flex gap-2">
        <ElSelect
          v-model="subflowId"
          class="flex-1"
          :placeholder="
            $t('ai-platform.workflow.panels.subflow.selectSubflowPlaceholder')
          "
          filterable
          :loading="loadingSubflows"
          @change="handleSubflowChange"
        >
          <ElOption
            v-for="subflow in subflowList"
            :key="subflow.id"
            :label="subflow.name"
            :value="subflow.id"
          >
            <div class="flex items-center justify-between">
              <span>{{ subflow.name }}</span>
              <span class="text-muted-foreground text-xs">{{
                subflow.code
              }}</span>
            </div>
          </ElOption>
        </ElSelect>
        <ElButton
          v-if="subflowId"
          :icon="ExternalLink"
          @click="openSubflow"
          :title="$t('ai-platform.workflow.panels.subflow.openInNewTab')"
        />
      </div>
      <div class="text-muted-foreground mt-1 text-xs">
        {{ $t('ai-platform.workflow.panels.subflow.publishedOnly') }}
      </div>
    </ElFormItem>

    <!-- 变量传递分组 -->
    <div class="border-border rounded-lg border p-4">
      <div class="text-foreground mb-3 text-sm font-semibold">
        {{ $t('ai-platform.workflow.panels.subflow.varPass') }}
      </div>

      <ElFormItem
        :label="$t('ai-platform.workflow.panels.subflow.passMode')"
        class="!mb-3"
      >
        <ElSelect v-model="varPassMode" class="w-full">
          <ElOption
            value="all"
            :label="$t('ai-platform.workflow.panels.subflow.passAll')"
          />
          <ElOption
            value="selected"
            :label="$t('ai-platform.workflow.panels.subflow.passSelected')"
          />
          <ElOption
            value="none"
            :label="$t('ai-platform.workflow.panels.subflow.passNone')"
          />
        </ElSelect>
      </ElFormItem>

      <div v-if="varPassMode === 'selected'">
        <div class="mb-2 flex items-center justify-between">
          <span class="text-foreground text-sm font-medium">{{
            $t('ai-platform.workflow.panels.subflow.varMapping')
          }}</span>
          <ElButton link type="primary" :icon="Plus" @click="addVarMapping">
            {{ $t('ai-platform.workflow.panels.common.add') }}
          </ElButton>
        </div>

        <div
          v-if="varMappings.length === 0"
          class="text-muted-foreground border-border rounded border border-dashed p-4 text-center text-xs"
        >
          {{ $t('ai-platform.workflow.panels.subflow.addVarMappingHint') }}
        </div>

        <div v-else class="space-y-2">
          <div
            v-for="(mapping, index) in varMappings"
            :key="index"
            class="bg-muted/50 rounded-lg border p-3"
          >
            <div class="mb-2 flex items-center justify-between">
              <span class="text-foreground text-xs font-medium">{{
                $t('ai-platform.workflow.panels.subflow.varIndex', {
                  index: index + 1,
                })
              }}</span>
              <ElButton
                link
                type="danger"
                size="small"
                @click="removeVarMapping(index)"
              >
                {{ $t('ai-platform.workflow.panels.common.delete') }}
              </ElButton>
            </div>
            <div class="space-y-2">
              <div>
                <label class="text-muted-foreground mb-1 block text-xs">{{
                  $t('ai-platform.workflow.panels.subflow.subflowVarName')
                }}</label>
                <ElInput
                  v-model="mapping.name"
                  placeholder="e.g. customer_name"
                  size="small"
                />
              </div>
              <div>
                <label class="text-muted-foreground mb-1 block text-xs">{{
                  $t('ai-platform.workflow.panels.subflow.mainflowVarValue')
                }}</label>
                <SmartInput
                  v-model="mapping.value"
                  :current-node-id="nodeId"
                  :placeholder="
                    $t(
                      'ai-platform.workflow.panels.subflow.selectVarPlaceholder',
                    )
                  "
                  size="small"
                />
              </div>
            </div>
          </div>
        </div>

        <div class="text-muted-foreground mt-2 text-xs">
          {{ $t('ai-platform.workflow.panels.subflow.varMappingHint1') }}<br />
          {{ $t('ai-platform.workflow.panels.subflow.varMappingHint2') }}
        </div>
      </div>
    </div>

    <!-- 结果处理分组 -->
    <div class="border-border rounded-lg border p-4">
      <div class="text-foreground mb-3 text-sm font-semibold">
        {{ $t('ai-platform.workflow.panels.subflow.resultHandling') }}
      </div>

      <ElFormItem
        :label="$t('ai-platform.workflow.panels.subflow.resultPassMode')"
        class="!mb-3"
      >
        <ElSelect v-model="resultPassMode" class="w-full">
          <ElOption
            value="all"
            :label="$t('ai-platform.workflow.panels.subflow.resultPassAll')"
          />
          <ElOption
            value="selected"
            :label="
              $t('ai-platform.workflow.panels.subflow.resultPassSelected')
            "
          />
          <ElOption
            value="none"
            :label="$t('ai-platform.workflow.panels.subflow.resultPassNone')"
          />
        </ElSelect>
      </ElFormItem>

      <div v-if="resultPassMode === 'selected'" class="mb-3">
        <label class="text-foreground mb-1 block text-sm font-medium">{{
          $t('ai-platform.workflow.panels.subflow.selectResultVars')
        }}</label>
        <div class="mb-2 flex gap-2">
          <ElInput
            v-model="newResultVar"
            :placeholder="
              $t('ai-platform.workflow.panels.subflow.resultVarPlaceholder')
            "
            size="small"
            @keyup.enter="addResultVar"
          />
          <ElButton size="small" :icon="Plus" @click="addResultVar" />
        </div>
        <div class="flex flex-wrap gap-1">
          <ElTag
            v-for="(varName, index) in resultVars"
            :key="index"
            closable
            size="small"
            @close="removeResultVar(index)"
          >
            {{ varName }}
          </ElTag>
        </div>
        <div
          v-if="resultVars.length === 0"
          class="text-muted-foreground text-xs"
        >
          {{ $t('ai-platform.workflow.panels.subflow.resultVarHint') }}
        </div>
      </div>

      <ElFormItem
        :label="$t('ai-platform.workflow.panels.subflow.resultVarName')"
      >
        <ElInput v-model="resultVariable" placeholder="subflow_result" />
        <div class="text-muted-foreground mt-1 text-xs">
          {{
            $t('ai-platform.workflow.panels.subflow.resultVarSavedHint', {
              template: resultVariable,
            })
          }}
        </div>
      </ElFormItem>
    </div>

    <!-- 高级设置分组 -->
    <div class="border-border rounded-lg border p-4">
      <div class="text-foreground mb-3 text-sm font-semibold">
        {{ $t('ai-platform.workflow.panels.common.advancedSettings') }}
      </div>

      <ElFormItem
        :label="$t('ai-platform.workflow.panels.subflow.maxNestDepth')"
        class="!mb-3"
      >
        <ElInputNumber v-model="maxDepth" :min="1" :max="10" class="w-full" />
        <div class="text-muted-foreground mt-1 text-xs">
          {{ $t('ai-platform.workflow.panels.subflow.maxNestDepthHint') }}
        </div>
      </ElFormItem>

      <div class="flex items-center justify-between py-2">
        <div>
          <div class="text-foreground text-sm font-medium">
            {{ $t('ai-platform.workflow.panels.subflow.showSubflowMessages') }}
          </div>
          <div class="text-muted-foreground text-xs">
            {{
              $t('ai-platform.workflow.panels.subflow.showSubflowMessagesHint')
            }}
          </div>
        </div>
        <ElSwitch v-model="showSubflowMessages" />
      </div>

      <div class="flex items-center justify-between py-2">
        <div>
          <div class="text-foreground text-sm font-medium">
            {{ $t('ai-platform.workflow.panels.subflow.forwardInteractive') }}
          </div>
          <div class="text-muted-foreground text-xs">
            {{
              $t('ai-platform.workflow.panels.subflow.forwardInteractiveHint')
            }}
          </div>
        </div>
        <ElSwitch v-model="forwardInteractive" />
      </div>
    </div>

    <!-- 使用说明 -->
    <ElAlert type="info" :closable="false" show-icon>
      <template #title>
        <span class="text-xs font-medium">{{
          $t('ai-platform.workflow.panels.common.usage')
        }}</span>
      </template>
      <ul class="mt-1 list-inside list-disc text-xs">
        <li>{{ $t('ai-platform.workflow.panels.subflow.usageTip1') }}</li>
        <li>{{ $t('ai-platform.workflow.panels.subflow.usageTip2') }}</li>
        <li>{{ $t('ai-platform.workflow.panels.subflow.usageTip3') }}</li>
        <li>{{ $t('ai-platform.workflow.panels.subflow.usageTip4') }}</li>
        <li>{{ $t('ai-platform.workflow.panels.subflow.usageTip5') }}</li>
      </ul>
    </ElAlert>
  </ElForm>
</template>
