<template>
  <el-form :inline="true" :model="sdAgentNodeData" :rules="rules" ref="dynamicFormRef" class="http-form"
    label-position="top" label-width="auto">
    <el-collapse v-model="activeNames">
      <el-collapse-item name="1" title="请求配置" icon-position="left">
        <div class="form__container">
          <div v-for="(property, index) in sdAgentNodeData.config" :key="index">
            <el-row>
              <el-form-item :label="index === 0 ? '参数名' : ''" :prop="`config.${index}.name`" :rules="[
                { required: true, message: '请输入参数名', trigger: 'blur' },
              ]">
                <el-input :disabled="true" class="param-name" v-model="property.name" placeholder="请输入" clearable />
              </el-form-item>
              <el-form-item :label="index === 0 ? '参数值' : ''" :prop="`config.${index}.input`">
                <el-select v-model="property.type" class="param-type" @change="handleTypeChange(index)">
                  <el-option label="引用" value="quote" />
                  <el-option label="输入" value="input" />
                </el-select>
                <el-form-item v-if="property.type === 'input'" :rules="[
                  {
                    required: property?.required ?? true,
                    message: '请输入参数值',
                    trigger: 'blur',
                  },
                ]" :prop="`config.${index}.input`">
                  <el-input-number class="param-value" v-if="property.componentType === 'number'"
                    v-model="property.input" :min="0" :max="property.max || Infinity" :controls="false"
                    :step-strictly="true" placeholder="请输入" clearable />
                  <el-select v-model="property.input" class="param-value"
                    v-else-if="property.componentType === 'select'">
                    <el-option v-for="item in property.selectOptions" :key="item.value" :label="item.label"
                      :value="item.value" />
                  </el-select>
                  <el-input class="param-value" v-else v-model="property.input" placeholder="请输入" clearable />
                </el-form-item>
                <el-form-item v-if="property.type === 'quote'" :rules="[
                  {
                    required: true,
                    message: '请选择参数值',
                    trigger: 'blur',
                  },
                ]" :prop="`config.${index}.quote`">
                  <el-cascader :ref="(el) => {
                    if (el) cascaderRefs[index] = el;
                  }
                    " v-model="property.quote" :checkStrictly="true" :options="quoteOptions" placeholder="请选择"
                    @visible-change="
                      (visible) => visibleChange(visible, index, property.quote)
                    " @change="(value) => cascaderChange(value, index, sdAgentNodeData, 'config')" />
                </el-form-item>
              </el-form-item>
            </el-row>
          </div>
          <el-row>
            <span style="margin-right: 24px">是否调用TTS接口</span>
            <el-switch size="small" v-model="sdAgentNodeData.invokeTts" @change="handleTtsChange" />
          </el-row>
          <div v-if="sdAgentNodeData.invokeTts">
            <div style="margin: 10px 0">TTS参数设置</div>
            <div v-for="(property, index) in sdAgentNodeData.tts" :key="index">
              <el-row>
                <el-form-item :label="index === 0 ? '参数名' : ''" :prop="`tts.${index}.name`" :rules="[
                  { required: true, message: '请输入参数名', trigger: 'blur' },
                ]">
                  <el-input :disabled="true" class="param-name" v-model="property.name" placeholder="请输入" clearable />
                </el-form-item>
                <el-form-item :label="index === 0 ? '参数值' : ''" :prop="`tts.${index}.input`">
                  <el-select v-model="property.type" class="param-type" @change="handleTypeChange(index)">
                    <el-option label="引用" value="quote" />
                    <el-option label="输入" value="input" />
                  </el-select>
                  <el-form-item v-if="property.type === 'input'" :rules="[
                    {
                      required: property?.required ?? true,
                      message: '请输入参数值',
                      trigger: 'blur',
                    },
                  ]" :prop="`tts.${index}.input`">
                    <el-input-number class="param-value" v-if="property.componentType === 'number'"
                      v-model="property.input" :min="0" :max="property.max || Infinity" :controls="false"
                      :step-strictly="true" placeholder="请输入" clearable />
                    <el-select v-model="property.input" class="param-value"
                      v-else-if="property.componentType === 'select'">
                      <el-option v-for="item in property.selectOptions" :key="item.value" :label="item.label"
                        :value="item.value" />
                    </el-select>
                    <el-input class="param-value" v-else v-model="property.input" placeholder="请输入" clearable />
                  </el-form-item>
                  <el-form-item v-if="property.type === 'quote'" :rules="[
                    {
                      required: true,
                      message: '请选择参数值',
                      trigger: 'blur',
                    },
                  ]" :prop="`tts.${index}.quote`">
                    <el-cascader :ref="(el) => {
                      if (el) cascaderRefs[index] = el;
                    }
                      " v-model="property.quote" :checkStrictly="true" :options="quoteOptions" placeholder="请选择"
                      @visible-change="
                        (visible) => visibleChange(visible, index, property.quote)
                      " @change="(value) => cascaderChange(value, index, sdAgentNodeData, 'tts')" />
                  </el-form-item>
                </el-form-item>
              </el-row>
            </div>
          </div>
        </div>
      </el-collapse-item>
      <el-collapse-item name="3" icon-position="left">
        <template #title>
          输出参数
          <el-tooltip class="box-item" effect="dark" content="这里定义的输出变量可以被后续节点引用。" placement="top">
            <el-icon class="header-icon" style="margin-left: 6px">
              <info-filled />
            </el-icon>
          </el-tooltip>
          <el-button :circle="true" size="small" @click="(e) => addSdAgentItem(e)" class="addFormItem">
            <el-icon :size="14">
              <Plus />
            </el-icon>
          </el-button>
        </template>
        <div class="form__container">
          <el-form :inline="true" :model="sdAgentNodeData" label-position="top" label-width="auto" :rules="outputRules"
            ref="outputFormRef">
            <FormItemRecursive formType="output" :current-list="sdAgentNodeData.outputParams" prop-path="outputParams"
              :depth="0" :is-first-level="true" :endDepth="2" :parent-path="[]"
              @delete-item="(path) => deleteSdAgentItem(path, 'outputParams')" />
          </el-form>
        </div>
      </el-collapse-item>
    </el-collapse>
  </el-form>
