using AlibabaCloud.SDK.Dingtalkh5package_1_0.Models;
using AlibabaCloud.SDK.Dingtalkvillage_1_0.Models;
using DSWeb.Areas.CommMng.DAL;
using DSWeb.Areas.Dispatch.Helper;
using DSWeb.Areas.MvcShipping.DB;
using DSWeb.Areas.MvcShipping.Job;
using DSWeb.Areas.MvcShipping.Models.MsOpSeaeBaoXian;
using DSWeb.Common.DB;
using HcUtility.Comm;
using java.rmi.server;
using java.util;
using log4net;
using Microsoft.Office.Interop.Excel;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Runtime.Caching;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Web;
using Tea;
using static DSWeb.Areas.CommMng.Controllers.WorkFlowController;
using static DSWeb.Areas.MvcShipping.Helper.DingTalk_SendAuditWork;
namespace DSWeb.Areas.MvcShipping.Helper
{
public static class DingTalkHelper
{
public static readonly string DingTalkAccessTokenStoreKey = "DingTalkToken";
private static ILog logger = LogManager.GetLogger("DingTalkHelper");
///
/// 发送工作通知
/// https://open-dev.dingtalk.com/apiExplorer#/?devType=org&api=dingtalk.oapi.message.corpconversation.asyncsend_v2
///
///
///
///
///
public static bool SendMessage(string uid, string msg)
{
DingTalkContext dingTalkContext = new DingTalkContext();
var pAgentid = dingTalkContext.ParamSets.FirstOrDefault(p => p.PARAMNAME == "DingTalkAgentid");
if (pAgentid == null || string.IsNullOrWhiteSpace(pAgentid.PARAMVALUE))
{
throw new Exception("钉钉Agentid参数配置错误");
}
var user = dingTalkContext.Users.FirstOrDefault(u => u.GID == uid);
if (user != null && !string.IsNullOrWhiteSpace(user.DingTalkAccount))
{
var token = MemoryCache.Default[DingTalkTokenJob.DingTalkAccessTokenStoreKey].ToString();
var json = new
{
agent_id = pAgentid.PARAMVALUE,
userid_list = user.DingTalkAccount,
msg = new
{
msgtype = "text",
text = new
{
content = msg
}
}
};
string resp = WebRequestHelper.DoPost($"https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token={token}", JsonConvert.SerializeObject(json));
logger.Debug(resp);
var jsonObj = JsonConvert.DeserializeAnonymousType(resp, new
{
errcode = 0,
errmsg = "",
task_id = ""
});
if (jsonObj.errcode == 0)
{
return true;
}
}
return false;
}
///
/// 读取实例当前值 data内容是json文本
///
///
///
public static DBResult DingTalk_Instanceinfo(string instanceId) {
//https://open.dingtalk.com/document/isvapp-server/queries-a-process-instance-based-on-its-id
var result = new DBResult();
DingTalk_Instanceinfo dh = new DingTalk_Instanceinfo();
dh.MakeSendMessage(instanceId);//i0P82FAHT_G9TWJmavxGdg03131673000830
result = dh.DoSend();
return result;
}
//public static DBResult DingTalk_ReadWMSINInstance(string instanceId)
//{
// var result = new DBResult();
// var instanceiddic = BasicDataRefDAL.GetLogicInfo(wmsno, "钉钉审批");
// if (instanceiddic == null || !instanceiddic.ContainsKey("instanceId"))
// {
// return result.SetErrorInfo(wmsno + "没有进行钉钉审批");
// }
// else
// {
// }
// var _r = DingTalk_Instanceinfo(instanceId);
// if (!_r.Success)
// {
// return _r;
// }
// 如果成功 用数据对象解析结果 并做相应处理
//}
public static DBResult Send_WMSIN(string uid, string wmsno)
{
var result = new DBResult();
DingTalk_SendAuditWork dh = new DingTalk_SendAuditWork(uid);
if (dh.cansend(wmsno))
{
result= dh.MakeSendMessage(wmsno);
if (!result.Success) {
return result;
}
result = dh.DoSend();
}
else {
result.SetErrorInfo("该业务已发送");
}
return result;
}
}
public class DingTalkSendHelper {
public DingTalkSendHelper() { }
public string url { get; set; }
public string uid { get; set; }
public object SendObject { get; set; }
public SysParamSet pAgentid { get; set; }
public DB.User user { get; set; } = null;
public object jsonObj { get; set; }
public Dictionary dicObj { get; set; } = new Dictionary();
public string json { get; set; }
public string token { get; set; }
public Dictionary HeaderDic { get; set; }
private static ILog logger = LogManager.GetLogger("DingTalkHelper");
public DingTalkContext dingTalkContext { get; set; } = new DingTalkContext();
DBResult result { get; set; } = new DBResult();
public DBResult getUser()
{
user = dingTalkContext.Users.FirstOrDefault(u => u.GID == uid);
if (user == null || string.IsNullOrWhiteSpace(user.DingTalkAccount))
{
result.SetErrorInfo("用户没有维护钉钉userid");
return result;
}
result.OK();
return result;
}
public DBResult GetAgentid() {
result = new DBResult();
pAgentid = dingTalkContext.ParamSets.FirstOrDefault(p => p.PARAMNAME == "DingTalkAgentid");
if (pAgentid == null || string.IsNullOrWhiteSpace(pAgentid.PARAMVALUE))
{
result.SetErrorInfo("钉钉Agentid参数配置错误");
return result;
}
result.OK();
return result;
}
public DBResult DoSend() {
var result = new DBResult();
string resp = WebRequestHelper.DoPost(url, JsonConvert.SerializeObject(jsonObj));
logger.Debug(resp);
result.setMessage(true,"发送成功", jsonObj);
return result;
}
public DBResult DoSend_Header()
{
var result = new DBResult();
string resp = "";
if (jsonObj != null)
{
resp=WebRequestHelper.DoPost_Header(url, HeaderDic, jsonObj);
}
else {
resp=WebRequestHelper.DoPost_Header(url, HeaderDic);
}
logger.Debug(resp);
result.setMessage(true, "发送成功", resp);
return result;
}
public DBResult DoGet_Header_Param()
{
var result = new DBResult();
string resp = WebRequestHelper.DoGet_Header_Param(url, HeaderDic, dicObj);
//logger.Debug(resp);
result.setMessage(true, "发送成功", resp);
return result;
}
public static object JsonToObject(string jsonString, object obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
MemoryStream mStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
return serializer.ReadObject(mStream);
}
}
public class DingTalk_SendWorkMessage : DingTalkSendHelper {
public DingTalk_SendWorkMessage(string uid) {
this.uid = uid;
}
public DBResult MakeSendMessage(string msg) {
var result = new DBResult();
result = GetAgentid();
if (!result.Success) return result;
result = getUser();
if (!result.Success) return result;
jsonObj = new
{
agent_id = pAgentid.PARAMVALUE,
userid_list = user.DingTalkAccount,
msg = new
{
msgtype = "text",
text = new
{
content = msg
}
}
};
token = MemoryCache.Default[DingTalkTokenJob.DingTalkAccessTokenStoreKey].ToString();
url = $"https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token={token}";
result.OK();
return result;
}
}
public class DingTalk_SendAuditWork : DingTalkSendHelper
{
public string BSNO { get; set; }
public DingTalk_SendAuditWork(string uid)
{
this.uid = uid;
getUser();
}
public class DingTalkFormField {
public string name { get; set; }
public string value { get; set; }
public DingTalkFormField(string name, string value)
{
this.name = name;
this.value = value;
}
}
public class DingTalkForm_approvers
{
public string actionType { get; set; }
public List userIds { get; set; }
public DingTalkForm_approvers(string actionType, List userIds)
{
this.actionType = actionType;
this.userIds = userIds;
}
}
public class DingTalk_OAAuditBody {
public long deptId { get; set; }
public List approvers { get; set; } = new List();
public long microappAgentId { get; set; }
public string originatorUserId { get; set; }
public string processCode { get; set; }
public List formComponentValues { get; set; } = new List();
}
public bool cansend(string GID) {
//看是否已发过
var logiclog = BasicDataRefDAL.GetLogicInfo(GID, "钉钉审批");
if (logiclog.Count > 0)
{
return false;
}
return true;
}
public DBResult MakeSendMessage(string wmsno)
{
var result = new DBResult();
wmsno = wmsno.Replace("'", "");
try
{
if (string.IsNullOrWhiteSpace(user.DingTalkAccount))
{
return result.SetErrorInfo("请配置用户的钉钉id");
}
BSNO = wmsno;
DingTalk_OAAuditBody body = new DingTalk_OAAuditBody();
var dp = DingTalkProcess.GetDingTalkProcess("诚锐入货通知");
body.deptId = dp.deptid;//
//获取用户的钉钉id
var dtc = new DingTalkContext();
body.approvers.Add(new DingTalkForm_approvers("OR", new List { user.DingTalkAccount }));
body.microappAgentId = dp.agentid;//
body.originatorUserId = user.DingTalkAccount;
body.processCode = dp.processCode;
var cdc = new CommonDataContext();
var wms = cdc.wms.First(p => p.WMSNO == wmsno);
var wmsinList = cdc.wms_in.Where(x => x.ASSOCIATEDNO == wms.GID).ToList();
var 入库信息list = new List>();
var 车队信息list = new List>();
var 车队idlist = wmsinList.Select(s => s.CHEDUIID).ToList();
var 车队list = cdc.info_client.Where(x => 车队idlist.Contains(x.GID)).ToList();
foreach (var item in wmsinList)
{
var newrk = new List
{
new DingTalkFormField("提单号", item.BLNO),
new DingTalkFormField("箱号", item.CNTRNO),
new DingTalkFormField("品名", item.GOODSNAME),
new DingTalkFormField("重量", item.GOODSRKSL.ToString()),
new DingTalkFormField("件数", item.GOODSPACK.ToString()),
new DingTalkFormField("尺码", item.CHIMA1.ToString()),
new DingTalkFormField("库位", item.CHIMA1.ToString())
};
入库信息list.Add(newrk);
if (车队list != null && 车队list.Exists(x => x.GID == item.CHEDUIID))
{
var 车队 = 车队list.First(x => x.GID == item.CHEDUIID);
var newcl = new List{
new DingTalkFormField("车队", 车队.SHORTNAME),
new DingTalkFormField("车牌号", item.TRUCKNO)
};
车队信息list.Add(newcl);
}
}
var 入库信息 = new DingTalkFormField("入库信息", JsonConvert.SerializeObject(入库信息list));
var 车队信息 = new DingTalkFormField("车队信息", JsonConvert.SerializeObject(车队信息list));
body.formComponentValues = new List
{
//new DingTalkFormField("提单号", "123123")
//增加字段内容
new DingTalkFormField("客户名称", wms.CUSTOMERNAME),
new DingTalkFormField("入库日期", ((DateTime)wms.WMSDATE).ToString("yyyy-MM-dd")),
入库信息,
车队信息
};
jsonObj = body;
token = MemoryCache.Default[DingTalkTokenJob.DingTalkAccessTokenStoreKey].ToString();
url = $"https://api.dingtalk.com/v1.0/workflow/processInstances";
HeaderDic = new Dictionary
{
{ "x-acs-dingtalk-access-token", token }
};
result.OK();
return result;
}
catch (Exception e) {
return result.SetErrorInfo(e.Message );
}
}
public class DingTalk_SendAuditResult {
public string instanceId { get; set; }
}
public DBResult DoSend() {
var result = base.DoSend_Header();
if (result.Success) {
try
{
var jo = new DingTalk_SendAuditResult();
jo = (DingTalk_SendAuditResult)JsonToObject(result.Data.ToString(), jo);
var dic = new Dictionary();
dic.Add("instanceId", jo.instanceId);
BasicDataRefDAL.SaveLogicInfo(BSNO, "钉钉审批", dic);
}catch(Exception ex)
{
}
}
return result;
}
}
public class DingTalk_Instanceinfo : DingTalkSendHelper {
public string instanceId { get; set; }
public DingTalk_Instanceinfo()
{
//this.uid = uid;
}
public DBResult MakeSendMessage(string instanceId )
{
this.instanceId = instanceId;
var result = new DBResult();
jsonObj = null;
token = MemoryCache.Default[DingTalkTokenJob.DingTalkAccessTokenStoreKey].ToString();
url = $"https://api.dingtalk.com/v1.0/workflow/processInstances" ;
dicObj= new Dictionary {
{"processInstanceId",instanceId }
};
HeaderDic = new Dictionary
{
{ "x-acs-dingtalk-access-token", token }
};
result.OK();
return result;
}
public DBResult DoSend()
{
var result = base.DoGet_Header_Param();
if (result.Success)
{
try
{
BasicDataRefDAL.SaveLog(result.Data.ToString(), uid, "读取业务信息","返回");
//jo = (DingTalk_Instanceinfo)JsonToObject(result.Data.ToString(), jo);
}
catch (Exception ex)
{
}
}
return result;
}
}
#region 处理钉钉回调返回值
public class DingTalkCallbackDealHelper
{
public string processInstanceId { get; set; }
public string processCode { get; set; }
public string type { get; set; }
public DingTalkCallbackDealHelper() { }
public DingTalkCallbackDealHelper(string instanceId) {
processInstanceId = instanceId;
}
public DingTalkCallbackDealHelper(CallBackInfo callbackinfo)
{
processInstanceId = callbackinfo.processInstanceId;
processCode = callbackinfo.processCode;
type = callbackinfo.type;
}
}
public class OperationRecords
{
///
///
///
public string date { get; set; }
///
///
///
public string result { get; set; }
///
///
///
public string type { get; set; }
///
///
///
public string userId { get; set; }
}
public class FormComponentValues
{
///
///
///
public string componentType { get; set; }
///
/// 客户名称
///
public string name { get; set; }
///
///
///
public string bizAlias { get; set; }
///
///
///
public string id { get; set; }
///
/// 众盈
///
public string value { get; set; }
public 行信息 GetRowValues() {
//用value值文本来解析成 行信息
var result = new 行信息();
if (value.Contains("\\\"rowValue\\\""))
{
try
{
var _value = value.Replace("\\", "");
var hxx = JsonConvert.DeserializeObject<行信息>(_value);
result = hxx;
}
catch (Exception ex)
{ }
}
return result;
}
}
public class Tasks
{
///
///
///
public string result { get; set; }
///
///
///
public string activityId { get; set; }
///
///
///
public string pcUrl { get; set; }
///
///
///
public string createTime { get; set; }
///
///
///
public string mobileUrl { get; set; }
///
///
///
public string userId { get; set; }
///
///
///
public int taskId { get; set; }
///
///
///
public string status { get; set; }
}
public class Result
{
///
///
///
public List attachedProcessInstanceIds { get; set; }
///
///
///
public string businessId { get; set; }
///
/// 邓羽提交的入库统计
///
public string title { get; set; }
///
///
///
public string originatorDeptId { get; set; }
///
///
///
public List operationRecords { get; set; }
///
///
///
public List formComponentValues { get; set; }
///
///
///
public string result { get; set; }
///
///
///
public string bizAction { get; set; }
///
///
///
public string createTime { get; set; }
///
///
///
public string originatorUserId { get; set; }
///
///
///
public List tasks { get; set; }
///
/// 青岛诚锐众盈货运代理有限公司
///
public string originatorDeptName { get; set; }
///
///
///
public string status { get; set; }
}
public class DingTalkInstanceinfo
{
///
///
///
public Result result { get; set; }
///
///
///
public bool success { get; set; }
}
public class 行信息
{
public List rowValue { get; set; }
public string rowNumber { get; set; }
public string getValue(string fieldname) {
var result = "";
if (rowValue.Exists(x => x.label == fieldname)) {
result = rowValue.First(x => x.label == fieldname).value;
}
return result;
}
}
public class rowValue
{
public string bizAlias { get; set; }
public string label { get; set; }
public string value { get; set; }
public string key { get; set; }
}
#endregion
#region 钉钉业务类
public class DingTalkProcess {
public string processname { get; set; }
public string processCode { get; set; }
public string token { get; set; }
public string aes_key { get; set; }
public string appkey { get; set; }
public long agentid { get; set; }
public long deptid { get; set; }
//public string callbackstr { get; set; }
public DingTalkCallbackDealHelper callbackinfo { get; set; }
public void SaveCallBack(CallBackInfo _callbackinfo) {
callbackinfo = new DingTalkCallbackDealHelper(_callbackinfo);
}
public DingTalkProcess() { }
public DingTalkProcess(string processname) { this.processname = processname; }
///
/// 这些数值来自于钉钉中某个组织的某个应用。一个应用可以监听多个实际业务的返回值
///
///
///
public static DingTalkProcess GetDingTalkProcess(string processname) {
var result = new DingTalkProcess();
if (processname == "测试入货通知") {
result = new DingTalkProcess_测试入货通知(processname);
return result;
}
if (processname == "诚锐入货通知")
{
result = new DingTalkProcess_诚锐入库(processname);
return result;
}
return result;
}
public virtual DBResult DoDeal() { return new DBResult(); }
}
public class DingTalkProcess_测试入货通知 : DingTalkProcess
{
public DingTalkProcess_测试入货通知(string processname)
{
this.processname = processname;
processCode = "PROC-0DC40EA2-E9D2-4917-A597-AD77EC055C49";
token = "zbGFOwrH6zCvq3VE3izLmWRTNUC1YcX";
aes_key = "sb6GkCKsUwNQo3RKbX1MzHKea1ZsE221n3xQ9hwJBMK";
appkey = "dingsaofiohmsrcbxyef";
agentid = 2298782307;
agentid = 809181118;
}
public override DBResult DoDeal() {
var result = new DBResult();
//根据processinstancid 读取审批实例信息
var 返回结果Str = DingTalkHelper.DingTalk_Instanceinfo(callbackinfo.processInstanceId);
//解析返回结果
return result;
}
}
public class DingTalkProcess_诚锐入库 : DingTalkProcess
{
public DingTalkProcess_诚锐入库(string processname) {
this.processname = processname;
processCode = "PROC-0888A19C-0562-42AC-A9C6-24E4C4398410";
token = "CWhvNvfyuNf9D8halMs5PyHV70CrFx3E";
aes_key = "O5u6L8YnUaucnC8FyFNMeMeGE5uoYSAGFGdg3rOHftt";
appkey = "dingkt5caipnn4fbuqsf";
agentid = 2365401074;
deptid = 432400353;
}
public override DBResult DoDeal()
{
return new DBResult();
}
}
#endregion
}