<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

import { $t } from '@easyflow/locales';

import { ArrowDown, Back, VideoPlay } from '@element-plus/icons-vue';
import {
  ElButton,
  ElForm,
  ElFormItem,
  ElIcon,
  ElInput,
  ElMessage,
  ElOption,
  ElSelect,
  ElTable,
  ElTableColumn,
} from 'element-plus';

import { api } from '#/api/request';
import PluginInputAndOutParams from '#/views/ai/plugin/PluginInputAndOutParams.vue';
import PluginRunTestModal from '#/views/ai/plugin/PluginRunTestModal.vue';
import WorkflowApprovalSnapshotPreview from '#/views/system/approval/components/WorkflowApprovalSnapshotPreview.vue';

const route = useRoute();
const router = useRouter();

const toolId = ref<string>((route.query.id as string) || '');
const pluginToolInfo = ref<any>({
  name: '',
  englishName: '',
  description: '',
  basePath: '',
  requestMethod: '',
});
const pluginInfo = ref<any>({});
const pluginInputData = ref<any[]>([]);
const pluginOutputData = ref<any[]>([]);
const pluginInputParamsEditable = ref(false);
const pluginOutputParamsEditable = ref(false);
const isWorkflowPlugin = ref(false);
const pluginUnavailable = ref(false);
const pluginUnavailableReason = ref('');
const workflowSnapshot = ref<any>(null);

const pluginBasicCollapse = ref({
  title: $t('pluginItem.pluginToolEdit.basicInfo'),
  isOpen: true,
  isEdit: false,
});
const pluginBasicCollapseInputParams = ref({
  title: $t('pluginItem.pluginToolEdit.configureInputParameters'),
  isOpen: false,
  isEdit: false,
});
const pluginBasicCollapseOutputParams = ref({
  title: $t('pluginItem.pluginToolEdit.configureOutputParameters'),
  isOpen: false,
  isEdit: false,
});

const pluginInputParamsRef = ref();
const pluginOutputParamsRef = ref();
const saveForm = ref();
const runTestRef = ref();

const rules = reactive({
  name: [{ required: true, message: $t('message.required'), trigger: 'blur' }],
  requestMethod: [
    {
      required: true,
      message: $t('message.required'),
      trigger: 'blur',
    },
  ],
  basePath: [
    { required: true, message: $t('message.required'), trigger: 'blur' },
  ],
  englishName: [
    { required: true, message: $t('message.required'), trigger: 'blur' },
  ],
  description: [
    {
      required: true,
      message: $t('message.required'),
      trigger: 'blur',
      whiteSpace: true,
    },
  ],
});

const requestMethodOptions = [
  {
    label: 'POST',
    value: 'POST',
  },
  {
    label: 'GET',
    value: 'GET',
  },
  {
    label: 'PUT',
    value: 'PUT',
  },
  {
    label: 'DELETE',
    value: 'DELETE',
  },
  {
    label: 'PATCH',
    value: 'PATCH',
  },
];

onMounted(() => {
  if (!toolId.value) {
    return;
  }
  getPluginToolInfo();
});

const workflowParameterRows = computed(() => [
  ...flattenParameterRows(pluginInputData.value, 'input'),
  ...flattenParameterRows(pluginOutputData.value, 'output'),
]);

function getPluginToolInfo() {
  api
    .post('/api/v1/pluginItem/tool/search', {
      aiPluginToolId: toolId.value,
    })
    .then((res) => {
      if (res.errorCode === 0) {
        pluginToolInfo.value = res.data.data;
        pluginInfo.value = res.data.aiPlugin;
        pluginInputData.value = JSON.parse(res.data.data.inputData || '[]');
        pluginOutputData.value = JSON.parse(res.data.data.outputData || '[]');
        isWorkflowPlugin.value = Number(res.data.aiPlugin?.type || 1) === 2;
        pluginUnavailable.value = res.data.aiPlugin?.available === false;
        pluginUnavailableReason.value = res.data.aiPlugin?.reasonMessage || '';
        workflowSnapshot.value = res.data.workflowSnapshot || null;
      }
    });
}

