Merge branch 'refs/heads/abp' into digital-collectibles

This commit is contained in:
橙子
2025-02-03 10:30:26 +08:00
20 changed files with 593 additions and 481 deletions

View File

@@ -75,6 +75,7 @@ public class YiTokenAuthorizationFilter : IDashboardAsyncAuthorizationFilter, IT
function sendToken() { function sendToken() {
// 获取输入的 token // 获取输入的 token
var token = document.getElementById("tokenInput").value; var token = document.getElementById("tokenInput").value;
token = token.replace('Bearer ','');
// 构建请求 URL // 构建请求 URL
var url = "/hangfire"; var url = "/hangfire";
// 发送 GET 请求 // 发送 GET 请求
@@ -107,7 +108,7 @@ public class YiTokenAuthorizationFilter : IDashboardAsyncAuthorizationFilter, IT
<body style="text-align: center;"> <body style="text-align: center;">
<h1>Yi-hangfire</h1> <h1>Yi-hangfire</h1>
<h1>Token</h1> <h1>Token</h1>
<input type="text" id="tokenInput" placeholder="请输入 token" /> <textarea id="tokenInput" placeholder="请输入 token" style="width: 80%;height: 120px;margin: 0 10%;"></textarea>
<button onclick="sendToken()"></button> <button onclick="sendToken()"></button>
</body> </body>
</html> </html>

View File

@@ -23,14 +23,13 @@ namespace Yi.Framework.ChatHub.Application.Services
/// <param name="chatContext"></param> /// <param name="chatContext"></param>
/// <returns></returns> /// <returns></returns>
[Authorize] [Authorize]
[HttpPost] [HttpPost("ai-chat/chat/{model}")]
public async Task ChatAsync([FromRoute]string model, [FromBody] List<AiChatContextDto> chatContext)
public async Task ChatAsync([FromBody] List<AiChatContextDto> chatContext)
{ {
const int maxChar = 10; const int maxChar = 10;
var contextId = Guid.NewGuid(); var contextId = Guid.NewGuid();
Queue<string> stringQueue = new Queue<string>(); Queue<string> stringQueue = new Queue<string>();
await foreach (var aiResult in _aiManager.ChatAsStreamAsync(chatContext)) await foreach (var aiResult in _aiManager.ChatAsStreamAsync(model,chatContext))
{ {
stringQueue.Enqueue(aiResult); stringQueue.Enqueue(aiResult);
@@ -42,7 +41,7 @@ namespace Yi.Framework.ChatHub.Application.Services
var str = stringQueue.Dequeue(); var str = stringQueue.Dequeue();
currentStr.Append(str); currentStr.Append(str);
} }
await _userMessageManager.SendMessageAsync(MessageContext.CreateAi(currentStr.ToString(), CurrentUser.Id!.Value, contextId)); await _userMessageManager.SendMessageAsync(MessageContext.CreateAi(currentStr.ToString(), CurrentUser.Id!.Value, contextId),model);
} }
} }
@@ -52,9 +51,7 @@ namespace Yi.Framework.ChatHub.Application.Services
var str = stringQueue.Dequeue(); var str = stringQueue.Dequeue();
currentEndStr.Append(str); currentEndStr.Append(str);
} }
await _userMessageManager.SendMessageAsync(MessageContext.CreateAi(currentEndStr.ToString(), CurrentUser.Id!.Value, contextId)); await _userMessageManager.SendMessageAsync(MessageContext.CreateAi(currentEndStr.ToString(), CurrentUser.Id!.Value, contextId),model);
//await _userMessageManager.SendMessageAsync(MessageContext.CreateAi(null, CurrentUser.Id!.Value, contextId));
} }
} }
} }

View File

@@ -24,19 +24,8 @@ namespace Yi.Framework.ChatHub.Domain.Managers
} }
private OpenAIService OpenAIService { get; } private OpenAIService OpenAIService { get; }
public async IAsyncEnumerable<string> ChatAsStreamAsync(List<AiChatContextDto> aiChatContextDtos) public async IAsyncEnumerable<string> ChatAsStreamAsync(string model, List<AiChatContextDto> aiChatContextDtos)
{ {
//var temp = "站长正在接入ChatGpt,敬请期待~";
//for (var i = 0; i < temp.Length; i++)
//{
// await Task.Delay(200);
// yield return temp[i].ToString();
//}
if (aiChatContextDtos.Count == 0) if (aiChatContextDtos.Count == 0)
{ {
yield return null; yield return null;
@@ -56,7 +45,7 @@ namespace Yi.Framework.ChatHub.Domain.Managers
var completionResult = OpenAIService.ChatCompletion.CreateCompletionAsStream(new ChatCompletionCreateRequest var completionResult = OpenAIService.ChatCompletion.CreateCompletionAsStream(new ChatCompletionCreateRequest
{ {
Messages = messages, Messages = messages,
Model = Models.Gpt_4o_mini Model =model
}); });
HttpStatusCode? error = null; HttpStatusCode? error = null;

View File

@@ -31,7 +31,14 @@ namespace Yi.Framework.ChatHub.Domain.Managers
private IRedisClient RedisClient => LazyServiceProvider.LazyGetRequiredService<IRedisClient>(); private IRedisClient RedisClient => LazyServiceProvider.LazyGetRequiredService<IRedisClient>();
private string CacheKeyPrefix => LazyServiceProvider.LazyGetRequiredService<IOptions<AbpDistributedCacheOptions>>().Value.KeyPrefix; private string CacheKeyPrefix => LazyServiceProvider.LazyGetRequiredService<IOptions<AbpDistributedCacheOptions>>().Value.KeyPrefix;
public async Task SendMessageAsync(MessageContext context)
/// <summary>
/// 发送消息
/// </summary>
/// <param name="context">消息内容</param>
/// <param name="relStr">关联字符</param>
/// <exception cref="NotImplementedException"></exception>
public async Task SendMessageAsync(MessageContext context,string relStr=null)
{ {
switch (context.MessageType) switch (context.MessageType)
{ {
@@ -39,20 +46,20 @@ namespace Yi.Framework.ChatHub.Domain.Managers
var userModel = await GetUserAsync(context.ReceiveId.Value); var userModel = await GetUserAsync(context.ReceiveId.Value);
if (userModel is not null) if (userModel is not null)
{ {
await _hubContext.Clients.Client(userModel.ClientId).SendAsync(ChatConst.ClientActionReceiveMsg, context.MessageType, context); await _hubContext.Clients.Client(userModel.ClientId).SendAsync(ChatConst.ClientActionReceiveMsg, context.MessageType,relStr, context);
} }
break; break;
case MessageTypeEnum.Group: case MessageTypeEnum.Group:
throw new NotImplementedException(); throw new NotImplementedException();
break; break;
case MessageTypeEnum.All: case MessageTypeEnum.All:
await _hubContext.Clients.All.SendAsync(ChatConst.ClientActionReceiveMsg, context.MessageType, context); await _hubContext.Clients.All.SendAsync(ChatConst.ClientActionReceiveMsg, context.MessageType,relStr, context);
break; break;
case MessageTypeEnum.Ai: case MessageTypeEnum.Ai:
var userModel2 = await GetUserAsync(context.ReceiveId.Value); var userModel2 = await GetUserAsync(context.ReceiveId.Value);
if (userModel2 is not null) if (userModel2 is not null)
{ {
await _hubContext.Clients.Client(userModel2.ClientId).SendAsync(ChatConst.ClientActionReceiveMsg, context.MessageType, context); await _hubContext.Clients.Client(userModel2.ClientId).SendAsync(ChatConst.ClientActionReceiveMsg, context.MessageType,relStr, context);
} }
break; break;

View File

@@ -2,7 +2,7 @@
namespace Yi.Framework.Rbac.Application.Contracts.Dtos.Role namespace Yi.Framework.Rbac.Application.Contracts.Dtos.Role
{ {
public class UpdateDataScpoceInput public class UpdateDataScopeInput
{ {
public Guid RoleId { get; set; } public Guid RoleId { get; set; }

View File

@@ -39,7 +39,7 @@ namespace Yi.Framework.Rbac.Application.Services.System
private ISqlSugarRepository<UserRoleEntity> _userRoleRepository; private ISqlSugarRepository<UserRoleEntity> _userRoleRepository;
public async Task UpdateDataScpoceAsync(UpdateDataScpoceInput input) public async Task UpdateDataScopeAsync(UpdateDataScopeInput input)
{ {
//只有自定义的需要特殊处理 //只有自定义的需要特殊处理
if (input.DataScope == DataScopeEnum.CUSTOM) if (input.DataScope == DataScopeEnum.CUSTOM)

View File

@@ -20,7 +20,10 @@
</ItemGroup> </ItemGroup>
<ItemGroup>
<PackageReference Include="DistributedLock.Redis" Version="1.0.3" />
<PackageReference Include="Volo.Abp.DistributedLocking" Version="$(AbpVersion)" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\..\..\framework\Yi.Framework.Caching.FreeRedis\Yi.Framework.Caching.FreeRedis.csproj" /> <ProjectReference Include="..\..\..\framework\Yi.Framework.Caching.FreeRedis\Yi.Framework.Caching.FreeRedis.csproj" />
<ProjectReference Include="..\..\..\framework\Yi.Framework.SqlSugarCore.Abstractions\Yi.Framework.SqlSugarCore.Abstractions.csproj" /> <ProjectReference Include="..\..\..\framework\Yi.Framework.SqlSugarCore.Abstractions\Yi.Framework.SqlSugarCore.Abstractions.csproj" />

View File

@@ -1,6 +1,10 @@
using Microsoft.Extensions.DependencyInjection; using Medallion.Threading;
using Medallion.Threading.Redis;
using Microsoft.Extensions.DependencyInjection;
using StackExchange.Redis;
using Volo.Abp.AspNetCore.SignalR; using Volo.Abp.AspNetCore.SignalR;
using Volo.Abp.Caching; using Volo.Abp.Caching;
using Volo.Abp.DistributedLocking;
using Volo.Abp.Domain; using Volo.Abp.Domain;
using Volo.Abp.Imaging; using Volo.Abp.Imaging;
using Volo.Abp.Modularity; using Volo.Abp.Modularity;
@@ -20,7 +24,8 @@ namespace Yi.Framework.Rbac.Domain
typeof(AbpAspNetCoreSignalRModule), typeof(AbpAspNetCoreSignalRModule),
typeof(AbpDddDomainModule), typeof(AbpDddDomainModule),
typeof(AbpCachingModule), typeof(AbpCachingModule),
typeof(AbpImagingImageSharpModule) typeof(AbpImagingImageSharpModule),
typeof(AbpDistributedLockingModule)
)] )]
public class YiFrameworkRbacDomainModule : AbpModule public class YiFrameworkRbacDomainModule : AbpModule
{ {
@@ -36,6 +41,15 @@ namespace Yi.Framework.Rbac.Domain
//配置阿里云短信 //配置阿里云短信
Configure<AliyunOptions>(configuration.GetSection(nameof(AliyunOptions))); Configure<AliyunOptions>(configuration.GetSection(nameof(AliyunOptions)));
//分布式锁
context.Services.AddSingleton<IDistributedLockProvider>(sp =>
{
var connection = ConnectionMultiplexer
.Connect(configuration["Redis:Configuration"]);
return new
RedisDistributedSynchronizationProvider(connection.GetDatabase());
});
} }
} }
} }

View File

@@ -1,8 +1,10 @@
using System.Xml.Linq; using System.Xml.Linq;
using Mapster; using Mapster;
using Medallion.Threading;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting; using Microsoft.AspNetCore.RateLimiting;
using Volo.Abp.Application.Services; using Volo.Abp.Application.Services;
using Volo.Abp.DistributedLocking;
using Volo.Abp.Settings; using Volo.Abp.Settings;
using Volo.Abp.Uow; using Volo.Abp.Uow;
using Yi.Framework.Bbs.Application.Contracts.Dtos.Banner; using Yi.Framework.Bbs.Application.Contracts.Dtos.Banner;
@@ -49,7 +51,7 @@ namespace Yi.Abp.Application.Services
throw new UserFriendlyException("业务异常"); throw new UserFriendlyException("业务异常");
throw new Exception("系统异常"); throw new Exception("系统异常");
} }
/// <summary> /// <summary>
/// SqlSugar /// SqlSugar
/// </summary> /// </summary>
@@ -138,6 +140,7 @@ namespace Yi.Abp.Application.Services
} }
private static int RequestNumber { get; set; } = 0; private static int RequestNumber { get; set; } = 0;
/// <summary> /// <summary>
/// 速率限制 /// 速率限制
/// </summary> /// </summary>
@@ -154,6 +157,7 @@ namespace Yi.Abp.Application.Services
public ISettingProvider _settingProvider { get; set; } public ISettingProvider _settingProvider { get; set; }
public ISettingManager _settingManager { get; set; } public ISettingManager _settingManager { get; set; }
/// <summary> /// <summary>
/// 系统配置模块 /// 系统配置模块
/// </summary> /// </summary>
@@ -175,5 +179,41 @@ namespace Yi.Abp.Application.Services
return result ?? string.Empty; return result ?? string.Empty;
} }
/// <summary>
/// 分布式送abp版本abp套了一层娃。但是纯粹鸡肋不建议使用这个
/// </summary>
public IAbpDistributedLock AbpDistributedLock { get; set; }
/// <summary>
/// 分布式锁推荐使用版本yyds分布式锁永远的神
/// </summary>
public IDistributedLockProvider DistributedLock { get; set; }
/// <summary>
/// 分布式锁
/// </summary>
/// <remarks>强烈吐槽一下abp正如他们所说abp的分布式锁单纯为了自己用一切还是以DistributedLock为主</remarks>>
/// <returns></returns>
public async Task<string> GetDistributedLockAsync()
{
var number = 0;
await Parallel.ForAsync(0, 100, async (i, cancellationToken) =>
{
await using (await DistributedLock.AcquireLockAsync("MyLockName"))
{
//执行1秒
number += 1;
}
});
var number2 = 0;
await Parallel.ForAsync(0, 100, async (i, cancellationToken) =>
{
//执行1秒
number2 += 1;
});
return $"加锁结果:{number},不加锁结果:{number2}";
}
} }
} }

