using EyeSoft.Extensions;
using OASystem.Domain.Dtos.QiYeWeChat;
using OASystem.Domain.ViewModels.QiYeWeChat;
using System.Diagnostics;
using System.Text.Json;
namespace OASystem.API.OAMethodLib.QiYeWeChatAPI
{
///
/// 聚合Api 服务
///
public class QiYeWeChatApiService : IQiYeWeChatApiService
{
private readonly HttpClient _httpClient;
private readonly string CorpId = "wwe978bef5495a0728"; //企业Id
private readonly string PersonnelAssistant_AgentId = "3010011"; //人事助手Id
private readonly string PersonnelAssistant_Corpsecret = "ig--IJd6TxWDMJ1wT4e-RDRcRX12v5GjB359DNATwJ4"; //人事助手凭证密钥
private readonly string PunchCard_AgentId = "3010185"; //打卡Id
private readonly string PunchCard_Corpsecret = "Xhrl37GOqlAjsu0VzUSJECaJdjzkDXQLbvrzRsZQb8M"; //打卡凭证密钥
private readonly string Email_AgentId = "1000004"; //E-Mail Id
private readonly string Email_Corpsecret = "NA1zbJM15GmgjPYwDOqz59dIo1Wnug-MbU107MeUemc"; //E-Mail 凭证密钥
private readonly string AddressBook_Corpsecret = "Y1tnjh7j-BvbqAytAoXZPUbmDR6dqLTL6mXtc6PZ7fo"; //通讯录同步 凭证密钥
private readonly string Approve_AgentId = "3010040"; //审批 Id
private readonly string Approve_Corpsecret = "k_Jo69Jw9Hqg_in-Rypbs30PNbxOYa1t4e-dxYuT-kw"; //审批 凭证密钥
private readonly string GroupStatus_AgentId = "1000008"; //OA通知 Id
private readonly string GroupStatus_Corpsecret = "7J_ST3jTPzbZpFwl7ttToTVufjEx6O2wuApvKHxt2Ak"; //OA通知Secret
private readonly DateTime _1970 = new DateTime(1970, 1, 1, 0, 0, 0, 0);
private readonly JobPostRepository _jobPostRep;
///
/// 初始化
///
///
///
public QiYeWeChatApiService(IHttpClientFactory clientFactory, JobPostRepository jobPostRep)
{
_httpClient = clientFactory.CreateClient("PublicQiYeWeChatApi"); ;
_jobPostRep = jobPostRep;
}
///
/// 获取access_token
///
///
/// 1:人事助手
/// 2:打卡
/// 3:邮件
/// 4:通讯录同步
/// 5:审批
/// 6:团组状态通知
///
///
private async Task GetTokenAsync(int applicationType)
{
Access_TokenView tokenResult = new Access_TokenView();
Access_Token_Request access_Token = new Access_Token_Request();
string cacheName = string.Empty;
if (applicationType == 1)
{
access_Token.corpsecret = PersonnelAssistant_Corpsecret; //人事助手
cacheName = "PersonnelAssistant_Access_Token";
}
else if (applicationType == 2)
{
access_Token.corpsecret = PunchCard_Corpsecret; //打卡
cacheName = "PunchCard_Access_Token";
}
else if (applicationType == 3)
{
access_Token.corpsecret = Email_Corpsecret; //E-Mail
cacheName = "Enail_Access_Token";
}
else if (applicationType == 4) //通讯录同步
{
access_Token.corpsecret = AddressBook_Corpsecret;
cacheName = "AddressBook_Access_Token";
}
else if (applicationType == 5) //审批
{
access_Token.corpsecret = Approve_Corpsecret;
cacheName = "Approve_Access_Token";
}
else if (applicationType == 6) //团组状态通知
{
access_Token.corpsecret = GroupStatus_Corpsecret;
cacheName = "GroupStatus_Access_Token";
}
else
{
tokenResult.errmsg = "未识别应用类型Id!";
return tokenResult;
}
string access_token = await RedisRepository.RedisFactory
.CreateRedisRepository()
.StringGetAsync(cacheName);//string 取
if (string.IsNullOrEmpty(access_token))
{
string access_token_url = string.Format(@"/cgi-bin/gettoken?corpid={0}&corpsecret={1}", access_Token.corpid, access_Token.corpsecret);
var access_tokenReq = await _httpClient.GetAsync(access_token_url);
if (access_tokenReq.IsSuccessStatusCode)
{
var stringResponse = await access_tokenReq.Content.ReadAsStringAsync();
tokenResult = System.Text.Json.JsonSerializer.Deserialize(stringResponse,
new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
if (tokenResult.errcode == 0)
{
TimeSpan ts = DateTime.Now.AddMinutes(118) - DateTime.Now; //设置redis 过期时间 118分钟
await RedisRepository
.RedisFactory
.CreateRedisRepository()
.StringSetAsync(cacheName, tokenResult.access_token, ts);//string 存
}
}
else
{
tokenResult.errmsg = "企业微信Token未获取到!";
}
}
else
{
tokenResult.errcode = 0;
tokenResult.access_token = access_token;
}
return tokenResult;
}
#region 添加员工
///
/// 获取成员ID列表
///
///
public async Task GetUserIdListAsync()
{
UserIdListView userIdListView = new UserIdListView();
Access_TokenView access_Token = await GetTokenAsync(4);
if (access_Token.errcode != 0)
{
userIdListView.errcode = access_Token.errcode;
userIdListView.errmsg = access_Token.errmsg;
return userIdListView;
}
string url = string.Format("/cgi-bin/user/list_id?access_token={0}&debug=1", access_Token.access_token);
var jsonData = new
{
access_token = access_Token.access_token, //调用接口凭证
};
var json = System.Text.Json.JsonSerializer.Serialize(jsonData);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var create_Req = await _httpClient.PostAsync(url, content);
var stringResponse = await create_Req.Content.ReadAsStringAsync();
userIdListView = System.Text.Json.JsonSerializer.Deserialize(stringResponse,
new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
return userIdListView;
}
///
/// 获取成员信息
///
///
public async Task GetUserInfosAsync()
{
QYWX_UserInfosView infoViews = new QYWX_UserInfosView();
//获取员工useridList
UserIdListView useridView = await GetUserIdListAsync();
if (useridView.errcode != 0)
{
infoViews.errcode = useridView.errcode;
infoViews.errmsg = useridView.errmsg;
return infoViews;
}
Access_TokenView access_Token = await GetTokenAsync(4);
if (access_Token.errcode != 0)
{
infoViews.errcode = access_Token.errcode;
infoViews.errmsg = access_Token.errmsg;
return infoViews;
}
List items = new List();
string urlTitle = string.Format("/cgi-bin/user/get?access_token={0}", access_Token.access_token);
foreach (var item in useridView.dept_user)
{
if (!string.IsNullOrEmpty(item.userid))
{
QYWX_UserInfoView _UserInfoView = new QYWX_UserInfoView();
string url = string.Format("{0}&userid={1}", urlTitle, item.userid);
var create_Req = await _httpClient.GetAsync(url);
if (create_Req.IsSuccessStatusCode)
{
var stringResponse = await create_Req.Content.ReadAsStringAsync();
_UserInfoView = System.Text.Json.JsonSerializer.Deserialize(stringResponse,
new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
if (_UserInfoView.errcode == 0)
{
items.Add(new QYWX_UserInfo()
{
userid = _UserInfoView.QYWX_User.userid,
name = _UserInfoView.QYWX_User.name,
mobile = _UserInfoView.QYWX_User.mobile,
position = _UserInfoView.QYWX_User.position,
email = _UserInfoView.QYWX_User.email,
biz_mail = _UserInfoView.QYWX_User.biz_mail,
});
}
}
}
}
infoViews.errcode = 0;
infoViews.errmsg = "操作成功!";
infoViews.QYWX_Users = items;
return infoViews;
}
///
/// 获取部门列表
///
///
///
private async Task GetDepartmentAsync(string access_token)
{
DepartmentListView result = new DepartmentListView();
string dep_url = string.Format("/cgi-bin/department/list?access_token={0}&debug=1", access_token);
var depReq = await _httpClient.GetAsync(dep_url);
if (depReq.IsSuccessStatusCode)
{
var stringResponse = await depReq.Content.ReadAsStringAsync();
result = System.Text.Json.JsonSerializer.Deserialize(stringResponse,
new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
}
else
{
result.errcode = -1;
result.errmsg = "企业微信部门列表未获取到!";
}
return result;
}
///
/// 创建员工
///
///
///
public async Task CreateAsync(Create_Request create_Request)
{
ResponseBase responseBase = new ResponseBase();
#region 职位
string depName = string.Empty,
jobName = string.Empty;
List jobs = await _jobPostRep.QueryJobPost(string.Empty);
Sys_JobPostI jobPost = jobs.Where(it => it.IsDel == 0 && it.Id == Convert.ToInt32(create_Request.position)).FirstOrDefault();
if (jobPost != null)
{
depName = jobPost.DepName;
jobName = jobPost.JobName;
}
create_Request.position = jobName;
if (string.IsNullOrEmpty(create_Request.biz_mail))
{
create_Request.biz_mail = string.Format("{0}@pan-american-intl.com", create_Request.userid);
}
#endregion
Access_TokenView access_Token = new Access_TokenView();
access_Token = await GetTokenAsync(4);
if (access_Token.errcode == 0)
{
create_Request.access_token = access_Token.access_token;
#region 处理部门
Access_TokenView dep_Access_Token = await GetTokenAsync(1);
if (dep_Access_Token.errcode != 0)
{
responseBase.errcode = dep_Access_Token.errcode;
responseBase.errmsg = dep_Access_Token.errmsg;
}
DepartmentListView depData = await GetDepartmentAsync(dep_Access_Token.access_token);
if (depData.errcode == 0)
{
var depData1 = depData.department.Where(x => x.name == depName).FirstOrDefault();
if (depData1 != null)
{
create_Request.department = new List { depData1.id };
}
else
{
responseBase.errcode = -1;
responseBase.errmsg = "未在企业微信上找到OA内设置的部门";
return responseBase;
}
}
else
{
responseBase.errcode = depData.errcode;
responseBase.errmsg = depData.errmsg;
return responseBase;
}
#endregion
create_Request.access_token = access_Token.access_token;
string create_url = string.Format("/cgi-bin/user/create?access_token={0}", create_Request.access_token);
var json = System.Text.Json.JsonSerializer.Serialize(create_Request);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var create_Req = await _httpClient.PostAsync(create_url, content);
var stringResponse = await create_Req.Content.ReadAsStringAsync();
responseBase = System.Text.Json.JsonSerializer.Deserialize(stringResponse,
new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
}
else
{
responseBase.errcode = access_Token.errcode;
responseBase.errmsg = access_Token.errmsg;
}
return responseBase;
}
#endregion
#region 打卡
///
/// 获取企业所有打卡规则
///
///
public async Task GetCheckIn_CorpCheckInOptionAsync()
{
CorpCheckInRuleView corpCheckInRuleView = new CorpCheckInRuleView();
//获取打卡数据 token
Access_TokenView access_Token = await GetTokenAsync(2);
if (access_Token.errcode != 0)
{
corpCheckInRuleView.errcode = access_Token.errcode;
corpCheckInRuleView.errmsg = string.Format("【企业微信】【获取月打卡数据】【Token】【Msg】{0}", access_Token.errmsg);
return corpCheckInRuleView;
}
string url = string.Format("/cgi-bin/checkin/getcorpcheckinoption?access_token={0}", access_Token.access_token);
var content = new StringContent(string.Empty, Encoding.UTF8, "application/json");
var create_Req = await _httpClient.PostAsync(url, content);
var stringResponse = await create_Req.Content.ReadAsStringAsync();
corpCheckInRuleView = System.Text.Json.JsonSerializer.Deserialize(stringResponse,
new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
return corpCheckInRuleView;
}
///
/// 获取月打卡记录数据
///
///
///
///
public async Task GetCheckin_MonthDataAsync1(DateTime startDt, DateTime endDt)
{
CheckInView checkInView = new CheckInView();
//获取员工Id
UserIdListView userIdListView = await GetUserIdListAsync();
if (userIdListView.errcode != 0)
{
checkInView.errcode = userIdListView.errcode;
checkInView.errmsg = string.Format("【企业微信】【获取员工IdList】【Msg】{0}", userIdListView.errmsg);
return checkInView;
}
if (userIdListView.dept_user == null || userIdListView.dept_user.Count <= 0)
{
checkInView.errmsg = string.Format("【企业微信】【获取员工IdList】【Msg】未查出员工Id");
return checkInView;
}
//获取打卡数据 token
Access_TokenView access_Token = await GetTokenAsync(2);
if (access_Token.errcode != 0)
{
checkInView.errcode = access_Token.errcode;
checkInView.errmsg = string.Format("【企业微信】【获取月打卡数据】【Token】【Msg】{0}", access_Token.errmsg);
return checkInView;
}
string url = string.Format("/cgi-bin/checkin/getcheckin_monthdata?access_token={0}", access_Token.access_token);
Checkin_MonthData_Request checkInReq = new Checkin_MonthData_Request();
checkInReq.access_token = access_Token.access_token;
checkInReq.starttime = (uint)(startDt - _1970).TotalSeconds;
checkInReq.endtime = (uint)(endDt - _1970).TotalSeconds;
checkInReq.useridlist = userIdListView.dept_user.Select(it => it.userid).ToList();
var json = System.Text.Json.JsonSerializer.Serialize(checkInReq);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var create_Req = await _httpClient.PostAsync(url, content);
var stringResponse = await create_Req.Content.ReadAsStringAsync();
checkInView = System.Text.Json.JsonSerializer.Deserialize(stringResponse,
new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
return checkInView;
}
///
/// 获取月打卡记录数据
///
///
///
///
public async Task GetCheckin_MonthDataAsync(DateTime startDt, DateTime endDt)
{
CheckInView checkInView = new CheckInView();
//获取员工Id
UserIdListView userIdListView = await GetUserIdListAsync();
if (userIdListView.errcode != 0)
{
checkInView.errcode = userIdListView.errcode;
checkInView.errmsg = string.Format("【企业微信】【获取员工IdList】【Msg】{0}", userIdListView.errmsg);
return checkInView;
}
if (userIdListView.dept_user == null || userIdListView.dept_user.Count <= 0)
{
checkInView.errmsg = string.Format("【企业微信】【获取员工IdList】【Msg】未查出员工Id");
return checkInView;
}
//获取打卡数据 token
Access_TokenView access_Token = await GetTokenAsync(2);
if (access_Token.errcode != 0)
{
checkInView.errcode = access_Token.errcode;
checkInView.errmsg = string.Format("【企业微信】【获取月打卡数据】【Token】【Msg】{0}", access_Token.errmsg);
return checkInView;
}
#region 处理超31天的月报表数据
string url = string.Format("/cgi-bin/checkin/getcheckin_monthdata?access_token={0}", access_Token.access_token);
Checkin_MonthData_Request checkInReq = new Checkin_MonthData_Request();
checkInReq.access_token = access_Token.access_token;
checkInReq.useridlist = userIdListView.dept_user.Select(it => it.userid).ToList();
uint starttimeOne, endtimeOne, starttimeTwo, endtimeTwo;
int days = (int)(endDt - startDt).TotalDays;
if (days > 32)
{
starttimeOne = (uint)((startDt.ToUniversalTime().Ticks - 621355968000000000) / 10000000);
endtimeOne = (uint)((startDt.AddDays(31).ToUniversalTime().Ticks - 621355968000000000) / 10000000);
starttimeTwo = (uint)((startDt.AddDays(32).ToUniversalTime().Ticks - 621355968000000000) / 10000000);
endtimeTwo = (uint)((endDt.ToUniversalTime().Ticks - 621355968000000000) / 10000000);
checkInReq.starttime = starttimeOne;
checkInReq.endtime = endtimeOne;
CheckInView checkInViewOne = new CheckInView();
var jsonOne = System.Text.Json.JsonSerializer.Serialize(checkInReq);
var contentOne = new StringContent(jsonOne, Encoding.UTF8, "application/json");
var create_ReqOne = await _httpClient.PostAsync(url, contentOne);
var stringResponseOne = await create_ReqOne.Content.ReadAsStringAsync();
checkInViewOne = System.Text.Json.JsonSerializer.Deserialize(stringResponseOne,
new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
if (checkInViewOne.errcode != 0)
{
return checkInViewOne;
}
checkInReq.starttime = starttimeTwo;
checkInReq.endtime = endtimeTwo;
CheckInView checkInViewTwo = new CheckInView();
var jsonTwo = System.Text.Json.JsonSerializer.Serialize(checkInReq);
var contentTwo = new StringContent(jsonTwo, Encoding.UTF8, "application/json");
var create_ReqTwo = await _httpClient.PostAsync(url, contentTwo);
var stringResponseTwo = await create_ReqTwo.Content.ReadAsStringAsync();
checkInViewTwo = System.Text.Json.JsonSerializer.Deserialize(stringResponseTwo,
new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
if (checkInViewTwo.errcode != 0)
{
return checkInViewTwo;
}
#region 整合月报表数据
foreach (var item_one in checkInViewOne.datas)
{
foreach (var item_two in checkInViewTwo.datas)
{
if (item_one.base_info.acctid.Equals(item_two.base_info.acctid))
{
#region summary_info 汇总信息整合
item_one.summary_info.work_days += item_two.summary_info.work_days; //应打卡天数
item_one.summary_info.regular_days += item_two.summary_info.regular_days; //正常天数
item_one.summary_info.except_days += item_two.summary_info.except_days; //异常天数
item_one.summary_info.regular_work_sec += item_two.summary_info.regular_work_sec; //实际工作时长,为统计周期每日实际工作时长之和
item_one.summary_info.standard_work_sec += item_two.summary_info.standard_work_sec; //标准工作时长,为统计周期每日标准工作时长之和
#endregion
#region exception_infos 异常状态统计信息 整合
item_one.exception_infos.AddRange(item_two.exception_infos);
#endregion
#region sp_items 假勤统计信息整合
item_one.sp_items.AddRange(item_two.sp_items);
#endregion
#region overwork_info 加班情况 整合
item_one.overwork_info.workday_over_sec += item_two.overwork_info.workday_over_sec; //工作日加班时长
item_one.overwork_info.holidays_over_sec += item_two.overwork_info.holidays_over_sec; //节假日加班时长
item_one.overwork_info.restdays_over_sec += item_two.overwork_info.restdays_over_sec; //休息日加班时长
#endregion
break;
}
}
}
#endregion
checkInView = checkInViewOne;
}
else
{
checkInReq.starttime = (uint)((startDt.ToUniversalTime().Ticks - 621355968000000000) / 10000000);
checkInReq.endtime = (uint)((endDt.ToUniversalTime().Ticks - 621355968000000000) / 10000000);
var json = System.Text.Json.JsonSerializer.Serialize(checkInReq);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var create_Req = await _httpClient.PostAsync(url, content);
var stringResponse = await create_Req.Content.ReadAsStringAsync();
checkInView = System.Text.Json.JsonSerializer.Deserialize(stringResponse,
new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
}
#endregion
return checkInView;
}
///
/// 获取月打卡数据(redis缓存)
///
///
///
///
public async Task GetCheckin_MonthDataRedisAsync(DateTime startDt, DateTime endDt)
{
CheckInView checkInView = new CheckInView();
string checkInDatastring = await RedisRepository.RedisFactory
.CreateRedisRepository()
.StringGetAsync("Checkin_MonthData");//List 取
if (!string.IsNullOrEmpty(checkInDatastring))
{
checkInView = JsonConvert.DeserializeObject(checkInDatastring);
return checkInView;
}
//获取员工Id
UserIdListView userIdListView = await GetUserIdListAsync();
if (userIdListView.errcode != 0)
{
checkInView.errcode = userIdListView.errcode;
checkInView.errmsg = string.Format("【企业微信】【获取员工IdList】【Msg】{0}", userIdListView.errmsg);
return checkInView;
}
if (userIdListView.dept_user == null || userIdListView.dept_user.Count <= 0)
{
checkInView.errmsg = string.Format("【企业微信】【获取员工IdList】【Msg】未查出员工Id");
return checkInView;
}
//获取月打卡数据 token
Access_TokenView access_Token = await GetTokenAsync(2);
if (access_Token.errcode != 0)
{
checkInView.errcode = access_Token.errcode;
checkInView.errmsg = string.Format("【企业微信】【获取月打卡数据】【Token】【Msg】{0}", access_Token.errmsg);
return checkInView;
}
string url = string.Format("/cgi-bin/checkin/getcheckin_monthdata?access_token={0}", access_Token.access_token);
Checkin_MonthData_Request checkInReq = new Checkin_MonthData_Request();
checkInReq.access_token = access_Token.access_token;
checkInReq.starttime = (uint)(startDt - _1970).TotalSeconds;
checkInReq.endtime = (uint)(endDt - _1970).TotalSeconds;
checkInReq.useridlist = userIdListView.dept_user.Select(it => it.userid).ToList();
var json = System.Text.Json.JsonSerializer.Serialize(checkInReq);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var create_Req = await _httpClient.PostAsync(url, content);
var stringResponse = await create_Req.Content.ReadAsStringAsync();
checkInView = System.Text.Json.JsonSerializer.Deserialize(stringResponse,
new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
if (checkInView.errcode == 0)
{
TimeSpan ts = DateTime.Now.AddMinutes(60) - DateTime.Now; //设置redis 过期时间 60分钟
await RedisRepository
.RedisFactory
.CreateRedisRepository()
.StringSetAsync("Checkin_MonthData", JsonConvert.SerializeObject(checkInView), ts);//List 存
}
return checkInView;
}
public async Task