hao
2025-04-30 543a8e4f314534401d39d48b6778ec5f8b6956f4
StandardInterface/MES.Service/service/QcIssueResult/QcIssueResultManager.cs
@@ -19,6 +19,10 @@
using Newtonsoft.Json;
using Oracle.ManagedDataAccess.Client;
using System.Data;
using System.Reflection;
using System.Text;
using DingTalk.Api;
using System.Net.Http;
namespace MES.Service.service.QcIssueResult;
@@ -56,8 +60,8 @@
        AlibabaCloud.SDK.Dingtalkoauth2_1_0.Client client = CreateClient1();
        AlibabaCloud.SDK.Dingtalkoauth2_1_0.Models.GetAccessTokenRequest getAccessTokenRequest = new AlibabaCloud.SDK.Dingtalkoauth2_1_0.Models.GetAccessTokenRequest
        {
            AppKey = "dingyzos0r1bizj7g6lr",
            AppSecret = "-HP4RvK2OUbqhG3iBUpd_TPe5MZRj8cfLc0b8Skt8rhC3I38kVLY9SS8P3kLWFcH",
            AppKey = "ding8nmegrbi29a78ze0",
            AppSecret = "CwWeKXzItBJktsVhGoZi73Ts79bP8qp3FuLmS5PtJgNmMxrWFaqdQQTY0RqCRQSC",
        };
        try
@@ -124,6 +128,85 @@
        }
    }
    /**
    * 获取userid
    * @return string 返回启动结果
    */
   public  HttpClient _httpClient;
    public string DingTalkService()
    {
        _httpClient = new HttpClient();
        _httpClient.Timeout = TimeSpan.FromSeconds(30);
        return "1";
    }
    public async Task<string> GetUserId(string phone)
    {
        // 参数验证
        if (string.IsNullOrWhiteSpace(phone))
            throw new ArgumentException("手机号不能为空", nameof(phone));
        // 获取访问令牌
        string accessToken = GetToken();
        // 调用现有方法
        return await GetUserIdByMobile(accessToken, phone);
    }
    public async Task<string> GetUserIdByMobile(string accessToken, string mobile)
    {
        // 参数验证
        if (string.IsNullOrWhiteSpace(accessToken))
            throw new ArgumentException("Access token cannot be empty", nameof(accessToken));
        if (string.IsNullOrWhiteSpace(mobile) || !IsValidMobile(mobile))
            throw new ArgumentException("Invalid mobile number", nameof(mobile));
        try
        {
            // 构造请求URL
            var url = $"https://oapi.dingtalk.com/topapi/v2/user/getbymobile?access_token={accessToken}";
            string m = DingTalkService();
            // 构造请求体
            var requestBody = new { mobile };
            var jsonContent = JsonConvert.SerializeObject(requestBody);
            var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
            // 发送请求
            var response = await _httpClient.PostAsync(url, content);
            // 处理响应
            response.EnsureSuccessStatusCode();
            var responseBody = await response.Content.ReadAsStringAsync();
            var result = JsonConvert.DeserializeObject<DingTalkResponse>(responseBody);
            // 处理业务逻辑错误
            if (result?.Errcode != 0)
                throw new DingTalkApiException(result?.Errcode ?? -1, result?.Errmsg ?? "Unknown error");
            return result?.Result?.UserId ?? throw new InvalidOperationException("User ID not found in response");
        }
        catch (HttpRequestException ex)
        {
            throw new DingTalkApiException(500, $"HTTP request failed: {ex.Message}", ex);
        }
        catch (JsonException ex)
        {
            throw new DingTalkApiException(500, $"JSON parsing failed: {ex.Message}", ex);
        }
    }
    private bool IsValidMobile(string mobile)
    {
        // 简单的手机号格式验证
        return !string.IsNullOrEmpty(mobile) && mobile.Length == 11 && mobile.StartsWith("1");
    }
    /**
     * 启动钉钉工作流实例
@@ -132,19 +215,21 @@
    public string GetProcessNo(GetQcIssueResultDetail getQcIssueResultDetail)
    {
        var db = SqlSugarHelper.GetInstance();
        var mapping = db.Queryable<DingNameCode>()
            .Where(t => t.DingDingName == getQcIssueResultDetail.Fname)
        var stafflist = db.Queryable<DingNameCode>()
            .Where(t => t.STAFF_NO == getQcIssueResultDetail.Fname)
            .Select(t => new DingNameCode
            {
               DingDingCode=t.DingDingCode,
                STAFF_NAME = t.STAFF_NAME,
                PHONE_NUMBER = t.PHONE_NUMBER
            })
            .ToList();
        if (mapping.Any())
        {
            string UserId = mapping.FirstOrDefault().DingDingCode;
        if (stafflist.Any())
        {
            Task<string> task = GetUserId(stafflist[0].PHONE_NUMBER);
            string UserId = task.Result;
            // 使用 JSON 序列化输出对象的详细内容
            string getQcIssueResultDetailJson = JsonConvert.SerializeObject(getQcIssueResultDetail, Formatting.Indented);
@@ -199,7 +284,7 @@
            AlibabaCloud.SDK.Dingtalkworkflow_1_0.Models.StartProcessInstanceRequest.StartProcessInstanceRequestFormComponentValues formComponentValues8 = new AlibabaCloud.SDK.Dingtalkworkflow_1_0.Models.StartProcessInstanceRequest.StartProcessInstanceRequestFormComponentValues
            {
                Name = "SignatureField_SKF9Q82DZUO0",
                Value = getQcIssueResultDetail.Fname,
                Value = stafflist[0].STAFF_NAME,
            };
            AlibabaCloud.SDK.Dingtalkworkflow_1_0.Models.StartProcessInstanceRequest.StartProcessInstanceRequestFormComponentValues formComponentValues9 = new AlibabaCloud.SDK.Dingtalkworkflow_1_0.Models.StartProcessInstanceRequest.StartProcessInstanceRequestFormComponentValues
            {
@@ -307,8 +392,9 @@
                return $"Exception: {_err.Message}";
            }
        }
        else {
            return "您不是公司成员或还未被加入到数据库中或名字填写错误,总之未找到匹配的用户信息";
        else
        {
            return "查不到您的手机号";
        }
    }
@@ -514,3 +600,39 @@
   
}
// 响应模型
public class DingTalkResponse
{
    [JsonProperty("errcode")]
    public int Errcode { get; set; }
    [JsonProperty("errmsg")]
    public string Errmsg { get; set; }
    [JsonProperty("result")]
    public UserResult Result { get; set; }
}
public class UserResult
{
    [JsonProperty("userid")]
    public string UserId { get; set; }
}
// 自定义异常
public class DingTalkApiException : Exception
{
    public int ErrorCode { get; }
    public DingTalkApiException(int errorCode, string message) : base(message)
    {
        ErrorCode = errorCode;
    }
    public DingTalkApiException(int errorCode, string message, Exception innerException)
        : base(message, innerException)
    {
        ErrorCode = errorCode;
    }
}