View File

@@ -2,6 +2,7 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Linq; using System.Linq;
using System.Runtime.InteropServices;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.Extensions.CommandLineUtils; using Microsoft.Extensions.CommandLineUtils;
@@ -39,12 +40,11 @@ namespace Yi.Abp.Tool.Commands
} }
CheckFirstSlnPath(slnPath); CheckFirstSlnPath(slnPath);
var dotnetSlnCommandPart1 = $"dotnet sln \"{slnPath}\" add \"{modulePath}\\{moduleName}."; var dotnetSlnCommandPart = new List<string>() { "Application", "Application.Contracts", "Domain", "Domain.Shared", "SqlSugarCore" };
var dotnetSlnCommandPart2 = new List<string>() { "Application", "Application.Contracts", "Domain", "Domain.Shared", "SqlSugarCore" }; var paths = dotnetSlnCommandPart.Select(x => Path.Combine(modulePath, $"{moduleName}.{x}")).ToArray();
var paths = dotnetSlnCommandPart2.Select(x => $@"{modulePath}\{moduleName}." + x).ToArray();
CheckPathExist(paths); CheckPathExist(paths);
var cmdCommands = dotnetSlnCommandPart2.Select(x => dotnetSlnCommandPart1 + x+"\"").ToArray(); var cmdCommands = dotnetSlnCommandPart.Select(x => $"dotnet sln \"{slnPath}\" add \"{Path.Combine(modulePath, $"{moduleName}.{x}")}\"").ToArray();
StartCmd(cmdCommands); StartCmd(cmdCommands);
Console.WriteLine("恭喜~模块添加成功!"); Console.WriteLine("恭喜~模块添加成功!");
@@ -81,15 +81,24 @@ namespace Yi.Abp.Tool.Commands
{ {
ProcessStartInfo psi = new ProcessStartInfo ProcessStartInfo psi = new ProcessStartInfo
{ {
FileName = "cmd.exe",
Arguments = $"/c chcp 65001&{string.Join("&", cmdCommands)}",
RedirectStandardInput = true, RedirectStandardInput = true,
RedirectStandardOutput = true, RedirectStandardOutput = true,
RedirectStandardError = true, RedirectStandardError = true,
CreateNoWindow = true, CreateNoWindow = true,
UseShellExecute = false UseShellExecute = false
}; };
// 判断操作系统
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
psi.FileName = "cmd.exe";
psi.Arguments = $"/c chcp 65001&{string.Join("&", cmdCommands)}";
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) || RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
psi.FileName = "/bin/bash";
psi.Arguments = $"-c \"{string.Join("; ", cmdCommands)}\"";
}
Process proc = new Process Process proc = new Process
{ {
StartInfo = psi StartInfo = psi

View File

@@ -2,6 +2,7 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Linq; using System.Linq;
using System.Runtime.InteropServices;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.Extensions.CommandLineUtils; using Microsoft.Extensions.CommandLineUtils;
@@ -35,15 +36,24 @@ namespace Yi.Abp.Tool.Commands
{ {
ProcessStartInfo psi = new ProcessStartInfo ProcessStartInfo psi = new ProcessStartInfo
{ {
FileName = "cmd.exe",
Arguments = $"/c chcp 65001&{string.Join("&", cmdCommands)}",
RedirectStandardInput = true, RedirectStandardInput = true,
RedirectStandardOutput = true, RedirectStandardOutput = true,
RedirectStandardError = true, RedirectStandardError = true,
CreateNoWindow = true, CreateNoWindow = true,
UseShellExecute = false UseShellExecute = false
}; };
// 判断操作系统
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
psi.FileName = "cmd.exe";
psi.Arguments = $"/c chcp 65001&{string.Join("&", cmdCommands)}";
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) || RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
psi.FileName = "/bin/bash";
psi.Arguments = $"-c \"{string.Join("; ", cmdCommands)}\"";
}
Process proc = new Process Process proc = new Process
{ {
StartInfo = psi StartInfo = psi

View File

@@ -22,9 +22,9 @@ export function sendGroupMessage(data) {
}); });
} }
export function sendAiChat(data) { export function sendAiChat(data,model) {
return request({ return request({
url: "/ai-chat/chat", url: `/ai-chat/chat/${model}`,
method: "post", method: "post",
data data
}); });

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

View File

Before

Width:  |  Height:  |  Size: 10 KiB

After

Width:  |  Height:  |  Size: 10 KiB

View File

@@ -12,18 +12,16 @@ const receiveMsg = (connection) => {
chatStore.delUser(userId); chatStore.delUser(userId);
}); });
//接受其他用户消息 //接受其他用户消息
connection.on("receiveMsg", (type, content) => { connection.on("receiveMsg", (type,relStr, content) => {
const letChatStore = useChatStore(); const letChatStore = useChatStore();
//如果是ai消息还要进行流式显示 //如果是ai消息还要进行流式显示
// alert(type) if (type === 3) {//ai消息还需要支持动态类型
if (type == 3) { content.messageType ='ai@'+ relStr;
letChatStore.addOrUpdateMsg(content); letChatStore.addOrUpdateMsg(content);
} }
else { else {
letChatStore.addMsg(content); letChatStore.addMsg(content);
} }
}); });
//用户状态-正在输入中,无 //用户状态-正在输入中,无
connection.on("userStatus", (type) => { connection.on("userStatus", (type) => {

View File

@@ -5,16 +5,20 @@ const chatStore = defineStore("chat", {
msgList: [] msgList: []
}), }),
getters: { getters: {
allMsgContext: (state) => state.msgList.filter(x => x.messageType == "All"), allMsgContext: (state) => state.msgList.filter(x => x.messageType === "All"),
personalMsgContext: (state) => state.msgList.filter(x => x.messageType == "Personal"), personalMsgContext: (state) => state.msgList.filter(x => x.messageType === "Personal"),
aiMsgContext: (state) => state.msgList.filter(x => x.messageType == "Ai") // aiMsgContext: (state) => state.msgList.filter(x => x.messageType === "Ai"),
//获取msg通过类型
getMsgContextFunc: (state) => (messageType) => {
return state.msgList.filter(item => item.messageType === messageType);
},
}, },
actions: actions:
{ {
addOrUpdateMsg(msg) { addOrUpdateMsg(msg) {
var currentMsg = this.msgList.filter(x => x.id == msg.id)[0]; var currentMsg = this.msgList.filter(x => x.id === msg.id)[0];
//当前没有包含,如果有相同的上下文id只需要改变content即可 //当前没有包含,如果有相同的上下文id只需要改变content即可
if (currentMsg == undefined) { if (currentMsg === undefined) {
this.addMsg(msg); this.addMsg(msg);
} }
else { else {
@@ -22,9 +26,9 @@ const chatStore = defineStore("chat", {
} }
}, },
clearAiMsg() clearTypeMsg(messageType)
{ {
this.msgList=this.msgList.filter(x => x.messageType != "Ai") this.msgList=this.msgList.filter(x => x.messageType !==messageType)
}, },
setMsgList(value) { setMsgList(value) {
this.msgList = value; this.msgList = value;
@@ -39,7 +43,7 @@ const chatStore = defineStore("chat", {
this.userList.push(user); this.userList.push(user);
}, },
delUser(userId) { delUser(userId) {
this.userList = this.userList.filter(obj => obj.userId != userId); this.userList = this.userList.filter(obj => obj.userId !== userId);
} }
}, },
}); });

View File

@@ -1,26 +1,32 @@
<script setup> <script setup>
import { nextTick,onMounted, ref, computed, onUnmounted } from 'vue'; import {nextTick, onMounted, ref, computed, onUnmounted} from 'vue';
import { storeToRefs } from 'pinia' import {storeToRefs} from 'pinia'
import useAuths from '@/hooks/useAuths.js'; import useAuths from '@/hooks/useAuths.js';
import { getList as getChatUserList } from '@/apis/chatUserApi' import {getList as getChatUserList} from '@/apis/chatUserApi'
import { sendPersonalMessage, sendGroupMessage, getAccountList as getChatAccountMessageList, sendAiChat } from '@/apis/chatMessageApi' import {
sendPersonalMessage,
sendGroupMessage,
getAccountList as getChatAccountMessageList,
sendAiChat
} from '@/apis/chatMessageApi'
import useChatStore from "@/stores/chat"; import useChatStore from "@/stores/chat";
import useUserStore from "@/stores/user"; import useUserStore from "@/stores/user";
const { isLogin } = useAuths();
import { useRouter } from 'vue-router' const {isLogin} = useAuths();
import { getUrl } from '@/utils/icon' import {useRouter} from 'vue-router'
import {getUrl} from '@/utils/icon'
//markdown ai显示 //markdown ai显示
import { marked } from 'marked'; import {marked} from 'marked';
import '@/assets/atom-one-dark.css'; import '@/assets/atom-one-dark.css';
import '@/assets/github-markdown.css'; import '@/assets/github-markdown.css';
import hljs from "highlight.js"; import hljs from "highlight.js";
const isShowTipNumber=ref(10); const isShowTipNumber = ref(10);
const router = useRouter(); const router = useRouter();
//聊天存储 //聊天存储
const chatStore = useChatStore(); const chatStore = useChatStore();
const { userList } = storeToRefs(chatStore); const {userList} = storeToRefs(chatStore);
//用户信息 //用户信息
const userStore = useUserStore(); const userStore = useUserStore();
@@ -31,153 +37,24 @@ const currentSelectUser = ref('all');
//当前输入框的值 //当前输入框的值
const currentInputValue = ref(""); const currentInputValue = ref("");
//临时存储的输入框根据用户id及组name、all组为keydata为value //临时存储的输入框根据用户id及组name、all组为keydata为value
const inputListDataStore = ref([{ key: "all", value: "" }, { key: "ai", value: "" }]); const inputListDataStore = ref([
{key: "all", name: "官方学习交流群", titleName: "官方学习交流群", logo: "yilogo.png", value: ""},
{key: "ai@deepseek-chat", name: "DeepSeek聊天", titleName: "DeepSeek-聊天模式", logo: "deepSeekAi.png", value: ""},
{
key: "ai@DeepSeek-R1",
name: "DeepSeek思索",
titleName: "DeepSeek-思索模式",
logo: "deepSeekAi.png",
value: ""
},
{key: "ai@gpt-4o-mini", name: "ChatGpt聊天", titleName: "ChatGpt-聊天模式", logo: "openAi.png", value: ""},
]);
//AI聊天临时存储 //AI聊天临时存储
const sendAiChatContext = ref([]); const sendAiChatContext = ref([]);
let timerTip=null;
//倒计时显示tip
const startCountTip = () => {
timerTip = setInterval(() => {
if (isShowTipNumber.value > 0) {
isShowTipNumber.value--;
} else {
clearInterval(timerTip); // 倒计时结束
}
}, 1000);
};
let codeCopyDic=[];
//当前聊天框显示的消息
const currentMsgContext = computed(() => {
if (selectIsAll()) {
return chatStore.allMsgContext;
}
else if (selectIsAi()) {
//如果是ai的值还行经过markdown处理
// console.log(chatStore.aiMsgContext, "chatStore.aiMsgContext");
// return chatStore.aiMsgContext;
let tempHtml = [];
codeCopyDic=[];
chatStore.aiMsgContext.forEach(element => {
tempHtml.push({ content: toMarkDownHtml(element.content), messageType: 'Ai', sendUserId: element.sendUserId, sendUserInfo: element.sendUserInfo });
});
return tempHtml;
}
else {
return chatStore.personalMsgContext.filter(x => {
//两个条件
//接收用户者id为对面id我发给他
//或者发送用户id为对面他发给我
return (x.receiveId == currentSelectUser.value.userId && x.sendUserId == userStore.id) ||
(x.sendUserId == currentSelectUser.value.userId && x.receiveId == userStore.id);
});
}
});
//转换markdown
const toMarkDownHtml = (text) => {
marked.setOptions({
renderer: new marked.Renderer(),
highlight: function (code, language) {
return codeHandler(code, language);
//return hljs.highlightAuto(code).value;
},
pedantic: false,
gfm: true,//允许 Git Hub标准的markdown
tables: true,//支持表格
breaks: true,
sanitize: false,
smartypants: false,
xhtml: false,
smartLists: true,
}
);
//需要注意代码块样式
const soureHtml = marked(text);
nextTick(()=>{
addCopyEvent();
})
return soureHtml;
}
//code部分处理、高亮
const codeHandler = (code, language) => {
const codeIndex = parseInt(Date.now() + "") + Math.floor(Math.random() * 10000000);
//console.log(codeIndex,"codeIndex");
// 格式化第一行是右侧language和 “复制” 按钮;
if (code) {
const navCode = navHandler(code)
try {
// 使用 highlight.js 对代码进行高亮显示
const preCode = hljs.highlightAuto(code).value;
// 将代码包裹在 textarea 中由于防止textarea渲染出现问题这里将 "<" 用 "&lt;" 代替,不影响复制功能
let html = `<pre class='hljs pre'><div class="header"><span class="language">${language}</span><span class="copy" id="${codeIndex}">复制代码</span></div><div class="code-con"><div class="nav">${navCode}</div><code class="code">${preCode}</code></div></pre>`;
codeCopyDic.push({ id: codeIndex, code: code });
// console.log(codeCopyDic.length);
return html;
//<textarea style="position: absolute;top: -9999px;left: -9999px;z-index: -9999;" id="copy${codeIndex}">${code.replace(/<\/textarea>/g, "&lt;/textarea>")}</textarea>
} catch (error) {
console.log(error);
}
}
}
//左侧导航栏处理
const navHandler = (code) => {
//获取行数
var linesCount = getLinesCount(code);
var currentLine = 1;
var liHtml = ``;
while (linesCount + 1 >= currentLine) {
liHtml += `<li class="nav-li">${currentLine}</li>`
currentLine++
}
let html = `<ul class="nav-ul">${liHtml}</ul>`
return html;
}
const BREAK_LINE_REGEXP = /\r\n|\r|\n/g;
const getLinesCount = (text) => {
return (text.trim().match(BREAK_LINE_REGEXP) || []).length;
}
const getChatUrl = (url, position) => {
if (position == "left" && selectIsAi()) {
return "/openAi.png"
}
return getUrl(url);
}
//当前聊天框显示的名称
const currentHeaderName = computed(() => {
if (selectIsAll()) {
return "官方学习交流群";
}
else if
(selectIsAi()) {
return "Ai-ChatGpt4.0(你的私人ai小助手)"
}
else {
return currentSelectUser.value.userName;
}
});
const currentUserItem = computed(() => {
return userList.value.filter(x => x.userId != useUserStore().id)
});
var timer = null; var timer = null;
let codeCopyDic = [];
//初始化 //初始化
onMounted(async () => { onMounted(async () => {
if (!isLogin.value) { if (!isLogin.value) {
@@ -188,12 +65,12 @@ onMounted(async () => {
timer = setTimeout(function () { timer = setTimeout(function () {
onclickClose(); onclickClose();
}, 3000); }, 3000);
} }
//all的聊天消息
chatStore.setMsgList((await getChatAccountMessageList()).data); chatStore.setMsgList((await getChatAccountMessageList()).data);
//在线用户列表
chatStore.setUserList((await getChatUserList()).data); chatStore.setUserList((await getChatUserList()).data);
startCountTip(); startCountTip();
}) })
onUnmounted(() => { onUnmounted(() => {
if (timer != null) { if (timer != null) {
@@ -202,89 +79,114 @@ onUnmounted(() => {
if (timerTip != null) { if (timerTip != null) {
clearInterval(timerTip) clearInterval(timerTip)
} }
}) })
const clickCopyEvent=async function(event) { /*-----计算属性-----*/
const spanId=event.target.id; //当前聊天框内容显示的消息
console.log(codeCopyDic,"codeCopyDic") const currentMsgContext = computed(() => {
console.log(spanId,"spanId") //选择全部人
await navigator.clipboard.writeText(codeCopyDic.filter(x=>x.id==spanId)[0].code); if (selectIsAll()) {
ElMessage({ return chatStore.allMsgContext;
message: "代码块复制成功", }
type: "success", //选择ai
duration: 2000, else if (selectIsAi()) {
}); //如果是ai的值还行经过markdown处理
} let tempHtml = [];
//代码copy事件 codeCopyDic = [];
const addCopyEvent=()=>{ chatStore.getMsgContextFunc(currentSelectUser.value).forEach(element => {
const copySpans = document.querySelectorAll('.copy'); tempHtml.push({
// 为每个 copy span 元素添加点击事件 content: toMarkDownHtml(element.content),
copySpans.forEach(span => { messageType: 'Ai',
//先移除,再新增 sendUserId: element.sendUserId,
span.removeEventListener('click',clickCopyEvent ); sendUserInfo: element.sendUserInfo
span.addEventListener('click', clickCopyEvent); });
}); });
}
return tempHtml;
}
//选择个人
else {
return chatStore.personalMsgContext.filter(x => {
//两个条件
//接收用户者id为对面id我发给他
//或者发送用户id为对面他发给我
return (x.receiveId === currentSelectUser.value.userId && x.sendUserId === userStore.id) ||
(x.sendUserId === currentSelectUser.value.userId && x.receiveId === userStore.id);
});
}
});
//获取聊天内容的头像
const getChatUrl = (url, position) => {
if (position === "left" && (selectIsAi()||selectIsAll())) {
return imageSrc(inputListDataStore.value.find(x=>x.key===currentSelectUser.value).logo)
}
return getUrl(url);
}
//当前聊天框显示的名称
const currentHeaderName = computed(() => {
if (selectIsAll()||selectIsAi()) {
return inputListDataStore.value.find(x=>x.key===currentSelectUser.value).name;
} else {
return currentSelectUser.value.userName;
}
});
//当前在线的用户项
const currentUserItem = computed(() => {
return userList.value.filter(x => x.userId !== useUserStore().id)
});
/*-----方法-----*/ /*-----方法-----*/
//当前选择的是否为全部 //当前选择的是否为全部
const selectIsAll = () => { const selectIsAll = () => {
return currentSelectUser.value == 'all'; return currentSelectUser.value === 'all';
}; };
//当前选择的是否为Ai //当前选择的是否为Ai
const selectIsAi = () => { const selectIsAi = () => {
return currentSelectUser.value == 'ai'; //以ai@开头
return /^ai@/.test(currentSelectUser.value);
}; };
//是否为公共的类型
const isPublicType=(itemType)=>{
return itemType==='all'||/^ai@/.test(itemType);
}
//输入框的值被更改同时保存到store中
//输入框的值被更改
const changeInputValue = (inputValue) => { const changeInputValue = (inputValue) => {
currentInputValue.value = inputValue; currentInputValue.value = inputValue;
let index = -1; let index = -1;
let findKey = currentSelectUser.value?.userId let findKey = currentSelectUser.value?.userId
if (selectIsAll()) { if (selectIsAll()) {
findKey = 'all'; findKey = 'all';
} else if (selectIsAi()) {
findKey = currentSelectUser.value;
} }
else if (selectIsAi()) { index = inputListDataStore.value.findIndex(obj => obj.key === findKey);
findKey = 'ai';
}
index = inputListDataStore.value.findIndex(obj => obj.key == findKey);
inputListDataStore.value[index].value = currentInputValue.value; inputListDataStore.value[index].value = currentInputValue.value;
} }
//绑定的input改变事件
const updateInputValue = (event) => { //获取输入框的值(切换左侧菜单的时候,给输入框补充之前没发送的值)
changeInputValue(event.target.value);
}
//获取输入框的值
const getCurrentInputValue = () => { const getCurrentInputValue = () => {
if (selectIsAll()) { if (selectIsAll()) {
return inputListDataStore.value.filter(x => x.key == "all")[0].value; return inputListDataStore.value.filter(x => x.key === "all")[0].value;
} } else if (selectIsAi()) {
else if (selectIsAi()) { return inputListDataStore.value.filter(x => x.key === currentSelectUser.value)[0].value;
return inputListDataStore.value.filter(x => x.key == "ai")[0].value; } else {
}
else {
//如果不存在初始存储值 //如果不存在初始存储值
if (!inputListDataStore.value.some(x => x.key == currentSelectUser.value.userId)) { if (!inputListDataStore.value.some(x => x.key === currentSelectUser.value.userId)) {
inputListDataStore.value.push({ key: currentSelectUser.value.userId, value: "" }); inputListDataStore.value.push({key: currentSelectUser.value.userId, value: "",type:'user'});
return ""; return "";
} }
return inputListDataStore.value.filter(x => x.key == currentSelectUser.value.userId)[0].value; return inputListDataStore.value.filter(x => x.key === currentSelectUser.value.userId)[0].value;
} }
}; };
//点击用户列表, //点击用户列表,
const onclickUserItem = (userInfo, itemType) => { const onclickUserItem = (userInfo, itemType) => {
if (itemType == "all") { //公共
currentSelectUser.value = 'all'; if (isPublicType(itemType)) {
} currentSelectUser.value = itemType;
else if (itemType == "ai") {
currentSelectUser.value = 'ai';
} }
//个人
else { else {
currentSelectUser.value = userInfo; currentSelectUser.value = userInfo;
} }
@@ -294,26 +196,10 @@ const onclickUserItem = (userInfo, itemType) => {
changeInputValue(value); changeInputValue(value);
} }
//输入框按键事件
const handleKeydownInput=()=>{
// 检查是否按下 Shift + Enter
if (event.key === 'Enter' && event.shiftKey) {
// 允许输入换行
return; // 让默认行为继续
}
// 如果只按下 Enter则阻止默认的提交行为比如在表单中
if (event.key === 'Enter') {
// 阻止默认行为
event.preventDefault();
onclickSendMsg();
return;
}
}
//点击发送按钮 //点击发送按钮
const onclickSendMsg = () => { const onclickSendMsg = () => {
if (currentInputValue.value == "") { //发送空消息
if (currentInputValue.value === "") {
msgIsNullShow.value = true; msgIsNullShow.value = true;
setTimeout(() => { setTimeout(() => {
// 这里写上你想要3秒后执行的代码 // 这里写上你想要3秒后执行的代码
@@ -324,19 +210,30 @@ const onclickSendMsg = () => {
if (selectIsAll()) { if (selectIsAll()) {
onclickSendGroupMsg("all", currentInputValue.value); onclickSendGroupMsg("all", currentInputValue.value);
} } else if (selectIsAi()) {
else if (selectIsAi()) {
//ai消息需要将上下文存储 //ai消息需要将上下文存储
sendAiChatContext.value.push({ answererType: 'User', message: currentInputValue.value, number: sendAiChatContext.value.length }) sendAiChatContext.value.push({
answererType: 'User',
message: currentInputValue.value,
number: sendAiChatContext.value.length,
messageType: currentSelectUser.value
})
//离线前端存储 //离线前端存储
chatStore.addMsg({ messageType: "Ai", content: currentInputValue.value, sendUserId: userStore.id, sendUserInfo: { user: { icon: userStore.icon } } }) chatStore.addMsg({
messageType: currentSelectUser.value,
content: currentInputValue.value,
sendUserId: userStore.id,
sendUserInfo: {user: {icon: userStore.icon}}
})
//ai模型去掉key的ai@开头的字符串
const model=currentSelectUser.value.replace(/^ai@/, '');
//上下文内容当前ai进行隔离
const content= sendAiChatContext.value.filter(x=>x.messageType===currentSelectUser.value)
//发送ai消息 //发送ai消息
sendAiChat(sendAiChatContext.value); sendAiChat(content,model);
} else {
}
else {
onclickSendPersonalMsg(currentSelectUser.value.userId, currentInputValue.value); onclickSendPersonalMsg(currentSelectUser.value.userId, currentInputValue.value);
} }
changeInputValue(""); changeInputValue("");
@@ -351,80 +248,197 @@ const onclickSendPersonalMsg = (receiveId, msg) => {
content: msg, content: msg,
receiveId: receiveId receiveId: receiveId
}); });
sendPersonalMessage({ userId: receiveId, content: msg }); sendPersonalMessage({userId: receiveId, content: msg});
//调用接口发送消息 //调用接口发送消息
} }
const onclickClose = () => {
router.push({ path: "/index" })
.then(() => {
// 重新刷新页面
location.reload()
})
}
//点击发送群组消息按钮 //点击发送群组消息按钮
const onclickSendGroupMsg = (groupName, msg) => { const onclickSendGroupMsg = (groupName, msg) => {
//组还需区分是否给全部成员组 //组还需区分是否给全部成员组
if (selectIsAll) { if (selectIsAll) {
//添加到本地存储,不需要,因为广播自己能够接收 sendGroupMessage({content: msg});
// chatStore.addMsg({ } else {
// messageType: "All",
// sendUserId: userStore.id,
// content: msg
// });
//调用接口发送消息
sendGroupMessage({ content: msg });
}
else {
alert("暂未实现"); alert("暂未实现");
} }
} }
//清除ai对话
const clearAiMsg = () => {
sendAiChatContext.value = [];
chatStore.clearAiMsg();
ElMessage({
message: "当前会话清除成功",
type: "success",
duration: 2000,
});
}
//获取当前最后一条信息 //获取当前最后一条信息(显示在左侧菜单)
const getLastMessage = ((receiveId, itemType) => { const getLastMessage = ((receiveId, itemType) => {
if (itemType == "all") { if (isPublicType(itemType)) {
return chatStore.allMsgContext[chatStore.allMsgContext.length - 1]?.content.substring(0, 15); const message = chatStore.getMsgContextFunc(itemType);
} return message[message.length - 1]?.content.substring(0, 15);
else if (itemType == "ai") { }
return chatStore.aiMsgContext[chatStore.aiMsgContext.length - 1]?.content.substring(0, 15);
}
else { else {
const messageContext = chatStore.personalMsgContext.filter(x => { const messageContext = chatStore.personalMsgContext.filter(x => {
//两个条件 //两个条件
//接收用户者id为对面id我发给他 //接收用户者id为对面id我发给他
//或者发送用户id为对面他发给我 //或者发送用户id为对面他发给我
return (x.receiveId == receiveId && x.sendUserId == userStore.id) || return (x.receiveId === receiveId && x.sendUserId === userStore.id) ||
(x.sendUserId == receiveId && x.receiveId == userStore.id); (x.sendUserId === receiveId && x.receiveId === userStore.id);
}); });
return messageContext[messageContext.length - 1]?.content.substring(0, 15); return messageContext[messageContext.length - 1]?.content.substring(0, 15);
} }
}) })
/*----------以下方法是对内容通用处理,没有业务逻辑,无需变化----------*/
const imageSrc = (imageName) => {
// 动态拼接路径
return new URL(`../../assets/chat_images/${imageName}`, import.meta.url).href;
}
//绑定的input改变事件
const updateInputValue = (event) => {
changeInputValue(event.target.value);
}
//输入框按键事件
const handleKeydownInput = () => {
// 检查是否按下 Shift + Enter
if (event.key === 'Enter' && event.shiftKey) {
// 允许输入换行
return; // 让默认行为继续
}
// 如果只按下 Enter则阻止默认的提交行为比如在表单中
if (event.key === 'Enter') {
// 阻止默认行为
event.preventDefault();
onclickSendMsg();
return;
}
}
//关闭聊天框
const onclickClose = () => {
router.push({path: "/index"})
.then(() => {
// 重新刷新页面
location.reload()
})
}
//清除ai对话
const clearAiMsg = () => {
sendAiChatContext.value = [];
chatStore.clearTypeMsg(currentSelectUser.value);
ElMessage({
message: "当前Ai会话清除成功",
type: "success",
duration: 2000,
});
}
//转换markdown
const toMarkDownHtml = (text) => {
marked.setOptions({
renderer: new marked.Renderer(),
highlight: function (code, language) {
return codeHandler(code, language);
},
pedantic: false,
gfm: true,//允许 Git Hub标准的markdown
tables: true,//支持表格
breaks: true,
sanitize: false,
smartypants: false,
xhtml: false,
smartLists: true,
}
);
//需要注意代码块样式
const soureHtml = marked(text);
nextTick(() => {
addCopyEvent();
})
return soureHtml;
}
//code部分处理、高亮
const codeHandler = (code, language) => {
const codeIndex = parseInt(Date.now() + "") + Math.floor(Math.random() * 10000000);
//console.log(codeIndex,"codeIndex");
// 格式化第一行是右侧language和 “复制” 按钮;
if (code) {
const navCode = navHandler(code)
try {
// 使用 highlight.js 对代码进行高亮显示
const preCode = hljs.highlightAuto(code).value;
// 将代码包裹在 textarea 中由于防止textarea渲染出现问题这里将 "<" 用 "&lt;" 代替,不影响复制功能
let html = `<pre class='hljs pre'><div class="header"><span class="language">${language}</span><span class="copy" id="${codeIndex}">复制代码</span></div><div class="code-con"><div class="nav">${navCode}</div><code class="code">${preCode}</code></div></pre>`;
codeCopyDic.push({id: codeIndex, code: code});
// console.log(codeCopyDic.length);
return html;
//<textarea style="position: absolute;top: -9999px;left: -9999px;z-index: -9999;" id="copy${codeIndex}">${code.replace(/<\/textarea>/g, "&lt;/textarea>")}</textarea>
} catch (error) {
console.log(error);
}
}
}
//左侧导航栏处理
const navHandler = (code) => {
//获取行数
var linesCount = getLinesCount(code);
var currentLine = 1;
var liHtml = ``;
while (linesCount + 1 >= currentLine) {
liHtml += `<li class="nav-li">${currentLine}</li>`
currentLine++
}
let html = `<ul class="nav-ul">${liHtml}</ul>`
return html;
}
const BREAK_LINE_REGEXP = /\r\n|\r|\n/g;
const getLinesCount = (text) => {
return (text.trim().match(BREAK_LINE_REGEXP) || []).length;
}
let timerTip = null;
//倒计时显示tip
const startCountTip = () => {
timerTip = setInterval(() => {
if (isShowTipNumber.value > 0) {
isShowTipNumber.value--;
} else {
clearInterval(timerTip); // 倒计时结束
}
}, 1000);
};
//代码copy事件
const addCopyEvent = () => {
const copySpans = document.querySelectorAll('.copy');
// 为每个 copy span 元素添加点击事件
copySpans.forEach(span => {
//先移除,再新增
span.removeEventListener('click', clickCopyEvent);
span.addEventListener('click', clickCopyEvent);
});
}
const clickCopyEvent = async function (event) {
const spanId = event.target.id;
console.log(codeCopyDic, "codeCopyDic")
console.log(spanId, "spanId")
await navigator.clipboard.writeText(codeCopyDic.filter(x => x.id === spanId)[0].code);
ElMessage({
message: "代码块复制成功",
type: "success",
duration: 2000,
});
}
</script> </script>
<template> <template>
<div style="position: absolute; top: 0;left: 0;" v-show="isShowTipNumber>0"> <div style="position: absolute; top: 0;left: 0;" v-show="isShowTipNumber>0">
<p>当前版本1.6.2</p> <p>当前版本2.0.0</p>
<p>tip:官方学习交流群每次发送消息消耗 1 钱钱</p> <p>tip:官方学习交流群每次发送消息消耗 1 钱钱</p>
<p>tip:点击聊天窗口右上角X可退出</p> <p>tip:点击聊天窗口右上角X可退出</p>
<p>tip:多人同时在聊天室时左侧可显示其他成员</p> <p>tip:多人同时在聊天室时左侧可显示其他成员</p>
<p>Ai聊天当前Ai为 OpenAi ChatGpt4</p> <p>tip:当前支持多种AI模式由于接口收费原因还请各位手下留情</p>
<p>tip:当前Ai为OpenAi ChatGpt4由于接口收费原因还请各位手下留情</p>
<p>tip:ai对话为持续对话已优化输出速度</p> <p>tip:ai对话为持续对话已优化输出速度</p>
<p>tip:ai对话只有本地存储了记录可点击清除或刷新</p> <p>tip:ai对话只有本地存储了记录可点击清除或刷新</p>
<p>即将自动隐藏tip{{ isShowTipNumber }}</p> <p>即将自动隐藏tip{{ isShowTipNumber }}</p>
@@ -436,72 +450,52 @@ const getLastMessage = ((receiveId, itemType) => {
<img :src="userStore.icon"> <img :src="userStore.icon">
</div> </div>
<ul class="top-icon"> <ul class="top-icon">
<li><img src="@/assets/chat_images/wechat.png" /></li> <li><img src="@/assets/chat_images/wechat.png"/></li>
<li><img src="@/assets/chat_images/addressBook.png" /></li> <li><img src="@/assets/chat_images/addressBook.png"/></li>
<li><img src="@/assets/chat_images/collection.png" /></li> <li><img src="@/assets/chat_images/collection.png"/></li>
<li><img src="@/assets/chat_images/file.png" /></li> <li><img src="@/assets/chat_images/file.png"/></li>
<li><img src="@/assets/chat_images/friend.png" /></li> <li><img src="@/assets/chat_images/friend.png"/></li>
<li><img src="@/assets/chat_images/line.png" /></li> <li><img src="@/assets/chat_images/line.png"/></li>
<li><img src="@/assets/chat_images/look.png" /></li> <li><img src="@/assets/chat_images/look.png"/></li>
<li><img src="@/assets/chat_images/sou.png" /></li> <li><img src="@/assets/chat_images/sou.png"/></li>
</ul> </ul>
<ul class="bottom-icon"> <ul class="bottom-icon">
<li><img src="@/assets/chat_images/mini.png" /></li> <li><img src="@/assets/chat_images/mini.png"/></li>
<li><img src="@/assets/chat_images/phone.png" /></li> <li><img src="@/assets/chat_images/phone.png"/></li>
<li><img src="@/assets/chat_images/other.png" /></li> <li><img src="@/assets/chat_images/other.png"/></li>
</ul> </ul>
</div> </div>
<div class="middle"> <div class="middle">
<div class="header"> <div class="header">
<div class="header-div"> <div class="header-div">
<div class="search"> <div class="search">
<img src="@/assets/chat_images/search.png" /> <img src="@/assets/chat_images/search.png"/>
<span>搜索</span> <span>搜索</span>
</div> </div>
<button type="button"> <img src="@/assets/chat_images/add.png" /></button> <button type="button"><img src="@/assets/chat_images/add.png"/></button>
</div> </div>
</div> </div>
<div class="user-list"> <div class="user-list">
<div class="user-div" @click="onclickUserItem(null, 'all')" <div v-for="item in inputListDataStore.filter(x=>x.type!=='user')" :key="item.key" class="user-div"
:class="{ 'select-user-item': currentSelectUser == 'all' }"> @click="onclickUserItem(null, item.key)"
:class="{ 'select-user-item': currentSelectUser === item.key }">
<div class="user-div-left"> <div class="user-div-left">
<img src="@/assets/chat_images/yilogo.png" /> <img style="height: 48px;width: 48px; " :src="imageSrc(item.logo)"/>
<div class="user-name-msg"> <div class="user-name-msg">
<p class="font-name">官方学习交流群</p> <p class="font-name">{{ item.name }}</p>
<p class="font-msg">{{ getLastMessage(null, 'all') }}</p> <p class="font-msg">{{ getLastMessage(null, item.key) }}</p>
</div> </div>
</div> </div>
<div class=" user-div-right"> <div class=" user-div-right">
10:28 10:28
</div> </div>
</div> </div>
<div class="user-div" @click="onclickUserItem(null, 'ai')"
:class="{ 'select-user-item': currentSelectUser == 'ai' }">
<div class="user-div-left">
<img src="/openAi.png" />
<div class="user-name-msg">
<p class="font-name">Ai-ChatGpt</p>
<p class="font-msg">{{ getLastMessage(null, 'ai') }}</p>
</div>
</div>
<div class=" user-div-right">
10:28
</div>
</div>
<div v-for="(item, i) in currentUserItem" :key="i" @click="onclickUserItem(item, 'user')" class="user-div" <div v-for="(item, i) in currentUserItem" :key="i" @click="onclickUserItem(item, 'user')" class="user-div"
:class="{ 'select-user-item': currentSelectUser?.userId == item.userId }"> :class="{ 'select-user-item': currentSelectUser?.userId === item.userId }">
<div class="user-div-left"> <div class="user-div-left">
<img :src="getChatUrl(item.userIcon)"/>
<img :src="getChatUrl(item.userIcon)" />
<div class="user-name-msg"> <div class="user-name-msg">
<p class="font-name">{{ item.userName }}</p> <p class="font-name">{{ item.userName }}</p>
<p class="font-msg">{{ getLastMessage(item.userId, 'user') }}</p> <p class="font-msg">{{ getLastMessage(item.userId, 'user') }}</p>
@@ -516,19 +510,20 @@ const getLastMessage = ((receiveId, itemType) => {
<div class="right"> <div class="right">
<div class="header"> <div class="header">
<div class="header-left">{{ currentHeaderName }} <span class="clear-msg" v-show="selectIsAi()" @click="clearAiMsg">点击此处清空当前对话</span> <div class="header-left">{{ currentHeaderName }} <span class="clear-msg" v-show="selectIsAi()"
@click="clearAiMsg">点击此处清空当前对话</span>
</div> </div>
<div class="header-right"> <div class="header-right">
<div> <div>
<ul> <ul>
<li><img src="@/assets/chat_images/fixed.png" /></li> <li><img src="@/assets/chat_images/fixed.png"/></li>
<li><img src="@/assets/chat_images/min.png" /></li> <li><img src="@/assets/chat_images/min.png"/></li>
<li><img src="@/assets/chat_images/max.png" /></li> <li><img src="@/assets/chat_images/max.png"/></li>
<li style="cursor: pointer;" @click="onclickClose"><img src="@/assets/chat_images/close.png" /></li> <li style="cursor: pointer;" @click="onclickClose"><img src="@/assets/chat_images/close.png"/></li>
</ul> </ul>
</div> </div>
<div class="more"><img src="@/assets/chat_images/other2.png" /></div> <div class="more"><img src="@/assets/chat_images/other2.png"/></div>
</div> </div>
@@ -539,20 +534,20 @@ const getLastMessage = ((receiveId, itemType) => {
<!-- 对话框右侧 --> <!-- 对话框右侧 -->
<div class="content-myself content-common" v-if="item.sendUserId == userStore.id"> <div class="content-myself content-common" v-if="item.sendUserId === userStore.id">
<div class="content-myself-msg content-msg-common " v-html="item.content"></div> <div class="content-myself-msg content-msg-common " v-html="item.content"></div>
<img :src="getChatUrl(item.sendUserInfo?.user.icon, 'right')" /> <img :src="getChatUrl(item.sendUserInfo?.user.icon, 'right')"/>
</div> </div>
<!-- 对话框左侧 --> <!-- 对话框左侧 -->
<div class="content-others content-common" v-else> <div class="content-others content-common" v-else>
<img :src="getChatUrl(item.sendUserInfo?.user.icon, 'left')" /> <img :src="getChatUrl(item.sendUserInfo?.user.icon, 'left')"/>
<div> <div>
<p v-if="selectIsAll()" class="content-others-username">{{ item.sendUserInfo?.user.userName }}</p> <p v-if="selectIsAll()" class="content-others-username">{{ item.sendUserInfo?.user.userName }}</p>
<div class="content-others-msg content-msg-common " :class="{ 'content-others-msg-group': selectIsAll() }" <div class="content-others-msg content-msg-common " :class="{ 'content-others-msg-group': selectIsAll() }"
v-html="item.content"> v-html="item.content">
</div> </div>
</div> </div>
@@ -565,15 +560,15 @@ const getLastMessage = ((receiveId, itemType) => {
<div class="bottom-tool"> <div class="bottom-tool">
<ul class="ul-left"> <ul class="ul-left">
<li><img src="@/assets/chat_images/emoji.png" /></li> <li><img src="@/assets/chat_images/emoji.png"/></li>
<li><img src="@/assets/chat_images/sendFile.png" /></li> <li><img src="@/assets/chat_images/sendFile.png"/></li>
<li><img src="@/assets/chat_images/screenshot.png" /></li> <li><img src="@/assets/chat_images/screenshot.png"/></li>
<li><img src="@/assets/chat_images/chatHistory.png" /></li> <li><img src="@/assets/chat_images/chatHistory.png"/></li>
</ul> </ul>
<ul class="ul-right"> <ul class="ul-right">
<li><img src="@/assets/chat_images/landline.png" /></li> <li><img src="@/assets/chat_images/landline.png"/></li>
<li><img src="@/assets/chat_images/videoChat.png" /></li> <li><img src="@/assets/chat_images/videoChat.png"/></li>
</ul> </ul>
</div> </div>
@@ -582,9 +577,9 @@ const getLastMessage = ((receiveId, itemType) => {
</div> --> </div> -->
<textarea class="bottom-input" v-model="currentInputValue" @input="updateInputValue" <textarea class="bottom-input" v-model="currentInputValue" @input="updateInputValue"
@keydown="handleKeydownInput" @keydown="handleKeydownInput"
> >
</textarea> </textarea>
<div class="bottom-send"> <div class="bottom-send">
@@ -599,6 +594,10 @@ const getLastMessage = ((receiveId, itemType) => {
</div> </div>
</template> </template>
<style scoped lang="scss"> <style scoped lang="scss">
ul {
list-style-type: none;
}
.body { .body {
height: 790px; height: 790px;
width: 1400px; width: 1400px;
@@ -912,7 +911,6 @@ const getLastMessage = ((receiveId, itemType) => {
} }
.content-common { .content-common {
display: flex; display: flex;
margin-bottom: 18px; margin-bottom: 18px;
@@ -924,7 +922,7 @@ const getLastMessage = ((receiveId, itemType) => {
} }
.content-msg-common { .content-msg-common {
// display: flex; // display: flex;
align-content: center; align-content: center;
flex-wrap: wrap; flex-wrap: wrap;
position: relative; position: relative;
@@ -1068,6 +1066,7 @@ const getLastMessage = ((receiveId, itemType) => {
margin-bottom: 0; margin-bottom: 0;
//overflow-x: hidden; //overflow-x: hidden;
overflow-x: scroll; overflow-x: scroll;
.header { .header {
background-color: #409eff; background-color: #409eff;
color: white; color: white;
@@ -1077,7 +1076,8 @@ const getLastMessage = ((receiveId, itemType) => {
padding-top: 5px; padding-top: 5px;
.language {} .language {
}
.copy:hover { .copy:hover {
cursor: pointer; cursor: pointer;
@@ -1111,15 +1111,18 @@ const getLastMessage = ((receiveId, itemType) => {
} }
.clear-msg{
.clear-msg {
font-size: large; font-size: large;
margin-left: 10px; margin-left: 10px;
cursor: pointer; /* 设置为手型 */ cursor: pointer; /* 设置为手型 */
} }
.clear-msg:hover { .clear-msg:hover {
color: red; color: red;
cursor: pointer; /* 设置鼠标悬浮为手型 */ cursor: pointer; /* 设置鼠标悬浮为手型 */
} }
::v-deep(.nav-ul) { ::v-deep(.nav-ul) {
border-right: 1px solid #FFFFFF; border-right: 1px solid #FFFFFF;
margin-top: 12px; margin-top: 12px;

View File

@@ -38,7 +38,7 @@ export const delRole = roleIds => {
/** 修改角色数据权限 */ /** 修改角色数据权限 */
export const updataDataScope = data => { export const updataDataScope = data => {
return http.request<Result>("put", `/role/data-scpoce`, { data }); return http.request<Result>("put", `/role/data-scope`, { data });
}; };
/** 根据角色ID查询菜单下拉树结构 */ /** 根据角色ID查询菜单下拉树结构 */

View File

@@ -40,7 +40,7 @@ export function updateRole(data) {
// 角色数据权限 // 角色数据权限
export function dataScope(data) { export function dataScope(data) {
return request({ return request({
url: '/role/data-scpoce', url: '/role/data-scope',
method: 'put', method: 'put',
data: data data: data
}) })

View File

@@ -3,11 +3,11 @@
<el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true"> <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true">
<el-form-item label="角色名称" prop="roleName"> <el-form-item label="角色名称" prop="roleName">
<el-input v-model="queryParams.roleName" placeholder="请输入角色名称" clearable style="width: 240px" <el-input v-model="queryParams.roleName" placeholder="请输入角色名称" clearable style="width: 240px"
@keyup.enter="handleQuery" /> @keyup.enter="handleQuery" />
</el-form-item> </el-form-item>
<el-form-item label="角色编号" prop="roleCode"> <el-form-item label="角色编号" prop="roleCode">
<el-input v-model="queryParams.roleCode" placeholder="请输入角色编号" clearable style="width: 240px" <el-input v-model="queryParams.roleCode" placeholder="请输入角色编号" clearable style="width: 240px"
@keyup.enter="handleQuery" /> @keyup.enter="handleQuery" />
</el-form-item> </el-form-item>
<el-form-item label="状态" prop="state"> <el-form-item label="状态" prop="state">
<el-select v-model="queryParams.state" placeholder="角色状态" clearable style="width: 240px"> <el-select v-model="queryParams.state" placeholder="角色状态" clearable style="width: 240px">
@@ -16,7 +16,7 @@
</el-form-item> </el-form-item>
<el-form-item label="创建时间" style="width: 308px"> <el-form-item label="创建时间" style="width: 308px">
<el-date-picker v-model="dateRange" value-format="YYYY-MM-DD" type="daterange" range-separator="-" <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker> start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
</el-form-item> </el-form-item>
<el-form-item> <el-form-item>
<el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button> <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
@@ -29,11 +29,11 @@
</el-col> </el-col>
<el-col :span="1.5"> <el-col :span="1.5">
<el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate" <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
v-hasPermi="['system:role:edit']">修改</el-button> v-hasPermi="['system:role:edit']">修改</el-button>
</el-col> </el-col>
<el-col :span="1.5"> <el-col :span="1.5">
<el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
v-hasPermi="['system:role:remove']">删除</el-button> v-hasPermi="['system:role:remove']">删除</el-button>
</el-col> </el-col>
<el-col :span="1.5"> <el-col :span="1.5">
<el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['system:role:export']">导出 <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['system:role:export']">导出
@@ -52,7 +52,7 @@
<el-table-column label="状态" align="center"> <el-table-column label="状态" align="center">
<template #default="scope"> <template #default="scope">
<el-switch v-model="scope.row.state" :active-value="true" :inactive-value="false" <el-switch v-model="scope.row.state" :active-value="true" :inactive-value="false"
@change="handleStatusChange(scope.row)"></el-switch> @change="handleStatusChange(scope.row)"></el-switch>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="创建时间" align="center" prop="creationTime"> <el-table-column label="创建时间" align="center" prop="creationTime">
@@ -72,7 +72,7 @@
</el-tooltip> </el-tooltip>
<el-tooltip content="数据权限" placement="top" v-if="scope.row.roleId !== 1"> <el-tooltip content="数据权限" placement="top" v-if="scope.row.roleId !== 1">
<el-button link icon="CircleCheck" @click="handleDataScope(scope.row)" <el-button link icon="CircleCheck" @click="handleDataScope(scope.row)"
v-hasPermi="['system:role:edit']"></el-button> v-hasPermi="['system:role:edit']"></el-button>
</el-tooltip> </el-tooltip>
<el-tooltip content="分配用户" placement="top" v-if="scope.row.roleId !== 1"> <el-tooltip content="分配用户" placement="top" v-if="scope.row.roleId !== 1">
<el-button link icon="User" @click="handleAuthUser(scope.row)" v-hasPermi="['system:role:edit']"> <el-button link icon="User" @click="handleAuthUser(scope.row)" v-hasPermi="['system:role:edit']">
@@ -83,7 +83,7 @@
</el-table> </el-table>
<pagination v-show="total > 0" :total="Number(total)" v-model:page="queryParams.skipCount" v-model:limit="queryParams.maxResultCount" <pagination v-show="total > 0" :total="Number(total)" v-model:page="queryParams.skipCount" v-model:limit="queryParams.maxResultCount"
@pagination="getList" /> @pagination="getList" />
<!-- 添加或修改角色配置对话框 --> <!-- 添加或修改角色配置对话框 -->
<el-dialog :title="title" v-model="open" width="500px" append-to-body> <el-dialog :title="title" v-model="open" width="500px" append-to-body>
@@ -110,7 +110,7 @@
<el-form-item label="状态"> <el-form-item label="状态">
<el-radio-group v-model="form.state"> <el-radio-group v-model="form.state">
<el-radio v-for="dict in sys_normal_disable" :key="dict.value" :value="JSON.parse(dict.value)">{{ dict.label <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :value="JSON.parse(dict.value)">{{ dict.label
}}</el-radio> }}</el-radio>
</el-radio-group> </el-radio-group>
</el-form-item> </el-form-item>
<el-form-item label="菜单权限"> <el-form-item label="菜单权限">
@@ -119,8 +119,8 @@
<el-checkbox v-model="form.menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')">父子联动 <el-checkbox v-model="form.menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')">父子联动
</el-checkbox> </el-checkbox>
<el-tree class="tree-border" :data="menuOptions" show-checkbox ref="menuRef" node-key="id" <el-tree class="tree-border" :data="menuOptions" show-checkbox ref="menuRef" node-key="id"
:check-strictly="!form.menuCheckStrictly" empty-text="加载中请稍候" :check-strictly="!form.menuCheckStrictly" empty-text="加载中请稍候"
:props="{ label: 'label', children: 'children' }"></el-tree> :props="{ label: 'label', children: 'children' }"></el-tree>
</el-form-item> </el-form-item>
<el-form-item label="备注"> <el-form-item label="备注">
<el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input> <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
@@ -155,8 +155,8 @@
<el-checkbox v-model="form.deptCheckStrictly" @change="handleCheckedTreeConnect($event, 'dept')">父子联动 <el-checkbox v-model="form.deptCheckStrictly" @change="handleCheckedTreeConnect($event, 'dept')">父子联动
</el-checkbox> </el-checkbox>
<el-tree class="tree-border" :data="deptOptions" show-checkbox default-expand-all ref="deptRef" node-key="id" <el-tree class="tree-border" :data="deptOptions" show-checkbox default-expand-all ref="deptRef" node-key="id"
:check-strictly="!form.deptCheckStrictly" empty-text="加载中请稍候" :check-strictly="!form.deptCheckStrictly" empty-text="加载中请稍候"
:props="{ label: 'label', children: 'children' }"></el-tree> :props="{ label: 'label', children: 'children' }"></el-tree>
</el-form-item> </el-form-item>
</el-form> </el-form>
<template #footer> <template #footer>
@@ -184,10 +184,11 @@ import {
treeselect as menuTreeselect, treeselect as menuTreeselect,
listMenu, listMenu,
} from "@/api/system/menu"; } from "@/api/system/menu";
import { listDept, roleDeptTreeselect } from "@/api/system/dept"; import {listDept, roleDeptTreeselect} from "@/api/system/dept";
const router = useRouter(); const router = useRouter();
const { proxy } = getCurrentInstance(); const {proxy} = getCurrentInstance();
const { sys_normal_disable } = proxy.useDict("sys_normal_disable"); const {sys_normal_disable} = proxy.useDict("sys_normal_disable");
const roleList = ref([]); const roleList = ref([]);
const open = ref(false); const open = ref(false);
@@ -211,16 +212,15 @@ const deptRef = ref(null);
/** 数据范围选项*/ /** 数据范围选项*/
const dataScopeOptions = ref([ const dataScopeOptions = ref([
{ value: 'ALL', label: "全部数据权限" }, {value: 'ALL', label: "全部数据权限"},
{ value: 'CUSTOM', label: "自定数据权限" }, {value: 'CUSTOM', label: "自定数据权限"},
{ value: 'DEPT', label: "本部门数据权限" }, {value: 'DEPT', label: "本部门数据权限"},
{ value: 'DEPT_FOLLOW', label: "本部门及以下数据权限" }, {value: 'DEPT_FOLLOW', label: "本部门及以下数据权限"},
{ value: 'USER', label: "仅本人数据权限" }, {value: 'USER', label: "仅本人数据权限"},
]); ]);
const data = reactive({ const data = reactive({
form: { form: {},
},
queryParams: { queryParams: {
skipCount: 1, skipCount: 1,
maxResultCount: 10, maxResultCount: 10,
@@ -230,86 +230,94 @@ const data = reactive({
}, },
rules: { rules: {
roleName: [ roleName: [
{ required: true, message: "角色名称不能为空", trigger: "blur" }, {required: true, message: "角色名称不能为空", trigger: "blur"},
], ],
roleCode: [ roleCode: [
{ required: true, message: "权限字符不能为空", trigger: "blur" }, {required: true, message: "权限字符不能为空", trigger: "blur"},
], ],
orderNum: [ orderNum: [
{ required: true, message: "角色顺序不能为空", trigger: "blur" }, {required: true, message: "角色顺序不能为空", trigger: "blur"},
], ],
}, },
}); });
const { queryParams, form, rules } = toRefs(data); const {queryParams, form, rules} = toRefs(data);
/** 查询角色列表 */ /** 查询角色列表 */
function getList() { function getList() {
loading.value = true; loading.value = true;
listRole(proxy.addDateRange(queryParams.value, dateRange.value)).then( listRole(proxy.addDateRange(queryParams.value, dateRange.value)).then(
(response) => { (response) => {
roleList.value = response.data.items; roleList.value = response.data.items;
total.value = response.data.totalCount; total.value = response.data.totalCount;
loading.value = false; loading.value = false;
} }
); );
} }
/** 搜索按钮操作 */ /** 搜索按钮操作 */
function handleQuery() { function handleQuery() {
queryParams.value.skipCount = 1; queryParams.value.skipCount = 1;
getList(); getList();
} }
/** 重置按钮操作 */ /** 重置按钮操作 */
function resetQuery() { function resetQuery() {
dateRange.value = []; dateRange.value = [];
proxy.resetForm("queryRef"); proxy.resetForm("queryRef");
handleQuery(); handleQuery();
} }
/** 删除按钮操作 */ /** 删除按钮操作 */
function handleDelete(row) { function handleDelete(row) {
const roleIds = row.id || ids.value; const roleIds = row.id || ids.value;
proxy.$modal proxy.$modal
.confirm('是否确认删除角色编号为"' + roleIds + '"的数据项?') .confirm('是否确认删除角色编号为"' + roleIds + '"的数据项?')
.then(function () { .then(function () {
return delRole(roleIds); return delRole(roleIds);
}) })
.then(() => { .then(() => {
getList(); getList();
proxy.$modal.msgSuccess("删除成功"); proxy.$modal.msgSuccess("删除成功");
}) })
.catch(() => { }); .catch(() => {
});
} }
/** 导出按钮操作 */ /** 导出按钮操作 */
function handleExport() { function handleExport() {
proxy.download( proxy.download(
"system/role/export", "system/role/export",
{ {
...queryParams.value, ...queryParams.value,
}, },
`role_${new Date().getTime()}.xlsx` `role_${new Date().getTime()}.xlsx`
); );
} }
/** 多选框选中数据 */ /** 多选框选中数据 */
function handleSelectionChange(selection) { function handleSelectionChange(selection) {
ids.value = selection.map((item) => item.id); ids.value = selection.map((item) => item.id);
single.value = selection.length != 1; single.value = selection.length != 1;
multiple.value = !selection.length; multiple.value = !selection.length;
} }
/** 角色状态修改 */ /** 角色状态修改 */
function handleStatusChange(row) { function handleStatusChange(row) {
let text = row.state === true ? "启用" : "停用"; let text = row.state === true ? "启用" : "停用";
proxy.$modal proxy.$modal
.confirm('确认要"' + text + '""' + row.roleName + '"角色吗?') .confirm('确认要"' + text + '""' + row.roleName + '"角色吗?')
.then(function () { .then(function () {
return changeRoleStatus(row.id, row.state); return changeRoleStatus(row.id, row.state);
}) })
.then(() => { .then(() => {
proxy.$modal.msgSuccess(text + "成功"); proxy.$modal.msgSuccess(text + "成功");
}) })
.catch(function () { .catch(function () {
row.state = row.state === true ? false : true; row.state = row.state === true ? false : true;
}); });
} }
/** 更多操作 */ /** 更多操作 */
function handleCommand(command, row) { function handleCommand(command, row) {
switch (command) { switch (command) {
@@ -323,10 +331,12 @@ function handleCommand(command, row) {
break; break;
} }
} }
/** 分配用户 */ /** 分配用户 */
function handleAuthUser(row) { function handleAuthUser(row) {
router.push("/system/role-auth/user/" + row.id); router.push("/system/role-auth/user/" + row.id);
} }
/** 查询菜单树结构 */ /** 查询菜单树结构 */
function getMenuTreeselect() { function getMenuTreeselect() {
return listMenu().then((response) => { return listMenu().then((response) => {
@@ -354,6 +364,7 @@ function getDeptAllCheckedKeys() {
checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys); checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
return checkedKeys; return checkedKeys;
} }
/** 重置新增的表单以及其他数据 */ /** 重置新增的表单以及其他数据 */
function reset() { function reset() {
if (menuRef.value != undefined) { if (menuRef.value != undefined) {
@@ -379,6 +390,7 @@ function reset() {
}; };
proxy.resetForm("roleRef"); proxy.resetForm("roleRef");
} }
/** 添加角色 */ /** 添加角色 */
function handleAdd() { function handleAdd() {
reset(); reset();
@@ -386,8 +398,9 @@ function handleAdd() {
open.value = true; open.value = true;
title.value = "添加角色"; title.value = "添加角色";
} }
/** 修改角色 */ /** 修改角色 */
function handleUpdate(row) { function handleUpdate(row) {
reset(); reset();
const roleId = row.id || ids.value; const roleId = row.id || ids.value;
getRoleMenuTreeselect(roleId); getRoleMenuTreeselect(roleId);
@@ -398,30 +411,32 @@ function handleAdd() {
title.value = "修改角色"; title.value = "修改角色";
}); });
} }
/** 根据角色ID查询菜单树结构 */ /** 根据角色ID查询菜单树结构 */
function getRoleMenuTreeselect(roleId) { function getRoleMenuTreeselect(roleId) {
//1获取该角色下的全部菜单id //1获取该角色下的全部菜单id
//2获取全量菜单 //2获取全量菜单
const menuTreeselect=getMenuTreeselect(); const menuTreeselect = getMenuTreeselect();
menuTreeselect.then(()=>{ menuTreeselect.then(() => {
nextTick(() => { nextTick(() => {
roleMenuTreeselect(roleId).then((response) => { roleMenuTreeselect(roleId).then((response) => {
const menuIds = []; const menuIds = [];
response.data.forEach((m) => { response.data.forEach((m) => {
menuIds.push(m.id); menuIds.push(m.id);
}); });
menuIds.forEach((v) => { menuIds.forEach((v) => {
menuRef.value.setChecked(v, true, false); menuRef.value.setChecked(v, true, false);
});
//这里是要一个当前用户已拥有的菜单的id
}); });
//这里是要一个当前用户已拥有的菜单的id
}); });
});
}) })
} }
/** 根据角色ID查询部门树结构 */ /** 根据角色ID查询部门树结构 */
function getDeptTree(roleId) { function getDeptTree(roleId) {
return listDept().then((response) => { return listDept().then((response) => {
@@ -439,7 +454,7 @@ function getDeptTree(roleId) {
let deptIds = []; let deptIds = [];
roleDeptTreeselect(roleId).then((response) => { roleDeptTreeselect(roleId).then((response) => {
deptIds = response.data.map(x=>x.id); deptIds = response.data.map(x => x.id);
// nextTick(() => { // nextTick(() => {
if (deptRef.value) { if (deptRef.value) {
deptRef.value.setCheckedKeys(deptIds); deptRef.value.setCheckedKeys(deptIds);
@@ -448,6 +463,7 @@ function getDeptTree(roleId) {
}); });
}); });
} }
/** 树权限(展开/折叠)*/ /** 树权限(展开/折叠)*/
function handleCheckedTreeExpand(value, type) { function handleCheckedTreeExpand(value, type) {
if (type == "menu") { if (type == "menu") {
@@ -462,6 +478,7 @@ function handleCheckedTreeExpand(value, type) {
} }
} }
} }
/** 树权限(全选/全不选) */ /** 树权限(全选/全不选) */
function handleCheckedTreeNodeAll(value, type) { function handleCheckedTreeNodeAll(value, type) {
if (type == "menu") { if (type == "menu") {
@@ -470,6 +487,7 @@ function handleCheckedTreeNodeAll(value, type) {
deptRef.value.setCheckedNodes(value ? deptOptions.value : []); deptRef.value.setCheckedNodes(value ? deptOptions.value : []);
} }
} }
/** 树权限(父子联动) */ /** 树权限(父子联动) */
function handleCheckedTreeConnect(value, type) { function handleCheckedTreeConnect(value, type) {
if (type == "menu") { if (type == "menu") {
@@ -478,6 +496,7 @@ function handleCheckedTreeConnect(value, type) {
form.value.deptCheckStrictly = value ? true : false; form.value.deptCheckStrictly = value ? true : false;
} }
} }
/** 所有菜单节点数据 */ /** 所有菜单节点数据 */
function getMenuAllCheckedKeys() { function getMenuAllCheckedKeys() {
// 目前被选中的菜单节点 // 目前被选中的菜单节点
@@ -487,6 +506,7 @@ function getMenuAllCheckedKeys() {
checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys); checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
return checkedKeys; return checkedKeys;
} }
/** 提交按钮 */ /** 提交按钮 */
function submitForm() { function submitForm() {
proxy.$refs["roleRef"].validate((valid) => { proxy.$refs["roleRef"].validate((valid) => {
@@ -509,37 +529,53 @@ function submitForm() {
} }
}); });
} }
/** 取消按钮 */ /** 取消按钮 */
function cancel() { function cancel() {
open.value = false; open.value = false;
reset(); reset();
} }
/** 选择角色权限范围触发 */ /** 选择角色权限范围触发 */
function dataScopeSelectChange(value) { function dataScopeSelectChange(value) {
if (value !== "2") { if (value !== "2") {
deptRef.value.setCheckedKeys([]); deptRef.value.setCheckedKeys([]);
} }
} }
// 判断返回值是否是数字
function isNumeric(value) {
return /^[+-]?\d+(\.\d+)?$/;
}
/** 分配数据权限操作 */ /** 分配数据权限操作 */
function handleDataScope(row) { function handleDataScope(row) {
reset(); reset();
getDeptTree(row.id); getDeptTree(row.id);
getRole(row.id).then((response) => { getRole(row.id).then((response) => {
form.value = response.data; if(response && response.data) {
let data = {...response.data};
if(isNumeric(data.dataScope)) {
let obj = dataScopeOptions.value[data.dataScope];
if(obj) {
data["dataScope"] = obj["value"];
}
form.value = {...data};
}
}
openDataScope.value = true; openDataScope.value = true;
title.value = "分配数据权限"; title.value = "分配数据权限";
}); });
} }
/** 提交按钮(数据权限) */ /** 提交按钮(数据权限) */
function submitDataScope() { function submitDataScope() {
if (form.value.id != undefined) { if (form.value.id != undefined) {
form.value.deptIds = getDeptAllCheckedKeys(); form.value.deptIds = getDeptAllCheckedKeys();
const data={ const data = {
roleId:form.value.id, roleId: form.value.id,
deptIds:form.value.deptIds, deptIds: form.value.deptIds,
dataScope:form.value.dataScope dataScope: form.value.dataScope
} }
console.log(data) console.log(data)
dataScope(data).then((response) => { dataScope(data).then((response) => {
proxy.$modal.msgSuccess("修改成功"); proxy.$modal.msgSuccess("修改成功");
openDataScope.value = false; openDataScope.value = false;
@@ -547,6 +583,7 @@ console.log(data)
}); });
} }
} }
/** 取消按钮(数据权限)*/ /** 取消按钮(数据权限)*/
function cancelDataScope() { function cancelDataScope() {
openDataScope.value = false; openDataScope.value = false;
@@ -554,4 +591,4 @@ function cancelDataScope() {
} }
getList(); getList();
</script> </script>