yangyin
2024-10-16 9b5a94232d5eb17fb3b0621ad691d0cdd73db5bb
src/views/project/yw/lowCode/sqlAmis/SqlAmis.vue
@@ -1,8 +1,584 @@
<template>
   <div>
   </div>
   <AHMContainer type="card" v-if="supervisorMgrShow">
      <template #aside>
         <!-- 目录树 -->
         <LeftTreeByMgr
            v-loading="treeLoading"
            class="h100"
            ref="leftTreeRef"
            :defaultProps="{
               id: 'group_id',
               label: 'group_name',
               children: 'children',
            }"
            :treedata="listTreeData"
            title-name="分组列表"
            :show-more-operate="false"
            defaultExpandAll
            :show-add="false"
            :current-node-key="currentListID"
            :node-icon="() => 'ele-Document'"
            @click="handleClickNode"
         >
         </LeftTreeByMgr>
      </template>
      <template #header>
         <el-form ref="queryFormRef" :inline="true" :model="queryParams">
            <el-form-item label="标题" prop="title">
               <el-input v-model="queryParams.title" style="width: 226.4px" placeholder="标题" clearable />
            </el-form-item>
            <el-form-item>
               <el-button type="primary" icon="ele-Search" @click="handleQueryTable"> 查询 </el-button>
               <el-button icon="ele-Refresh" @click="resetQuery">重置 </el-button>
               <el-button icon="ele-Plus" @click="openOptDlg()"> 添加 </el-button>
            </el-form-item>
         </el-form>
      </template>
      <template #main>
         <div class="h-full flex-column">
            <div class="flex-0 flex">
               <ColFilter class="ml-auto" :columnList="columnList" />
            </div>
            <el-table
               v-loading="tableLoading"
               ref="draggableTableRef"
               class="flex-auto"
               border
               :row-class-name="isDragStatus ? 'cursor-move' : 'cursor-pointer'"
               :data="displayTableData"
               highlight-current-row
            >
               <template v-for="item in columnList" :key="item.prop">
                  <el-table-column
                     v-if="item.isShow ?? true"
                     :prop="item.prop"
                     :label="item.label"
                     :fixed="item.fixed"
                     :width="item.width"
                     showOverflowTooltip
                  >
                     <template #default="scope" v-if="item.prop === 'published'">
                        <el-tag :type="scope.row.published === SupervisorPublished.Y ? 'primary' : 'info'">{{
                           supervisorPublishedMap[scope.row.published]
                        }}</el-tag>
                     </template>
                     <template #default="scope" v-else-if="item.prop === 'operate'">
                        <div class="space-x-3 items-center flex">
                           <el-tooltip effect="dark" content="AMIS低代码编辑" placement="top">
                              <i class="ywifont ywicon-didaima !text-[21px] text-blue-400 cursor-pointer" @click="gotoAmisPage(scope.row)"></i>
                           </el-tooltip>
                           <el-tooltip effect="dark" content="数据对接" placement="top">
                              <i class="ywifont ywicon-sjdj !text-[17px] text-blue-400 cursor-pointer" @click="editSqlClick(scope.row)"></i>
                           </el-tooltip>
                           <el-tooltip effect="dark" content="对话测试" placement="top">
                              <i class="ywifont ywicon-ceshi !text-[20px] text-blue-400 cursor-pointer" @click="openChatTest(scope.row)"></i>
                           </el-tooltip>
                           <el-tooltip
                              effect="dark"
                              :content="scope.row.published === SupervisorPublished.Y ? '取消发布' : '发布'"
                              placement="top"
                           >
                              <i
                                 class="ywifont !text-[20px] cursor-pointer"
                                 :class="[
                                    scope.row.published === SupervisorPublished.Y ? 'ywicon-quxiaofabu text-red-400' : 'ywicon-fabu text-blue-400',
                                 ]"
                                 @click="
                                    publishStatusChange(
                                       scope.row.published === SupervisorPublished.Y ? SupervisorPublished.N : SupervisorPublished.Y,
                                       scope.row.id,
                                       scope.$index
                                    )
                                 "
                              ></i>
                           </el-tooltip>
                           <el-tooltip effect="dark" content="编辑" placement="top">
                              <i class="ywifont ywicon-bianji !text-[15px] text-blue-400 cursor-pointer" @click="openOptDlg(scope.row)"></i>
                           </el-tooltip>
                           <el-tooltip effect="dark" content="删除" placement="top">
                              <i
                                 class="ywifont ywicon-shanchu !text-[17px] text-red-400 cursor-pointer"
                                 @click="
                                    () => {
                                       deleteCurrentRow(scope.row, '页面', supervisorAdminApi.deleteSupervisor, () => {
                                          const foundIndex = tableData.findIndex((item) => item === scope.row);
                                          foundIndex > -1 && tableData.splice(foundIndex, 1);
                                       });
                                    }
                                 "
                              ></i>
                           </el-tooltip>
                        </div>
                     </template>
                  </el-table-column>
               </template>
            </el-table>
            <div
               v-if="chatTestIsShow"
               ref="draggableChatRef"
               :style="style"
               class="fixed z-50 w-[700px] h-[800px] flex flex-col bg-[rgb(239,244,253)] right-0 bottom-0 rounded-lg"
            >
               <div ref="chatDragHandlerRef" class="flex-0">
                  <div class="flex items-center justify-between py-2 px-4">
                     <div class="font-bold cursor-move">
                        WI水务智能管家——【{{ chatTestMapRow?.title }}】测试
                        <!-- <img src="/static/images/logo/logo-mini.svg" width="10" height="10" /> -->
                     </div>
                     <i class="ywifont ywicon-guanbi font-[10px] font-bold cursor-pointer" @click="closeChatTest"></i>
                  </div>
               </div>
               <Chat ref="chatRef" class="flex-auto px-2" :questionApi="questionAi"> </Chat>
            </div>
         </div>
      </template>
      <OptDlg v-model="optDlgIsShow" :item="optDlgMapRow" @insert="insertOpt" @update="updateOpt" :groupId="currentListID"></OptDlg>
      <!-- 增加、修改数据对话框 -->
      <el-dialog
         :destroy-on-close="true"
         v-model="moduleDialogIsShow"
         width="300"
         :close-on-click-modal="false"
         @closed="closeModuleDialog"
      >
         <template #header>
            <div style="color: #fff">
               <SvgIcon :name="moduleDialogHeaderIcon" :size="16" style="margin-right: 3px; display: inline; vertical-align: middle" />
               <span> {{ moduleDialogTitle }} </span>
            </div>
         </template>
         <el-form :model="moduleDialogFormValue" ref="moduleDialogFormRef" :rules="moduleDialogFormRules" label-width="55">
            <el-form-item label="名称" prop="title">
               <el-input placeholder="请输入名称" v-model="moduleDialogFormValue.title"></el-input>
            </el-form-item>
            <el-form-item label="父级" prop="parent_id" v-if="!isEditModuleDialog">
               <el-tree-select
                  filterable
                  class="w100"
                  v-model="moduleDialogFormValue.parent_id"
                  :props="{
                     id: 'id',
                     label: 'title',
                     children: 'children',
                  }"
                  defaultExpandAll
                  :data="parentSelectOptions"
                  node-key="id"
                  :clearable="true"
                  :accordion="false"
                  :expandNode="false"
                  :check-strictly="true"
                  placeholder="请选择父级"
               >
               </el-tree-select>
            </el-form-item>
         </el-form>
         <template #footer>
            <div>
               <el-button @click="closeModuleDialog">取 消</el-button>
               <el-button type="primary" @click="submitModuleFormValue">确 定</el-button>
            </div>
         </template>
      </el-dialog>
   </AHMContainer>
   <SqlAmisEdit
      v-else
      :supervisor="sqlEditMapSupervisor"
      @backLastPage="backLastPage"
      @updatePublished="updatePublishedById"
   ></SqlAmisEdit>