</template>

<script setup>
import { ref, reactive, watch, nextTick } from 'vue'
import { Plus, Minus } from '@element-plus/icons-vue'
import FormItemRecursive from '../FormItemRecursive.vue'
import { getInput, transformSdAgentNodeData } from '@/utils/flow'
import { useQuote } from './useQuote.js'

const props = defineProps({
  data: Object
})

const emit = defineEmits(['save-success', 'save-error'])

const formData = reactive({
  nodeParams: [],
  outputParams: []
})

const rules = reactive({})
const outputRules = reactive({})
const dynamicFormRef = ref()
const outputFormRef = ref()
const activeNames = ref(['1', '2'])

// 使用共享的 quote 逻辑
const { quoteOptions, cascaderRefs, handleTypeChange, cascaderChange, visibleChange } = useQuote(props.data.id)

// 添加表单项
const addFormItem = (e, type) => {
  e.stopPropagation()
  const obj = {
    name: '',
    type: type === 'nodeParams' ? 'input' : 'string',
    required: false,
    children: [],
    input: ''
  }
  if (!formData[type]) formData[type] = []
  formData[type].push(obj)
}

// 商道智能体
const sdAgentNodeData = ref({})

const voiceOptions = () => {
  return [{
    value: 'x4_xiaoyan',
    label: 'x4_xiaoyan'
  }]
}

const handleTtsChange = (val) => {
  if (val) {
    sdAgentNodeData.value.tts = []
    if (!sdAgentNodeData.value.tts || sdAgentNodeData.value.tts.length === 0) {
      sdAgentNodeData.value.tts = [
        { name: 'url', type: "input", input: "", disabled: true },
        { name: 'text', type: "input", input: "", disabled: true },
        { name: 'speed', type: "input", input: "", max: 100, disabled: true },
        { name: 'voice', type: "input", input: "", componentType: 'select', selectOptions: voiceOptions(), disabled: true },
        { name: 'volume', type: "input", input: "", componentType: 'number', max: 100, disabled: true }
      ]
    }
  }
}

