using System; using System.Linq; using System.Windows.Forms; using UI.Framework.Forms; using System.Text.RegularExpressions; using Api.Framework; using Api.Framework.Tools; using AutoAnswer.Entitys; using Api.Framework.SDK; using UI.Framework.Controls; using Microsoft.JScript; using System.Text; using DevExpress.XtraEditors; using DevExpress.Utils.Menu; using Eson.Utils.ExcelHelper; using System.Data; using System.Collections.Generic; using AutoAnswer.Properties; using Api.Framework.Model; using Chat.Framework; using DevExpress.XtraGrid.Views.Grid; namespace AutoAnswer { public partial class MainForm : BaseForm { public MainForm() { InitializeComponent(); } public void CloseForm() { try { if (!this.IsDisposed) { this.Invoke(new Action(delegate { this.Close(); this.Dispose(); })); } } catch (Exception ex) { ShowError(ex); } } private void MainForm_Load(object sender, EventArgs e) { try { #region 用户绑定自定义词库分页 pageControl1.Bind((page, size) => { var session = ApiClient.GetSession(); var pram = session.NewParamMap(); pram.setPageParamters(page, size); var result = session.FindPage("select * from fl_plugin_autoanswer_definedlib", pram); return new PageControl.SerchResult() { Result = result.DataList, Total = result.Total }; }, gridControl1, 40, true, true); label6.Visible = gridView1.RowCount == 0; #endregion #region 初始化赋值 buttonCheck1.Checked = Class1.Config.Is_Top_User; hyperlinkLabelControl7.Enabled = hyperlinkLabelControl6.Enabled = hyperlinkLabelControl5.Enabled = hyperlinkLabelControl4.Enabled = hyperlinkLabelControl2.Enabled = memoEdit1.Enabled = bck_acquiescent_Auto_Answer_onoff.Checked = Class1.Config.Is_Auto_Answer; memoEdit1.Text = string.Join(@" -----------分割线----------- ", Class1.Config.DefaultContents); bck_TuLing_onoff.Checked = Class1.Config.TuLing_OnOff; tbx_TuLing_prefix.Text = Class1.Config.TuLing_prefix; tbx_TuLing_apikey.Text = Class1.Config.TuLing_apikey; cbx_chattype.Items.Clear(); cbx_chattype.Items.Add("全部"); cbx_chattype.SelectedIndex = 0; foreach (ChatType item in Enum.GetValues(typeof(ChatType))) cbx_chattype.Items.Add(item); #endregion #region 用户绑定未回复记录分页 pageControl2.Bind((page, size) => { string sql = string.Empty; sql = "select * from fl_plugin_autoanswer__log where 1=1 "; this.Invoke(new Action(() => { try { if (cbx_chattype.SelectedIndex != 0) sql += $" and chatType = '{cbx_chattype.SelectedIndex - 1}'"; } catch (Exception) { } })); if (!string.IsNullOrWhiteSpace(tBox_userInfo.Text)) sql += $" and (useraccount like '%{tBox_userInfo.Text.Replace("'", "''").Trim()}%' or username like '%{GlobalObject.escape(tBox_userInfo.Text.Replace("'", "''").Trim())}%')"; if (checkBox.Checked) sql += $" and '{DateTime.Now.AddDays(-(double)numericUpDown_days.Value).ToString("u")}' <= datetime and datetime <= '{DateTime.Now.ToString("u")}'"; sql += " order by datetime DESC"; var session = ApiClient.GetSession(); var parm = session.NewParamMap(); parm.setPageParamters(page, size); var result = session.FindPage(sql, parm); return new PageControl.SerchResult() { Result = result.DataList, Total = result.Total }; }, gridControl2, 40, true, true); label5.Visible = gridView2.RowCount == 0; #endregion #region 未识别的消息转发 Refresh(); repositoryItemComboBox1.SelectedValueChanged += RepositoryItemComboBox1_SelectedValueChanged; #endregion this.settingControl1.Bind(Class1.Config); this.dropDownButton1.DropDownControl = CreateDXPopupMenu(); } catch (Exception ex) { ShowError(ex); } } private new void Refresh() { try { this.gridControl3.DataSource = null; #region 加载所有的账号 var db = ApiClient.GetSession(); //所有机器人列表 var robotList = db.FindRobots(true); List list = new List(); if (robotList != null && robotList.Count != 0) { var loginWxs = ChatClient.WXClient.Values.Where(f => f.Status == Chat.Framework.WXSdk.WxStatus.在线).ToList(); //在线集合 var robotTemp_online = robotList.Where(f => loginWxs.FirstOrDefault(z => z.WeixinHao == f.name) != null).OrderBy(f => f.type).ToList(); //离线集合 var robotTemp_offline = robotList.Where(f => loginWxs.FirstOrDefault(z => z.WeixinHao == f.name) == null).ToList(); robotTemp_online.AddRange(robotTemp_offline); robotList = robotTemp_online; var tbList = db.Find("select * from fl_plugin_autoanswer_unprocessed"); foreach (var item in robotList) { var info = tbList.FirstOrDefault(f => f.rid == item.id); list.Add(new ShowTmp() { ID = item.id, name = item.name, nick = item.nick, chattype = item.type, username = info == null ? string.Empty : info.username, messtype = info == null ? "所有类型" : info.messtype }); } } this.gridControl3.DataSource = list; #endregion } catch (Exception) { } } private DXPopupMenu CreateDXPopupMenu() { DXPopupMenu menu = new DXPopupMenu(); menu.Items.Add(new DXMenuItem("获取导入模板", OnItemClick)); menu.Items.Add(new DXMenuItem("导入外部数据", OnItemClick)); return menu; } private void OnItemClick(object sender, EventArgs e) { try { DXMenuItem item = sender as DXMenuItem; if (item.Caption == "获取导入模板") { SaveFileDialog fbd = new SaveFileDialog(); fbd.FileName = "自定义问答导入模板"; fbd.Filter = "Excel|*.xls;*.xlsx;"; fbd.Title = "保存为"; if (fbd.ShowDialog() == DialogResult.OK) { var path = fbd.FileName; if (Util.WriteByteToFile(Resources.自定义问答导入模板, path)) ShowSuccess("保存成功,设置方式请看表头提示"); else ShowError("保存失败"); } } else if (item.Caption == "导入外部数据") { OpenFileDialog fileDialog = new OpenFileDialog(); fileDialog.Multiselect = true; fileDialog.Title = "请选择文件"; fileDialog.Filter = "所有文件(*xls*)|*.xls*"; //设置要选择的文件的类型 if (fileDialog.ShowDialog() == DialogResult.OK) { string file = fileDialog.FileName;//返回文件的完整路径 var excelTool = new ExcelStreamExport(); var dataTable = excelTool.ConvertExcelToTable(file, 0); var session = ApiClient.GetSession(); var userdefinedlibraryList = new List(); foreach (DataRow data in dataTable.Rows) { int match_pattern = -1; var ss = data[0].ToString(); switch (data[0].ToString()) { case "模糊": match_pattern = 1; break; case "全部": match_pattern = 0; break; default: continue; } if (string.IsNullOrWhiteSpace(data[1].ToString()) || string.IsNullOrWhiteSpace(data[2].ToString())) continue; var list = new List(); var is_alert_admin = _ConvertData(data[3].ToString()); if (-1 == is_alert_admin) continue; var qq = _ConvertData(data[4].ToString()); if (-1 == qq) continue; else if (qq == 1) list.Add(1); var wx = _ConvertData(data[5].ToString()); if (-1 == wx) continue; else if (wx == 1) list.Add(2); var gzh = _ConvertData(data[6].ToString()); if (-1 == gzh) continue; else if (gzh == 1) list.Add(3); userdefinedlibraryList.Add(new fl_plugin_autoanswer_definedlib() { match_pattern = match_pattern, antistop = GlobalObject.escape(data[1].ToString()), content = GlobalObject.escape(data[2].ToString()), is_alert_admin = is_alert_admin, chat_type = string.Join(",", list) }); } if (userdefinedlibraryList != null && userdefinedlibraryList.Count != 0) session.Insertable(userdefinedlibraryList).ExecuteCommand(); else throw new Exception("数据为空,请填写数据后操作导入操作"); ShowSuccess($@"导入数据一共:{dataTable.Rows.Count}条 导入成功:{userdefinedlibraryList.Count}条 导入失败:{dataTable.Rows.Count - userdefinedlibraryList.Count}条"); pageControl1.GotoPage(); } } } catch (Exception ex) { if (ex.Message == "InsertObjs is null") { ShowError("导入模板内容填写错误"); return; } ShowError(ex); } } private int _ConvertData(string str) { switch (str) { case "是": return 1; case "否": return 0; default: return -1; } } /// /// 跳转到图灵注册页面 /// /// /// private void hyperlinkLabelControl1_Click(object sender, EventArgs e) { System.Diagnostics.Process.Start(@"http://www.tuling123.com/sso-web/register?ReturnURL=http%3A%2F%2Fwww.tuling123.com%2F"); } private void barButtonItem2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { try { var selectRows = gridView1.GetSelectedRows(); if (e.Item.Caption.Trim().Contains("增")) { var editUserDefined = new EditUserDefinedForm(string.Empty); editUserDefined.ShowDialog(); } else if (selectRows.Length > 0) { if (e.Item.Caption.Contains("修")) { var editUserDefined = new EditUserDefinedForm(gridView1.GetRowCellValue(selectRows[0], "id").ToString()); editUserDefined.ShowDialog(); } else if (e.Item.Caption == "删除所有项") { if (MessageBox.Show("确定删除所有的数据吗", "温馨提示", MessageBoxButtons.YesNo) == DialogResult.Yes) { var session = ApiClient.GetSession(); session.Deleteable().ExecuteCommand(); } } else if (e.Item.Caption.Contains("删")) { var session = ApiClient.GetSession(); try { for (int i = selectRows.Length - 1; i >= 0; i--) { var pram = session.NewParamMap(); var id = gridView1.GetRowCellValue(selectRows[i], "id").ToString(); session.ExcuteSQL($"DELETE FROM fl_plugin_autoanswer_definedlib where id = @id", new { id = id }); } } catch (Exception ex) { throw ex; } } } } catch (Exception ex) { ShowError(ex); } finally { Tools.RefreshWordbanck1(); this.pageControl1.GotoPage(1); label6.Visible = gridView1.RowCount == 0; } } /// /// 检测图灵apikey是否可以正常使用 /// /// /// private void simpleButton1_Click(object sender, EventArgs e) { try { if (!string.IsNullOrEmpty(tbx_TuLing_apikey.Text)) { string htmlResult = Tools.GetHtml("测试1", "123123", tbx_TuLing_apikey.Text); if (Regex.IsMatch(htmlResult, @".?intent.?:{.?code.?:(5000|6000|4000|4001|4002|4003|4004|4005|4007|4100|4200|4300|4400|4500|4600|4602|7002|8008)}")) throw new Exception("测试失败"); else ShowSuccess("测试成功"); } else throw new Exception("图灵ApiKey不能为空,请先填写后重试!"); } catch (Exception ex) { ShowError(ex); } } /// /// 选中的tab值发生变化时 /// /// /// private void xtraTabControl1_Selected(object sender, DevExpress.XtraTab.TabPageEventArgs e) { try { if (e.PageIndex == 0) { this.pageControl1.GotoPage(1); label6.Visible = gridView1.RowCount == 0; } else if (e.PageIndex == 3) { this.pageControl2.GotoPage(1); label5.Visible = gridView2.RowCount == 0; } } catch (Exception ex) { ShowError(ex); } } /// /// 自定义显示文本 /// /// /// private void gridView1_CustomColumnDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e) { try { if (e.Column.Caption == "匹配模式") { var value = e.Value.ToString().ToLower(); if (value == "0") e.DisplayText = "完全匹配"; else if (value == "1") e.DisplayText = "模糊匹配"; } else if (e.Column.Caption == "通知管理员") { var value = e.Value.ToString().ToLower(); if (value == "1") e.DisplayText = "√"; else if (value == "0") e.DisplayText = "×"; } else if (e.Column.FieldName == "antistop" || e.Column.FieldName == "content") e.DisplayText = GlobalObject.unescape(e.Value.ToString()); var temp = _SetDisplayText(e.Column.Caption, e.Value.ToString().ToLower()); if (!string.IsNullOrEmpty(temp)) e.DisplayText = temp; } catch (Exception ex) { ShowError(ex); } } private string _SetDisplayText(string caption, string value) { try { if (caption == "QQ" || caption == "微信公众号" || caption == "微信") { var strs = value.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).ToList(); var enumkey = (int)((ChatType)Enum.Parse(typeof(ChatType), caption)); return strs.Contains(enumkey.ToString()) ? "√" : "×"; } return string.Empty; } catch (Exception ex) { ShowError(ex); return string.Empty; } } private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { try { Class1.Config.Is_Top_User = buttonCheck1.Checked; if (bck_acquiescent_Auto_Answer_onoff.Checked) Class1.Config.Is_Auto_Answer = !string.IsNullOrWhiteSpace(memoEdit1.Text.Replace("-----------分割线-----------", "")); else Class1.Config.Is_Auto_Answer = false; Class1.Config.DefaultContents = memoEdit1.Text.Split(new string[] { @" -----------分割线----------- " }, StringSplitOptions.RemoveEmptyEntries).ToList(); Class1.Config.TuLing_prefix = tbx_TuLing_prefix.Text; Class1.Config.TuLing_apikey = tbx_TuLing_apikey.Text; if (bck_TuLing_onoff.Checked && !string.IsNullOrWhiteSpace(tbx_TuLing_apikey.Text)) { string htmlResult = Tools.GetHtml("测试", "123123", tbx_TuLing_apikey.Text); Class1.Config.TuLing_OnOff = !Regex.IsMatch(htmlResult, @".?intent.?:{.?code.?:(5000|6000|4000|4001|4002|4003|4004|4005|4007|4100|4200|4300|4400|4500|4600|4602|7002|8008)}"); } else Class1.Config.TuLing_OnOff = false; Util.Save(Class1.Config); Tools.FindUnprocesseds(true); } catch (Exception ex) { ShowError(ex); } } /// /// 显示菜单 /// /// /// private void gridView1_MouseUp(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right) popupMenu1.ShowPopup(Control.MousePosition); } private void hyperlinkLabelControl2_Click(object sender, EventArgs e) { memoEdit1.Text = memoEdit1.Text.Insert(memoEdit1.SelectionStart, @" -----------分割线----------- "); memoEdit1.SelectionStart = memoEdit1.SelectionStart; } private void simpleButton2_Click(object sender, EventArgs e) { this.pageControl2.GotoPage(); label5.Visible = gridView2.RowCount == 0; } private void hyperlinkLabelControl3_Click(object sender, EventArgs e) { var clearForm = new ClearForm(); clearForm.ShowDialog(); this.pageControl2.GotoPage(); label5.Visible = gridView2.RowCount == 0; } private void gridView2_CustomColumnDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e) { try { if (e.Column.FieldName == "chatType") e.DisplayText = e.Value.ToString(); else if (e.Column.FieldName == "username" || e.Column.FieldName == "content") e.DisplayText = GlobalObject.unescape(e.Value.ToString()); } catch (Exception) { e.DisplayText = "其他"; } } private void bck_acquiescent_Auto_Answer_onoff_Click(object sender, EventArgs e) { hyperlinkLabelControl7.Enabled = hyperlinkLabelControl6.Enabled = hyperlinkLabelControl5.Enabled = hyperlinkLabelControl4.Enabled = hyperlinkLabelControl2.Enabled = memoEdit1.Enabled = bck_acquiescent_Auto_Answer_onoff.Checked; } private void hyperlinkLabelControl6_Click(object sender, EventArgs e) { try { OpenFileDialog dlg = new OpenFileDialog(); dlg.Multiselect = true;//等于true表示可以选择多个文件 dlg.DefaultExt = ".jpg"; dlg.Filter = "图片|*.jpg;*.png;*.gif;*.jpeg;*.bmp"; if (dlg.ShowDialog() == DialogResult.OK) { StringBuilder strb = new StringBuilder(); foreach (string file in dlg.FileNames) { strb.AppendLine($"[图片={file}]"); } memoEdit1.Text = memoEdit1.Text.Insert(memoEdit1.SelectionStart, strb.ToString().Trim()); memoEdit1.SelectionStart = memoEdit1.SelectionStart; } } catch (Exception ex) { ShowError(ex); } } private void hyperlinkLabelControl7_Click(object sender, EventArgs e) { try { var label = sender as HyperlinkLabelControl; var flag = label.Text.Substring(label.Text.Length - 3, 2); CommonForm commonForm = new CommonForm(flag); if (commonForm.ShowDialog() == DialogResult.OK) { if (!string.IsNullOrWhiteSpace(commonForm.Strs)) { var strs = commonForm.Strs.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries).ToList(); if (flag == "图片") strs = strs.Select(f => $"[图片={f}]").ToList(); else if (flag == "视频") strs = strs.Select(f => $"[视频={f}]").ToList(); else if (flag == "语音") strs = strs.Select(f => $"[语音={f}]").ToList(); memoEdit1.Text = memoEdit1.Text.Insert(memoEdit1.SelectionStart, string.Join("\r\n", strs).Trim()); memoEdit1.SelectionStart = memoEdit1.SelectionStart; } } } catch (Exception ex) { ShowError(ex); } } private void gridView3_CellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e) { try { if (e.Column.Caption == "填写转发到的账号") { //var value = e.Value?.ToString(); //if (!string.IsNullOrWhiteSpace(value) && value.Length == 9) //{ var selectRow = gridView3.GetSelectedRows()[0]; var id = this.gridView3.GetRowCellValue(selectRow, "ID").ToString();//获取ID列的数据 var messtype = this.gridView3.GetRowCellValue(selectRow, "messtype").ToString();//获取ID列的数据 var session = ApiClient.GetSession(); var result = session.FindSingle("select * from fl_plugin_autoanswer_unprocessed where rid = @id", new { id = id }); if (result == null) result = new fl_plugin_autoanswer_unprocessed() { rid = int.Parse(id) }; result.username = e.Value?.ToString(); result.messtype = messtype; session.Saveable(result).ExecuteCommand(); //ShowSuccess("成功"); //Refresh(); //} } } catch (Exception ex) { ShowError(ex); } } private void RepositoryItemComboBox1_SelectedValueChanged(object sender, EventArgs e) { try { var i = ((ComboBoxEdit)sender); var text = i.SelectedItem.ToString(); //获取gridview选中的行 //GridView myView = (gridControl3.MainView as GridView); //int dataIndex = myView.GetDataSourceRowIndex(myView.FocusedRowHandle); var selectRow = gridView3.GetSelectedRows()[0]; var id = this.gridView3.GetRowCellValue(selectRow, "ID").ToString();//获取ID列的数据 var username = this.gridView3.GetRowCellValue(selectRow, "username").ToString();//获取ID列的数据 var session = ApiClient.GetSession(); var result = session.FindSingle("select * from fl_plugin_autoanswer_unprocessed where rid = @id", new { id = id }); if (result == null) result = new fl_plugin_autoanswer_unprocessed() { rid = int.Parse(id) }; result.username = username; result.messtype = text; session.Saveable(result).ExecuteCommand(); } catch (Exception ex) { } } } }