function handleClickHeader(index: number) {
  switch (index) {
    case 1: {
      pluginBasicCollapse.value.isOpen = !pluginBasicCollapse.value.isOpen;
      break;
    }
    case 2: {
      pluginBasicCollapseInputParams.value.isOpen =
        !pluginBasicCollapseInputParams.value.isOpen;
      break;
    }
    case 3: {
      pluginBasicCollapseOutputParams.value.isOpen =
        !pluginBasicCollapseOutputParams.value.isOpen;
      break;
    }
  }
}

function back() {
  router.back();
}

function updatePluginTool(index: number) {
  if (index === 1) {
    if (!saveForm.value) {
      return;
    }
    saveForm.value.validate((valid: boolean) => {
      if (valid) {
        updatePluginToolInfo(index);
      }
    });
    return;
  }
  updatePluginToolInfo(index);
}

function updatePluginToolInfo(index: number) {
  api
    .post('/api/v1/pluginItem/tool/update', {
      id: toolId.value,
      name: pluginToolInfo.value.name,
      englishName: pluginToolInfo.value.englishName,
      description: pluginToolInfo.value.description,
      basePath: pluginToolInfo.value.basePath,
      requestMethod: pluginToolInfo.value.requestMethod,
      inputData: JSON.stringify(pluginInputData.value),
      outputData: JSON.stringify(pluginOutputData.value),
    })
    .then((res) => {
      if (res.errorCode === 0) {
        ElMessage.success($t('message.updateOkMessage'));
        switch (index) {
          case 1: {
            pluginBasicCollapse.value.isEdit = false;
            break;
          }
          case 2: {
            pluginBasicCollapseInputParams.value.isEdit = false;
            break;
          }
          case 3: {
            pluginBasicCollapseOutputParams.value.isEdit = false;
            break;
          }
        }
      }
    });
}

function handleEdit(index: number) {
  if (isWorkflowPlugin.value) {
    return;
  }
  switch (index) {
    case 1: {
      pluginBasicCollapse.value.isEdit = true;
      break;
    }
    case 2: {
      pluginBasicCollapseInputParams.value.isEdit = true;
      pluginBasicCollapseInputParams.value.isOpen = true;
      pluginInputParamsEditable.value = true;
      break;
    }
    case 3: {
      pluginBasicCollapseOutputParams.value.isEdit = true;
      pluginBasicCollapseOutputParams.value.isOpen = true;
      pluginOutputParamsEditable.value = true;
      break;
    }
  }
}

function handleSave(index: number) {
  if (index === 2) {
    pluginInputParamsRef.value.handleSubmitParams();
  }
  if (index === 3) {
    pluginOutputParamsRef.value.handleSubmitParams();
  }
  pluginInputParamsEditable.value = false;
  updatePluginTool(index);
}

function handleCancel(index: number) {
  getPluginToolInfo();
  switch (index) {
    case 1: {
      pluginBasicCollapse.value.isEdit = false;
      break;
    }
    case 2: {
      pluginBasicCollapseInputParams.value.isEdit = false;
      pluginInputParamsEditable.value = false;
      break;
    }
    case 3: {
      pluginBasicCollapseOutputParams.value.isEdit = false;
      pluginOutputParamsEditable.value = false;
      break;
    }
  }
}

function handleOpenRunModal() {
  runTestRef.value.openDialog();
}

function flattenParameterRows(
  parameters: any[] = [],
  direction: 'input' | 'output',
  parentPath = '',
): any[] {
  return parameters.flatMap((item) => {
    const currentName = String(item?.name || '').trim();
    const currentPath = currentName
      ? parentPath
        ? `${parentPath}.${currentName}`
        : currentName
      : parentPath || '-';
    const currentRow = {
      key: String(item?.id || item?.key || currentPath),
      direction,
      name: currentPath,
      type: String(item?.dataType || item?.type || '-'),
    };
    const children = Array.isArray(item?.children)
      ? flattenParameterRows(item.children, direction, currentPath)
      : [];
    return [currentRow, ...children];
  });
}
</script>

