<template>
  <div>
    <div class="back-wap cursor-pointer mb-20px" @click="goChatIndex">
      <icon-left size="16" class="color-#737478 mr-4px" />
      <span class="cs">返回空间</span>
    </div>
    <div class="workflow-container">
      <div class="left-wap mr-24px" v-if="isCollapsed == false">
        <div class="w-full w-100% mb-15px h-160px rounded-8px bg-#E6E6E8" v-image-main-color="cozeInfo.image_url">
          <img v-if="cozeInfo?.image_url" :src="cozeInfo?.image_url" class="w-full h-full object-contain" />
        </div>
        <div class="content mb-15px">
          <div class="title-body">
            <div class="text mr-4px">{{ cozeInfo.name }}</div>
            <div data-尺寸="迷你-20px" data-颜色="red" class="tag-body">
              <div class="">
                <SvgIcon size="12" name="svg-workflow" class="color-#F64B31" />
              </div>
              <div class="text">工作流</div>
            </div>
          </div>
          <div class="use-body flex items-center">
            <div class="num mr-2px">{{ formatNumberShow({ value: cozeInfo?.views, showExactValue: true }) }}</div>
            <div class="text">次使用</div>
          </div>
        </div>
        <div class="description">
          <div class="text">
            {{ cozeInfo.description }}
          </div>
        </div>
        <div class="out-line">
          <div class="out-line-div"></div>
        </div>
        <div class="history">
          <div class="section">
            <div class="text">历史对话</div>
          </div>
          <div class="history-item" v-for="(item, index) in history">
            <div class="item-body">
              <div class="text ellipsis-title" @click="getHistoryInfo(item)">
                {{ item.title }}
              </div>
              <a-trigger trigger="click" position="bottom" :auto-fit-position="true" :unmount-on-close="true">
                <SvgIcon size="12" name="svg-more" class="color-#6D4CFE" style="float: right" />
                <template #content>
                  <div class="">
                    <div class="history-item-dropdown">
                      <div class="dropdown-item ">
                        <SvgIcon size="12" name="svg-pin" class="icon color-#6D4CFE" />
                        <div @click="(event) => handleTop(item.id, item.sort, event)" class="text">
                          {{ item.sort > 1 ? '取消置顶' : '置顶' }}
                        </div>
                      </div>
                      <!--                        <div class="dropdown-item">-->
                      <!--                          <SvgIcon size="12" name="svg-edit" class="icon color-#6D4CFE" />-->
                      <!--                          <div @click="editTitle(item)" class="text">重命名</div>-->
                      <!--                        </div>-->
                      <div class="dropdown-item">
                        <SvgIcon size="12" name="svg-delete" class="icon color-#6D4CFE" />
                        <a-popconfirm
                          content="你确认删除该历史对话吗"
                          @ok="deleteHistory(item.id, index)"
                          type="error"
                        >
                          <div class="text delete">删除</div>
                        </a-popconfirm>
                      </div>
                    </div>
                  </div>
                </template>
              </a-trigger>
            </div>
          </div>
        </div>
      </div>
      <div class="right-wap">
        <div class="header">
          <div class="body">
            <div class="">
              <div class="toggle-btn cursor-pointer" @click="toggleCollapse">
                <a-tooltip :content="isCollapsed ? '展开' : '折叠'">
                  <img class="status-icon" :src="isCollapsed ? menuUnfold : menuFold" />
                </a-tooltip>
              </div>
            </div>
          </div>
        </div>
        <div class="content">
          <div class="form">
            <DynamicForm :formFields="formFields.form" :formData="formData" :loading="loading" @submit="handleSubmit" />
          </div>
          <div class="res">
            <a-spin v-if="loading" class="spin-center" tip="生成中。。。" />
            <div v-if="workFlowRes.output != '' && loading === false" v-html="renderedMarkdown"></div>
            <NoData v-if="workFlowRes.output == '' && loading === false" />
          </div>
        </div>
      </div>
    </div>

    <a-modal style="width: 500px" v-model:visible="editHistoryVisible">
      <template #title> Title</template>
      <div></div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import DynamicForm from './components/DynamicForm.vue';