</template>
<script setup lang="ts"></script>
<script setup lang="ts">
import { useDraggable } from '@vueuse/core';
import { travelTree } from '/@/utils/util';
import { computed, onMounted, ref } from 'vue';
import { usePageDisplay } from '/@/hooks/usePageDisplay';
import { useQueryTable } from '/@/hooks/useQueryTable';
// import { useTableSort } from '/@/hooks/useTableSort';
// import { useValidateUniqueness } from '/@/hooks/useValidateUniqueness';
import axios, { CancelTokenSource } from 'axios';
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus';
import { nextTick } from 'vue';
import SqlAmisEdit from './edit/SqlAmisEdit.vue';
import OptDlg from './optDlg/OptDlg.vue';
import { SupervisorPublished, supervisorPublishedMap } from './types';
import * as agentGroupApi from '/@/api/ai/agentGroup';
import * as supervisorAdminApi from '/@/api/supervisorAdmin';
import { checkSupervisorValidate, updatePublishStatus } from '/@/api/supervisorAdmin';
import * as supervisorGroupApi from '/@/api/supervisorAdmin/supervisorGroup';
import Chat from '/@/components/chat/Chat.vue';
import AHMContainer from '/@/components/layout/AHMContainer.vue';
import ColFilter from '/@/components/table/colFilter/ColFilter.vue';
import { TableCol } from '/@/components/table/colFilter/types';
import LeftTreeByMgr from '/@/components/tree/leftTreeByMgr.vue';
import { useUpdateData } from '/@/hooks/useUpdateData';
import emitter from '/@/utils/mitt';
import { deepClone } from '/@/utils/other';
import { gotoRoute } from '/@/utils/route';
import { useCompRef } from '/@/utils/types';
import { convertListToTree } from '/@/utils/util';
import { OptClassificationMap, classificationEnum } from '/@/views/types/metrics';
const columnList = ref<TableCol[]>([
   { prop: 'title', label: '标题', width: 300, fixed: 'left' },
   { prop: 'published', label: '发布状态', width: 85 },
   { prop: 'prompt', label: '提示词', width: 300 },
   { prop: 'question', label: '问题', width: 300 },
   { prop: 'creator', label: '创建人', width: 100 },
   { prop: 'create_time', label: '创建时间', width: 105 },
   { prop: 'update_time', label: '更新时间', width: 105 },
   { prop: 'note', label: '备注' },
   { prop: 'operate', label: '操作', width: 200, fixed: 'right' },
]);
//#region ====================== 左侧树数据,tree init ======================
const leftTreeRef = useCompRef(LeftTreeByMgr);
const treeLoading = ref(false);
const listData = ref([]);
const currentListID = computed(() => currentNode.value?.group_id);
const currentNode = ref(null);
const listTreeData = computed(() => {
   const byParentData = convertListToTree(listData.value, {
      ID: 'group_id',
      ParentID: 'p_group_id',
      Children: 'children',
   });
   const result = [];
   byParentData.forEach((item) => {
      if (
         item.group_type != OptClassificationMap[classificationEnum.Office] &&
         item.group_type != OptClassificationMap[classificationEnum.Knowledge]
      ) {
         result.push(item);
      }
   });
   return result;
});
const updateRelatedType = (extendType) => {
   emitter.emit('basic.sys.type.update', {
      ExtendType: extendType,
   });
};
const handleClickNode = (data) => {
   nextTick(() => {
      leftTreeRef.value?.treeRef.setCurrentKey(data.id);
   });
   currentNode.value = data;
   getTableData();
};
const getListTreeData = async () => {
   const res = await agentGroupApi.getSceneGroupTreeByPost();
   listData.value = res.groups || [];
   const firstListTreeNode = listTreeData.value[0];
   if (firstListTreeNode) {
      handleClickNode(firstListTreeNode);
   } else {
      tableData.value = [];
      currentNode.value = null;
   }
};
//#endregion
//#region ====================== 删除左侧树系统模块数据 ======================
const deleteCurrentModule = (row: any) => {
   ElMessageBox.confirm(`确定删除页面分组:【${row.title}】?`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
   }).then(async () => {
      const res = await supervisorGroupApi.deleteSupervisorGroup({
         group_id: row.id,
      });
      ElMessage.success('删除成功!');
      const foundIndex = listData.value.findIndex((item) => row.id === item.id);
      listData.value.splice(foundIndex, 1);
      if (listData.value.length > 0) {
         handleClickNode(listData.value[foundIndex]);
      }
   });
};
//#endregion
//#region ====================== 增加、删除系统模块操作, dialog init======================
const isEditModuleDialog = ref(false);
const moduleDialogTitle = computed(() => {
   return isEditModuleDialog.value ? '修改页面分组' : '添加页面分组';
});
const moduleDialogHeaderIcon = computed(() => {
   return isEditModuleDialog.value ? 'ele-Edit' : 'ele-Plus';
});
const moduleDialogFormValue = ref({
   Name: '',
   Code: '',
   Description: '',
}) as any;
const moduleDialogIsShow = ref(false);
const moduleDialogFormRef = ref<FormInstance>(null);
const moduleDialogFormRules = ref<FormRules>({
   title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
});
const openOperateModuleDialog = (data?) => {
   if (data) {
      isEditModuleDialog.value = true;
      const { id, title } = data;
      moduleDialogFormValue.value = deepClone({ group_id: id, title });
   } else {
      isEditModuleDialog.value = false;
      moduleDialogFormValue.value = { title: '', parent_id: '' };
   }
   moduleDialogIsShow.value = true;
};
const closeModuleDialog = () => {
   moduleDialogIsShow.value = false;
   moduleDialogFormRef.value.clearValidate();
};
const parentSelectOptions = computed(() => {
   const cloneTreeData = deepClone(listTreeData.value);
   travelTree(cloneTreeData, (value, index, array, parent) => {
      if ((value as any).id === moduleDialogFormValue.value.id) {
         if (parent === array) {
            parent?.splice(index, 1);
         } else {
            parent?.Children?.splice(index, 1);
         }
      }
   });
   return cloneTreeData;
});
const submitModuleFormValue = async () => {
   const valid = await moduleDialogFormRef.value.validate().catch(() => {});
   if (!valid) return;
   if (isEditModuleDialog.value) {
      const res = await supervisorGroupApi.updateSupervisorGroup(moduleDialogFormValue.value);
      const foundIndex = listData.value.findIndex((item) => item.id === moduleDialogFormValue.value.id);
      if (foundIndex > -1) {
         listData.value[foundIndex] = {
            ...listData.value[foundIndex],
            title: moduleDialogFormValue.value.title,
         };
      }
      getListTreeData();
      moduleDialogIsShow.value = false;
      ElMessage.success('修改页面分组成功');
   } else {
      const res = await supervisorGroupApi.addSupervisorGroup(moduleDialogFormValue.value);
      const newNode = {
         ...moduleDialogFormValue.value,
         id: res.group_id,
         parent: moduleDialogFormValue.value.parent_id,
      };
      Reflect.deleteProperty(newNode, 'parent_id');
      listData.value.push(newNode);
      handleClickNode(newNode);
      moduleDialogIsShow.value = false;
      ElMessage.success('添加页面分组成功');
   }
};
//#endregion
//#region ====================== 表格数据,table init ======================
const tableLoading = ref(false);
const tableData = ref([]);
const isDragStatus = ref(false);
const allTableData = ref(null);
const getTableData = async () => {
   if (!allTableData.value) {
      const res = await supervisorAdminApi.getSupervisorList();
      allTableData.value = (res.values || []).map((item) => {
         item.create_time = item.create_time?.slice(0, 10);
         item.update_time = item.update_time?.slice(0, 10);
         return item;
      });
   }
   tableData.value = allTableData.value.filter((item) => item.group_id === currentListID.value);
};
//#endregion
//#region ====================== 表格查询、排序,search form init ======================
const queryParams = ref({
   title: '',
});
const { resetQuery, handleQueryTable, displayTableData } = useQueryTable(tableData, queryParams, () => {
   displayTableData.value = tableData.value;
});
//#endregion
//#region ====================== 查询快捷键 ======================
const queryFormRef = ref(null);
const pressEnterSearch = (ev: KeyboardEvent) => {
   if (ev.key === 'Enter') {
      handleQueryTable();
   }
};
usePageDisplay(
   () => {
      queryFormRef.value?.$el?.addEventListener('keypress', pressEnterSearch);
   },
   () => {
      queryFormRef.value?.$el?.removeEventListener('keypress', pressEnterSearch);
   }
);
//#endregion
//#region ====================== sql ======================
const supervisorMgrShow = ref(true);
const sqlEditMapSupervisor = ref(null);
const editSqlClick = (item) => {
   sqlEditMapSupervisor.value = item;
   supervisorMgrShow.value = false;
};
const backLastPage = () => {
   supervisorMgrShow.value = true;
   nextTick(() => {
      leftTreeRef.value?.treeRef.setCurrentKey(currentListID.value);
   });
};
//#endregion
//#region ====================== 添加修改操作 ======================
const optDlgIsShow = ref(false);
const optDlgMapRow = ref(null);
const openOptDlg = (row?: any) => {
   optDlgMapRow.value = row;
   optDlgIsShow.value = true;
};
const updateOpt = (formValue) => {
   const foundIndex = tableData.value.findIndex((item) => item.id === formValue.id);
   if (foundIndex > -1) {
      tableData.value[foundIndex] = {
         ...tableData.value[foundIndex],
         ...formValue,
      };
   }
};
const insertOpt = (newData) => {
   tableData.value.unshift({ ...newData, published: SupervisorPublished.N });
};
//#endregion
const updatePublishedById = (id: string, published: SupervisorPublished) => {
   const row = tableData.value.find((item) => item.id === id);
   if (row) {
      row.published = published;
   }
};
//#region ====================== 改变发布状态 ======================
const publishStatusChange = async (published: SupervisorPublished, id, index) => {
   const res = await updatePublishStatus(
      {
         id: id,
         publish: published,
      },
      {
         loading: false,
      }
   );
   const origin = published === SupervisorPublished.Y ? SupervisorPublished.N : SupervisorPublished.Y;
   const final = res.publish ?? origin;
   if (final === origin) {
      ElMessage.warning('操作失败' + (res.fail_msg ? `:${res.fail_msg}` : ''));
      return;
   }
   tableData.value[index].published = final;
   published === SupervisorPublished.Y ? ElMessage.success('发布成功') : ElMessage.info('已取消发布');
};
//#endregion
//#region ====================== 跳转低代码编辑页面 ======================
const gotoAmisPage = (row) => {
   window.currentPage = row;
   gotoRoute({
      name: 'AmisEditor',
   });
};
//#endregion
//#region ====================== Chat 测试 ======================
const chatRef = useCompRef(Chat);
const chatTestMapRow = ref(null);
const chatTestIsShow = ref(false);
const openChatTest = (row) => {
   chatTestMapRow.value = row;
   chatTestIsShow.value = true;
   nextTick(() => {
      chatRef.value.clear();
      setTimeout(() => {
         chatRef.value.autoSend(row.question);
      }, 30);
   });
};
const closeChatTest = () => {
   chatTestMapRow.value = null;
   chatTestIsShow.value = false;
};
const draggableChatRef = ref<HTMLElement | null>(null);
const chatDragHandlerRef = ref<HTMLDivElement>(null);
// `style` will be a helper computed for `left: ?px; top: ?px;`
const { x, y, style } = useDraggable(draggableChatRef, {
   handle: chatDragHandlerRef,
   initialValue: {
      x: document.body.clientWidth / 2 - 350,
      y: document.body.clientHeight / 2 - 400,
   },
});
const questionAi = async (text, sourceObj: { source: CancelTokenSource }) => {
   const currentSource = axios.CancelToken.source();
   sourceObj.source = currentSource;
   const res = await checkSupervisorValidate(
      {
         id: chatTestMapRow.value.id,
         question: text,
      },
      {
         loading: false,
         cancelToken: currentSource.token,
      }
   );
   return res;
};
//#endregion
//#region ====================== 更新发布状态 ======================
useUpdateData({
   event: 'supervisor.publish',
   updateFun({ id, published }) {
      updatePublishedById(id, published);
   },
});
//#endregion
onMounted(() => {
   getListTreeData();
});
</script>
<style scoped lang="scss"></style>