<template>
  <div class="accordion-container">
    <div class="controls-header">
      <ElButton :icon="Back" @click="back">
        {{ $t('button.back') }}
      </ElButton>
      <ElButton type="primary" :icon="VideoPlay" @click="handleOpenRunModal">
        {{ $t('pluginItem.pluginToolEdit.trialRun') }}
      </ElButton>
    </div>
    <template v-if="isWorkflowPlugin">
      <div class="workflow-tool-layout">
        <section class="workflow-tool-card">
          <div class="workflow-tool-card__header">
            <div class="workflow-tool-card__title">
              {{ $t('pluginItem.inputData') }} / {{ $t('pluginItem.outputData') }}
            </div>
          </div>
          <ElTable
            :data="workflowParameterRows"
            border
            class="workflow-tool-table"
            empty-text="-"
          >
            <ElTableColumn
              prop="direction"
              :label="$t('pluginItem.direction')"
              width="120"
            >
              <template #default="{ row }">
                {{ row.direction === 'input' ? $t('pluginItem.inputData') : $t('pluginItem.outputData') }}
              </template>
            </ElTableColumn>
            <ElTableColumn
              prop="name"
              :label="$t('pluginItem.parameterName')"
              min-width="280"
            />
            <ElTableColumn
              prop="type"
              :label="$t('pluginItem.parameterType')"
              min-width="160"
            />
          </ElTable>
        </section>

        <section class="workflow-tool-card">
          <div class="workflow-tool-card__header">
            <div class="workflow-tool-card__title">
              快照
            </div>
          </div>
          <WorkflowApprovalSnapshotPreview
            :title="workflowSnapshot?.title || pluginInfo.workflowTitle || pluginToolInfo.name"
            :description="''"
            :content="workflowSnapshot?.content || ''"
          />
        </section>
      </div>
    </template>
    <div v-else class="accordion-list">
      <div
        class="accordion-item"
        :class="{ 'accordion-item--active': pluginBasicCollapse.isOpen }"
      >
        <div class="accordion-header" @click="handleClickHeader(1)">
          <div class="column-header-container">
            <div
              class="accordion-icon"
              :class="{ 'accordion-icon--rotated': pluginBasicCollapse.isOpen }"
            >
              <ElIcon size="16">
                <ArrowDown />
              </ElIcon>
            </div>
            <h3 class="accordion-title">{{ pluginBasicCollapse.title }}</h3>
          </div>
          <div v-if="!isWorkflowPlugin">
            <ElButton
              v-if="!pluginBasicCollapse.isEdit"
              type="primary"
              @click.stop="handleEdit(1)"
            >
              {{ $t('button.edit') }}
            </ElButton>
            <ElButton
              v-if="pluginBasicCollapse.isEdit"
              @click.stop="handleCancel(1)"
            >
              {{ $t('button.cancel') }}
            </ElButton>
            <ElButton
              v-if="pluginBasicCollapse.isEdit"
              type="primary"
              @click.stop="handleSave(1)"
            >
              {{ $t('button.save') }}
            </ElButton>
          </div>
          <ElTag v-else type="info" effect="plain">
            {{ $t('pluginItem.systemManaged') }}
          </ElTag>
        </div>

        <div
          class="accordion-content"
          :class="{ 'accordion-content--open': pluginBasicCollapse.isOpen }"
        >
          <div class="accordion-content-inner">
            <div v-show="pluginBasicCollapse.isEdit">
              <div class="plugin-tool-info-edit-container">
                <ElForm
                  ref="saveForm"
                  :model="pluginToolInfo"
                  label-width="80px"
                  status-icon
                  :rules="rules"
                >
                  <ElFormItem :label="$t('pluginItem.name')" prop="name">
                    <ElInput v-model.trim="pluginToolInfo.name" />
                  </ElFormItem>
                  <ElFormItem
                    :label="$t('pluginItem.englishName')"
                    prop="englishName"
                  >
                    <ElInput v-model.trim="pluginToolInfo.englishName" />
                  </ElFormItem>
                  <ElFormItem
                    :label="$t('pluginItem.pluginToolEdit.toolPath')"
                    prop="basePath"
                  >
                    <ElInput v-model.trim="pluginToolInfo.basePath">
                      <template #prepend>{{ pluginInfo.baseUrl }}</template>
                    </ElInput>
                  </ElFormItem>
                  <ElFormItem
                    :label="$t('pluginItem.description')"
                    prop="description"
                  >
                    <ElInput
                      v-model.trim="pluginToolInfo.description"
                      type="textarea"
                      :rows="4"
                    />
                  </ElFormItem>
                  <ElFormItem
                    :label="$t('pluginItem.pluginToolEdit.requestMethod')"
                    prop="requestMethod"
                  >
                    <ElSelect
                      v-model="pluginToolInfo.requestMethod"
                      :placeholder="$t('ui.placeholder.select')"
                    >
                      <ElOption
                        v-for="option in requestMethodOptions"
                        :key="option.value"
                        :label="option.label"
                        :value="option.value"
                      />
                    </ElSelect>
                  </ElFormItem>
                </ElForm>
              </div>
            </div>
            <div
              v-show="!pluginBasicCollapse.isEdit"
              class="plugin-tool-info-view-container"
            >
              <div class="plugin-tool-view-item">
                <div class="view-item-title">{{ $t('pluginItem.name') }}:</div>
                <div>{{ pluginToolInfo.name }}</div>
              </div>
              <div class="plugin-tool-view-item">
                <div class="view-item-title">
                  {{ $t('pluginItem.englishName') }}:
                </div>
                <div>{{ pluginToolInfo.englishName }}</div>
              </div>
              <div class="plugin-tool-view-item">
                <div class="view-item-title">
                  {{ $t('pluginItem.description') }}:
                </div>
                <div>{{ pluginToolInfo.description }}</div>
              </div>
              <div v-if="isWorkflowPlugin" class="plugin-tool-view-item">
                <div class="view-item-title">
                  {{ $t('pluginItem.pluginToolEdit.workflowTarget') }}:
                </div>
                <div>{{ pluginInfo.workflowTitle || '-' }}</div>
              </div>
              <template v-else>
                <div class="plugin-tool-view-item">
                  <div class="view-item-title">
                    {{ $t('pluginItem.pluginToolEdit.toolPath') }}:
                  </div>
                  <div>{{ pluginInfo.baseUrl }}{{ pluginToolInfo.basePath }}</div>
                </div>
                <div class="plugin-tool-view-item">
                  <div class="view-item-title">
                    {{ $t('pluginItem.pluginToolEdit.requestMethod') }}:
                  </div>
                  <div>
                    {{ pluginToolInfo.requestMethod }}
                  </div>
                </div>
              </template>
            </div>
          </div>
        </div>
      </div>

      <div
        class="accordion-item"
        :class="{
          'accordion-item--active': pluginBasicCollapseInputParams.isOpen,
        }"
      >
        <div class="accordion-header" @click="handleClickHeader(2)">
          <div class="column-header-container">
            <div
              class="accordion-icon"
              :class="{
                'accordion-icon--rotated':
                  pluginBasicCollapseInputParams.isOpen,
              }"
            >
              <ElIcon size="16">
                <ArrowDown />
              </ElIcon>
            </div>
            <h3 class="accordion-title">
              {{ pluginBasicCollapseInputParams.title }}
            </h3>
          </div>
          <div v-if="!isWorkflowPlugin">
            <ElButton
              v-if="!pluginBasicCollapseInputParams.isEdit"
              type="primary"
              @click.stop="handleEdit(2)"
            >
              {{ $t('button.edit') }}
            </ElButton>
            <ElButton
              v-if="pluginBasicCollapseInputParams.isEdit"
              @click.stop="handleCancel(2)"
            >
              {{ $t('button.cancel') }}
            </ElButton>
            <ElButton
              v-if="pluginBasicCollapseInputParams.isEdit"
              type="primary"
              @click.stop="handleSave(2)"
            >
              {{ $t('button.save') }}
            </ElButton>
          </div>
        </div>

        <div
          class="accordion-content"
          :class="{
            'accordion-content--open': pluginBasicCollapseInputParams.isOpen,
          }"
        >
          <div class="accordion-content-inner">
            <PluginInputAndOutParams
              ref="pluginInputParamsRef"
              v-model="pluginInputData"
              :editable="pluginInputParamsEditable"
              :is-edit-output="false"
            />
          </div>
        </div>
      </div>

      <div
        class="accordion-item"
        :class="{
          'accordion-item--active': pluginBasicCollapseOutputParams.isOpen,
        }"
      >
        <div class="accordion-header" @click="handleClickHeader(3)">
          <div class="column-header-container">
            <div
              class="accordion-icon"
              :class="{
                'accordion-icon--rotated':
                  pluginBasicCollapseOutputParams.isOpen,
              }"
            >
              <ElIcon size="16">
                <ArrowDown />
              </ElIcon>
            </div>
            <h3 class="accordion-title">
              {{ pluginBasicCollapseOutputParams.title }}
            </h3>
          </div>
          <div v-if="!isWorkflowPlugin">
            <ElButton
              v-if="!pluginBasicCollapseOutputParams.isEdit"
              type="primary"
              @click.stop="handleEdit(3)"
            >
              {{ $t('button.edit') }}
            </ElButton>
            <ElButton
              v-if="pluginBasicCollapseOutputParams.isEdit"
              @click.stop="handleCancel(3)"
            >
              {{ $t('button.cancel') }}
            </ElButton>
            <ElButton
              v-if="pluginBasicCollapseOutputParams.isEdit"
              type="primary"
              @click.stop="handleSave(3)"
            >
              {{ $t('button.save') }}
            </ElButton>
          </div>
        </div>

        <div
          class="accordion-content"
          :class="{
            'accordion-content--open': pluginBasicCollapseOutputParams.isOpen,
          }"
        >
          <div class="accordion-content-inner">
            <PluginInputAndOutParams
              ref="pluginOutputParamsRef"
              v-model="pluginOutputData"
              :editable="pluginOutputParamsEditable"
              :is-edit-output="true"
            />
          </div>
        </div>
      </div>
    </div>
    <PluginRunTestModal ref="runTestRef" :plugin-tool-id="toolId" />
  </div>