import {
  executeWorkFlow,
  getWorkFlowInfo,
  delWorkflowHistoryApi,
  getSyncWorkflowTaskApi,
  topWorkflowHistoryApi,
  getWorkflowHistoryListApi,
  cancelTopWorkflowHistoryApi,
} from '@/api/all/agent';
import { useRoute, useRouter } from 'vue-router';
import { marked } from 'marked';
import DOMPurify from 'dompurify';
import menuFold from '@/assets/svg/menu-fold.svg';
import menuUnfold from '@/assets/svg/menu-unfold.svg';
import { formatNumberShow } from '@/utils/tools';
// import { WORKEXECUTE_STATUS } from '../AgentConstants.ts';

const editHistoryVisible = ref(false);

const formFields = ref({});
const history = ref([]);
// 是否折叠状态
const isCollapsed = ref(false);

// 切换折叠状态
const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value;
};
// 表单数据对象（动态生成初始值）
const formData = ref({});

const route = useRoute();
const id = route.query.id;
const query = reactive({
  id: id,
});
const router = useRouter();
const goChatIndex = async () => {
  router.push({
    path: '/agent/index',
  });
};
const loading = ref(false);

const cozeInfo = reactive({
  name: '',
  description: '',
  icon_url: '',
  workflow_id: '',
});
const getData = async () => {
  const { code, data } = await getWorkFlowInfo(query.id);
  Object.assign(cozeInfo, data.info);
  formFields.value = data.form_config;
  history.value = data.history;
};
const workFlowRes = reactive({
  output: '',
  execute_id: '',
});

// 渲染 Markdown 的计算属性
const renderedMarkdown = computed(() => {
  if (workFlowRes?.output) {
    const rawHtml = marked.parse(workFlowRes.output || '');
    return DOMPurify.sanitize(rawHtml); // 防止 XSS 攻击
  }
  return '';
});

const deleteHistory = async (id, index) => {
  const { code } = await delWorkflowHistoryApi(id);
  if (code === 200) {
    history.value.splice(index, 1);
  }
};

const historyForm = reactive({
  id: 0,
  title: '',
});

const editTitle = async (item) => {
  historyForm.id = item.id;
  historyForm.title = item.title;
  editHistoryVisible.value = true;
};

const handleTop = async (id, sort, event) => {
  if (sort > 0) {
    canceltopHistory(id);
  } else {
    topHistory(id);
  }
  event.stopPropagation();
};

//置顶
const topHistory = async (id, sort) => {
  const { code, message } = await topWorkflowHistoryApi(id);
  if (code === 200) {
    AMessage.success(message);
    getWorkflowHistoryList();
  }
};
//取消置顶
const canceltopHistory = async (id, sort) => {
  const { code, message } = await cancelTopWorkflowHistoryApi(id);
  if (code === 200) {
    AMessage.success(message);
    getWorkflowHistoryList();
  }
};

const getWorkflowHistoryList = async () => {
  const { code, data } = await getWorkflowHistoryListApi({
    workflow_id: cozeInfo.workflow_id,
  });
  if (code === 200) {
    history.value = data.list;
  }
};

// 提交表单
const handleSubmit = async (formData) => {
  try {
    const param = { form_data: formData, workflow_id: cozeInfo.workflow_id, bot_id: formFields.value.bot_id };
    workFlowRes.output = '';
    loading.value = true;
    const { code, data } = await executeWorkFlow(param);
    if (code === 200) {
      workFlowRes.execute_id = data.execute_id;
      startTask();
    }
  } catch (error) {
    loading.value = false;
  }
};

const timerRef = ref(null);
const startTask = () => {
  if (timerRef.value !== null) return;
  timerRef.value = setInterval(async () => {
    getSyncWorkflowTask();
  }, 3000);
};

const getSyncWorkflowTask = async () => {
  try {
    const { code, data } = await getSyncWorkflowTaskApi({
      execute_id: workFlowRes.execute_id,
      workflow_id: cozeInfo.workflow_id,
    });
    if (code === 200) {
      if (data.execute_status === 'Success' || data.execute_status === 'Fail') {
        workFlowRes.output = data.output;
        clearTimeout();
        if (!isEmpty(data.history)) {
          addHistoryItem(data.history);
        }
      }
    }
  } catch (error) {
    clearTimeout();
  }
};

const clearTimeout = async () => {
  clearInterval(timerRef.value);
  timerRef.value = null;
  loading.value = false;
};

const addHistoryItem = (item) => {
  history.value.unshift(item);
};

const getHistoryInfo = (item) => {
  formData.value = item.param;
  workFlowRes.output = item.output;

  console.log(formData.value, 'formData');
};

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

<style scoped lang="scss">
@import './style.scss';
</style>