const addSdAgentItem = (e) => {
  e.stopPropagation();
  sdAgentNodeData.value.outputParams.push({ name: "", type: "string", input: "" });
}

const deleteSdAgentItem = (fullPath, propPath) => {
  // 从顶层数据开始查找
  let currentLevel = sdAgentNodeData.value[propPath];

  // 遍历路径（除最后一个索引，因为最后一个是要删除的项）
  for (let i = 0; i < fullPath.length - 1; i++) {
    const index = fullPath[i];
    // 进入下一层级
    currentLevel = currentLevel[index].children;
  }

  // 最后一个索引是当前层级要删除的项
  const lastIndex = fullPath[fullPath.length - 1];
  currentLevel.splice(lastIndex, 1);
}

// 初始化数据
const initData = () => {
  const nodeParams = JSON.parse(JSON.stringify(props.data.properties.nodeParams || []))
  const outputParams = JSON.parse(JSON.stringify(props.data.properties.outputParams || []))
  const transformedData = transformSdAgentNodeData(nodeParams);
  sdAgentNodeData.value = {
    ...transformedData,
    outputParams
  };
}

watch(
  () => props.data,
  () => {
    initData()
  },
  { immediate: true, deep: true }
)

// 保存验证
const validateAndSave = async () => {
  let inputValid = true
  let outputValid = true
  if (dynamicFormRef.value) {
    await dynamicFormRef.value.validate((valid) => { if (!valid) inputValid = false })
  }
  if (outputFormRef.value) {
    await outputFormRef.value.validate((valid) => { if (!valid) outputValid = false })
  }

  const nodeParams = []
  nodeParams.push({ name: "config", type: "input", input: "", children: sdAgentNodeData.value.config, required: true })
  nodeParams.push({ name: "invokeTts", type: "input", input: sdAgentNodeData.value.invokeTts })
  if (sdAgentNodeData.value.invokeTts) {
    nodeParams.push({ name: "tts", type: "input", input: "", children: sdAgentNodeData.value.tts })
  }
  lf.setProperties(props.data.id, {
    ...props.data.properties,
    nodeParams,
    outputParams: sdAgentNodeData.value.outputParams
  });


  if (inputValid && outputValid) {
    emit('save-success')
  } else {
    emit('save-error')
  }
}

defineExpose({ validateAndSave })
</script>

<style lang="scss" scoped>
.http-form {
  width: 100%;

  .el-collapse {
    width: 100%;
  }
}

.form__container {
  margin: 12px 0;

  :deep(.el-row) {
    align-items: end;

    .el-form-item {
      margin-right: 12px;
    }

    .param-name {
      width: 160px;
    }

    .param-type {
      width: 80px;
    }

    .param-value {
      width: 160px;
    }

  }



  .sub-properties {
    margin-left: 10px;

    .zw {
      margin-left: 15px;

      &::before {
        content: "";
        position: absolute;
        left: 0;
        top: -4px;
        width: 10px;
        border-left: 1px solid gray;
        border-bottom: 1px solid gray;
        border-bottom-left-radius: 4px;
        background-color: transparent;
        height: 24px;
      }
    }
  }

  .gSon-properties {
    margin-left: 10px;

    .zw {
      margin-left: 15px;

      &::before {
        content: "";
        position: absolute;
        left: 0;
        top: -4px;
        width: 10px;
        border-left: 1px solid gray;
        border-bottom: 1px solid gray;
        border-bottom-left-radius: 4px;
        background-color: transparent;
        height: 24px;
      }
    }
  }

  .deleteBtn {
    margin-bottom: 22px;
    cursor: pointer;
  }
}
</style>