</template>

<style scoped>
.accordion-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 24px;
}

.controls-header {
  display: flex;
  gap: 12px;
  align-items: center;
  justify-content: space-between;
}

.accordion-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.workflow-tool-layout {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.workflow-tool-card {
  padding: 20px;
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color-light);
  border-radius: 16px;
}

.workflow-tool-card__header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  margin-bottom: 16px;
}

.workflow-tool-card__title {
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.workflow-tool-table {
  width: 100%;
}

.accordion-item {
  overflow: hidden;
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color-light);
  border-radius: 16px;
}

.accordion-item--active {
  border-color: var(--el-color-primary-light-5);
}

.accordion-header {
  display: flex;
  gap: 16px;
  align-items: center;
  justify-content: space-between;
  padding: 18px 20px;
  cursor: pointer;
}

.column-header-container {
  display: flex;
  gap: 10px;
  align-items: center;
}

.accordion-icon {
  display: inline-flex;
  transition: transform 0.2s ease;
}

.accordion-icon--rotated {
  transform: rotate(180deg);
}

.accordion-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.accordion-content {
  display: grid;
  grid-template-rows: 0fr;
  transition: grid-template-rows 0.2s ease;
}

.accordion-content--open {
  grid-template-rows: 1fr;
}

.accordion-content-inner {
  min-height: 0;
  padding: 0 20px 20px;
  overflow: hidden;
}

.plugin-tool-info-view-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.plugin-tool-view-item {
  display: flex;
  gap: 8px;
  line-height: 22px;
}

.view-item-title {
  min-width: 108px;
  color: var(--el-text-color-secondary);
}

</style>
