123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206 |
- using Microsoft.Office.Tools.Ribbon;
- using Microsoft.Web.WebView2.Core;
- using PdfSharp.Drawing;
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Diagnostics;
- using System.Drawing;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Net.Http.Headers;
- using System.Text;
- using System.Text.Json;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- using static HTEXMark.QRCodeForm;
- namespace HTEXMark
- {
- public partial class AI_Form : Form
- {
- public RibbonButton ai_button;
- public RibbonButton user_button;
- public MarkLanguage lang;
- public MarkRibbon markRibbon;
- public RibbonDropDown schoolDropDown;
- public RibbonDropDown subjectDropDown;
- public string domain;
- private HttpClient httpClient;
- public List<IdCodeNameCount> periodSubjects = new List<IdCodeNameCount>();
- public AI_Form(List<IdCodeNameCount> periodSubjects, RibbonButton ai_button, RibbonButton user_button, RibbonDropDown schoolDropDown, RibbonDropDown subjectDropDown, MarkLanguage lang, MarkRibbon markRibbon, Microsoft.Office.Tools.CustomTaskPane customTaskPane, string domain)
- {
- this.ai_button=ai_button;
- this.user_button=user_button;
- this.lang = lang;
- this.markRibbon = markRibbon;
- this.schoolDropDown=schoolDropDown;
- this.subjectDropDown=subjectDropDown;
- this.periodSubjects=periodSubjects;
- this.httpClient=HttpClientFactory.Create();
- InitializeComponent();
- this.Load+=FormLoad;
- this.domain=domain;
- this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.AI_FormClosed);
- }
- public class ItemType {
- public string name { get; set; }
- public string type { get; set; }
- }
- private async void FormLoad(object sender, EventArgs e)
- {
- List<ItemType> items = new List<ItemType>() {
- new ItemType { name=lang.single,type= "single" },
- new ItemType { name=lang.multiple,type= "multiple" },
- new ItemType { name=lang.sortmultiple,type= "sortmultiple" },
- new ItemType { name=lang.judge,type= "judge" },
- new ItemType { name=lang.complete,type= "complete" },
- new ItemType { name=lang.subjective,type= "subjective" },
- new ItemType { name=lang.draw,type= "draw" },
- new ItemType { name=lang.connector,type= "connector" },
- new ItemType { name=lang.compose,type= "compose" },
- };
- comboBox_item_type.DataSource= items;
- comboBox_item_type.DisplayMember="name";
- comboBox_item_type.ValueMember="type";
- comboBox_subject.DataSource= periodSubjects;
- comboBox_subject.DisplayMember="name";
- comboBox_subject.ValueMember="periodType";
- // this.Text = lang.ai_title;
- // Microsoft.Web.WebView2.Core.CoreWebView2EnvironmentOptions options = new Microsoft.Web.WebView2.Core.CoreWebView2EnvironmentOptions();
- //options.AdditionalBrowserArguments = "--disable-web-security"; // 仅在开发/测试中使用,禁用同源策略
- //Microsoft.Web.WebView2.Core.CoreWebView2Environment env = await Microsoft.Web.WebView2.Core.CoreWebView2Environment.CreateAsync(null, null, options);
- var userDataFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Temp/webview2_temp");
- var environment = await CoreWebView2Environment.CreateAsync(null, userDataFolder);
- await webView21.EnsureCoreWebView2Async(environment);
- // await SparkAI("");
- // webView2.Source = new Uri("https://www.baidu.com");
- if (webView21 != null)
- {
- //webView21.Source = new Uri("about:blank"); // 设置源 URL
- // webView21.NavigationCompleted += WebView_NavigationCompleted; // 导航完成事件处理函数
- // string htmlContent = "<html><body><h1>Hello World!</h1></body></html>"; // 自定义 HTML 内容
- // webView21.NavigateToString(htmlContent); // 通过字符串形式传入 HTML 内容
- await SparkAI("");
- }
- }
- private void WebView_NavigationCompleted(object sender, CoreWebView2NavigationCompletedEventArgs e)
- {
- // 当导航完成时触发该事件,此时可以对 WebView2 进行更多操作
- Console.WriteLine($"Navigation completed with status code: {e}");
- }
- private async Task SparkAI(string name)
- {
- webView21.Source = new Uri("about:blank"); // 设置源 URL
- // InsertHtmlIntoWord(wordApp, processedHtml);
- string url = "https://appraisal-test.teammodel.cn/ai/chat/completion";
- if (QRCodeForm.token!= null)
- {
- var checkResult = await HttpClientHelper.CheckToken(UserSettings.Default.access_token, domain, UserSettings.Default.x_auth_token, httpClient);
- if (checkResult.ok)
- {
- QRCodeForm.token.access_token= checkResult.AuthorizationToken;
- StringBuilder data = new StringBuilder();
- ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
- var content = new StringContent(JsonSerializer.Serialize(new { appId = "533233bf-4605-4264-ab2d-e57a8084767a", sessionId = "", text = "请按照模板创建10个小学数学题" }), Encoding.UTF8, "application/json");
- var httpreq = new HttpRequestMessage(HttpMethod.Post, url) { Content = content };
- checkResult.httpClient.DefaultRequestHeaders.AcceptCharset.Add(new StringWithQualityHeaderValue("utf-8"));
- var response = await checkResult.httpClient.SendAsync(httpreq, HttpCompletionOption.ResponseHeadersRead);
- // 读取响应内容的异步流
- using (var responseStream = await response.Content.ReadAsStreamAsync())
- {
- //Debug.Print("============start response use minseconds=" + (DateTime.Now - d).TotalMilliseconds + " =================\r\n");
- // 逐块读取并处理响应内容
- var buffer = new byte[1024];
- int bytesRead;
- while ((bytesRead = await responseStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
- {
- // 处理响应内容
- string contentData = System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead);
- if (contentData.Contains("data:"))
- {
- contentData = contentData.Replace("data:", "").Replace("[DONE]", "");
- }
- if (contentData.Contains("[DONE]"))
- {
- contentData = contentData.Replace("data:", "").Replace("[DONE]", "");
- }
- data.Append(contentData);
- webView21.NavigateToString(data.ToString());
- var webView2 = webView21.CoreWebView2;
- await webView2.ExecuteScriptAsync("window.scrollTo(0, document.body.scrollHeight);");
- }
- }
- webView21.NavigationCompleted += WebView_NavigationCompleted; // 导航完成事件处理函数
- }
- else { MessageBox.Show(lang.unlogin); }
- }
- else { MessageBox.Show(lang.unlogin); }
- }
- private void AI_FormClosed(object sender, FormClosedEventArgs e) {
-
- }
- private async void AddAIItem_Click(object sender, EventArgs e)
- {
- // 使用 JavaScript 选择整个网页内容
- await webView21.CoreWebView2.ExecuteScriptAsync("document.execCommand('selectall')");
- // 使用 JavaScript 复制选定的内容到剪贴板
- await webView21.CoreWebView2.ExecuteScriptAsync("document.execCommand('copy')");
- IDataObject dataObject = Clipboard.GetDataObject();
- // 检查是否有图像数据
- if (dataObject != null && dataObject.GetDataPresent(DataFormats.Bitmap))
- {
- // 如果有图像数据,粘贴图像
- Bitmap bitmap = (Bitmap)dataObject.GetData(DataFormats.Bitmap);
- Globals.ThisAddIn.Application.ActiveDocument.Application.Selection.InlineShapes.AddPicture("", false, true).Range.PasteSpecial(DataType: Microsoft.Office.Interop.Word.WdPasteDataType.wdPasteBitmap);
- }
- else
- {
- // 如果没有图像数据,可以尝试其他格式的粘贴
- Globals.ThisAddIn.Application.ActiveDocument.Application.Selection.Paste();
- }
- }
- private void GenAIItem_Click(object sender, EventArgs e)
- {
- if (!string.IsNullOrWhiteSpace(richTextBoxEx.Text) && comboBox_subject.SelectedItem!=null && comboBox_item_type.SelectedItem!=null) {
-
- }
- }
- public void CenterFormOnScreen(Control qrCodeForm)
- {
- // 获取屏幕的工作区域
- var workingArea = System.Windows.Forms.Screen.GetWorkingArea(qrCodeForm);
- // 计算窗体应该显示的位置
- int x = (workingArea.Width - qrCodeForm.Width) / 2 + workingArea.Left;
- int y = (workingArea.Height - qrCodeForm.Height) / 2 + workingArea.Top;
- // 设置窗体位置
- qrCodeForm.Location = new System.Drawing.Point(x, y);
- }
-
- private void Button_AI_Option_Click(object sender, EventArgs e)
- {
- AISettingForm settingForm = new AISettingForm(schoolDropDown, periodSubjects,lang,markRibbon,domain);
- CenterFormOnScreen(settingForm);
- settingForm.ShowDialog();
- }
- }
- }
|