using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using Common.Model; using CoreEntity.DAL; using CoreEntity.Entity; using CoreEntity.ESEntity; using JCSoft.WX.Framework.Api; using MemberWeb.Commonss; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Caching.Memory; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using PublicLibrary.Model; using SupplierWeb.Commonss; using ZcPeng.PublicLibrary; namespace SupplierWeb.Controllers { [Route("web/ES_UsageMem")] public class ES_UsageMemberController : BaseController { public ES_UsageMemberController(IMemoryCache cache, IApiClient client) : base(cache, client) { } public IActionResult Index() { return View(); } /// /// 用户用药列表 /// /// /// /// [HttpPost] [Route("usedrug")] public ActionResult usedrug(QueryFilter[] filters, Int32 pageIndex, Int32 pageSize,string [] tagArr, string sortField, Int32 sortDirection, string[] sumFields, [FromBody]dynamic data) { int OutDays = 5; if (data != null) { filters = data.filters.ToObject(); pageIndex = data.pageIndex; pageSize = data.pageSize; sortField = data.sortField; sortDirection = data.sortDirection; sumFields = data.sumFields.ToObject(); } #region 获取列表 DataTable dt = new DataTable(); string result; List parameters = new List(); string source = "";//平台 string tagstr = "";//标签 string commandText=""; string chaheKey = "";//查询的缓存key long totalcount = 0; Random rand = new Random(); if (filters != null && filters.Length > 0) { //if (filters != null && filters.Length > 0 && filters[0].field.Equals("tagKey")) { string keyTag = null; foreach (var filter in filters) { if (filter.field == "OutDays" && filter.value != null && filter.value != "") { OutDays = Convert.ToInt32(filter.value.ToString()); } if (filter.field == "tagKey" && filter.value != null && filter.value != "") { keyTag = filter.value; } } if (keyTag!=null) { var keyArr = keyTag.Split("_");//0标签1平台2终端 if (keyArr.Length > 0) { chaheKey = keyTag; var key0 = keyArr[0].Split(","); if (!key0[0].Equals("0")&& key0[0].Length>0) { //获取标签会员号码 List _sourceTag = TagIDList(keyArr[0]); /* string result3; //创建临时表 foreach (mem_MemberTag memtag in _sourceTag) { commandText = commandText + "'"+ ES_DataStaisController.getPhoneEncDesrypt(memtag.MemberPhone)+"',"; } if (commandText != ""&& commandText.Length>0) { tagstr = " and s.AConsigneePhone2 IN("+ commandText.Substring(0,commandText.Length-1) + ") "; }*/ foreach (string memtag in key0) { commandText = commandText + "'" + memtag + "',"; } if (commandText != "" && commandText.Length > 0) { tagstr = " AND t.tagId IN(" + commandText.Substring(0, commandText.Length - 1) + ") "; } } if (keyArr.Length > 1 && keyArr[1] != null) { var key1 = keyArr[1].Split(","); if (!key1[0].Equals("0")) { source = source + " AND s.ConsigneeType IN("+ keyArr[1] + ") "; } } if (keyArr.Length > 2 && keyArr[2]!=null) { var key2 = keyArr[2].Split(","); if (!key2[0].Equals("0")) { source = source + " AND s.OriginType IN(" + keyArr[2]+ ") "; } } } } } string direct = " asc "; if (sortDirection != 1) { direct = " desc "; } string orderStr = " MinDates asc,DomeCount desc "; if (sortField.Equals("MemPhone")||sortField.Equals("UseCount")||sortField.Equals("DomeCount")||sortField.Equals("EndTime")) { orderStr = sortField + direct; } int start = (pageIndex - 1) * pageSize; int end = (start + 1 + pageSize); //有选择标签,ES查询标签会员 if (tagArr!=null&& tagArr.Length>0) { } string staTime1 = DateTime.Now.AddDays(-60).ToString("yyyy-MM-dd HH:mm:ss"); totalcount = rand.Next(9000, 10000); //获取会员订,有使用量,未被忽略商品 IList permss = new List(0); IList permssa = RedisUtil.getRedisUtils("0_"+start + "_" + end + chaheKey + orderStr);//获取缓存数据 if (permssa != null && permssa.Count > 0) { foreach (Mem_UserDrugv2 mu in permssa) { Mem_UserDrug mug = new Mem_UserDrug(); mug.MemPhone= mu.MemPhone; mug.DomeCount=Convert.ToString(mu.DomeCount); mug.EndTime = DateTime.ParseExact(mu.EndTime.Replace("T"," "), "yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.CurrentCulture); ; mug.UseCount = mu.UseCount; permss.Add(mug); } } else {//缓存中没有数据 /* string commandText1s = "select (SELECT dbo.DesDecryptFixKey('123456','123456e10adc3949ba59abbe56e057f20f883e',A.AConsigneePhone2)) AS MemPhone,A.CreationDate, " + " sum(CASE WHEN((u.UsageDays*s.Amount) - DATEDIFF(day, s.CreationDate, CONVERT(varchar, GETDATE(), 23))) <= 5 THEN 1 ELSE 0 END) AS DomeCount " + " FROM mall..Orders A left join mall..OrderProducts s on s.OrdersCode = A.OrdersCode and s.CreationDate > '" + staTime1 + "' " + " and A.CreationDate > '" + staTime1 + "' LEFT JOIN mall..ProductUsage u ON u.ProductCode = s.ProductCode " + " and s.CreationDate > '" + staTime1 + "' AND u.UsageDays!='' " + tagstr + " LEFT JOIN MemberStopDrugMsg d ON d.MemPhone=A.AConsigneePhone2 AND d.ProductCode=u.ProductCode " + " where 1=1 " + " and A.AConsigneePhone2!='' and A.CreationDate>'" + staTime1 + "' and s.CreationDate>'" + staTime1 + "' and u.ID!='' and u.ID is not null " + source + " GROUP BY A.AConsigneePhone2 ,A.CreationDate,d.MemPhone "; commandText1s = commandText1s + " ORDER BY " + orderStr; string commandText2s = " OFFSET " + start + " ROWS FETCH NEXT 15 ROWS ONLY "; string commandText3s = commandText + commandText1s + commandText2s; bool success = DataAccess.GetValuesV2(commandText3s, ref dt, parameters.ToArray(), out result); */ string sql = " sum(CASE WHEN(minus(multiply(toInt8(u.UsageDays),toInt8(s.Amount)),minus(today(),toDate(s.OrderTime)))) <= "+ OutDays + " THEN 1 ELSE 0 END) as DomeCount," + "sum(CASE WHEN(minus(multiply(toInt8(u.UsageDays),toInt8(s.Amount)),minus(today(),toDate(s.OrderTime)))) >0 THEN 1 ELSE 0 END) as UseCount, " + "min(minus(multiply(toInt8(u.UsageDays),toInt8(s.Amount)),minus(today(),toDate(s.OrderTime)))) as MinDates," + "min(toDateTime(plus(multiply(toInt8(u.UsageDays),toInt8(s.Amount))*24*3600,toUnixTimestamp(s.OrderTime)))) as EndTime," + "toDate(plus(toUnixTimestamp(now()),MinDates*24*3600)) as EndDay," + "" + OutDays + " as OutDays," + "s.AConsigneePhone2 AS MemPhone "; string commandText1 = "SELECT " + sql+ " FROM `default`.OrdersAndOrderProducts s " + "global LEFT JOIN (select ProductCode,min(UsageDays)as UsageDays from ProductUsage group by ProductCode) u ON u.ProductCode = s.ProductCode " + "global LEFT JOIN (select MemberPhone,tagId,id,MAX(create_date) FROM memberTagV2 m " + "global LEFT JOIN (SELECT id,create_date FROM memberTagV2 WHERE tagId='0' GROUP BY id,MemberPhone,tagId,create_date)c ON c.id=m.MemberPhone " + "WHERE m.create_date>c.create_date GROUP BY m.id,m.MemberPhone,m.tagId) t ON t.MemberPhone=s.AConsigneePhone2 " + "where u.UsageDays != '' AND s.AConsigneePhone2 != '' " + " AND s.OrderTime > '"+ staTime1 + "' " + source+ tagstr; commandText1 = commandText1 + " GROUP BY MemPhone,s.OrderTime HAVING DomeCount>0 and MinDates>=1 " + " ORDER BY " + orderStr; string commandText2 = " LIMIT "+ start + ",20 "; string commandText3 = commandText1 + commandText2+ " FORMAT JSON "; var dugObj =ClickHouseUtil.HttpClickHouseGet(commandText3); var obj = (JObject)JsonConvert.DeserializeObject(dugObj); permss = JsonConvert.DeserializeObject>(JsonConvert.SerializeObject(obj.GetValue("data"))); #endregion if (dt != null) { // 把DataTable转换为IList //permss = ModelConvertHelper.ConvertToModel(dt); RedisUtil.addRedisUtils(permss, "0_" + start + "_" + end + chaheKey + orderStr);//保存 commandText1 = "SELECT count(1) cn FROM ("+ commandText1 + ")"; commandText1=ClickHouseUtil.HttpClickHouseGet(commandText1); totalcount = Convert.ToInt64(commandText1); } } string result1; IsoDateTimeConverter timejson = new IsoDateTimeConverter { DateTimeFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss" }; staTime1 = DateTime.Now.AddDays(-61).ToString("yyyy-MM-dd HH:mm:ss"); //计算会员用药数据 foreach (Mem_UserDrug m in permss) { DataTable dt1 = new DataTable(); if (m.MemPhone != null && m.MemPhone != "") { //m.MemPhone = ""; IList permss1 = new List(0); string sqlcount = "SELECT o.OrderStatus," + "p1.ProductCode,p1.ProductName,p1.Dosage,(select dbo.DesDecryptFixKey('123456','123456e10adc3949ba59abbe56e057f20f883e',o.AConsigneePhone2)) as AConsigneePhone2,o.Consignee,CONVERT(varchar(100), p.CreationDate, 23) AS CrDate,B.CreationDate AS GoDate,p1.packing,(ISNULL(u.UsageDays*p.Amount,0)) AS EndCount FROM Orders o " + " LEFT JOIN OrderProducts p ON o.OrdersCode= p.OrdersCode " + " LEFT JOIN Product p1 ON p1.ProductCode=p.ProductCode " + " LEFT JOIN ProductUsageData u ON u.ProductCode=p1.ProductCode " + " LEFT JOIN MemberStopDrugMsg B ON B.MemPhone=o.AConsigneePhone2 " + " WHERE NOT (o.AConsigneePhone2 IN(SELECT B.MemPhone FROM MemberStopDrugMsg B ) AND p1.ProductCode IN(SELECT B.ProductCode FROM MemberStopDrugMsg B )) AND o.CreationDate > '"+ staTime1 + "' " + " AND p1.ProductCode!='' AND o.AConsigneePhone2='" + m.MemPhone + "' " + " GROUP BY " + "o.OrderStatus," + "p1.ProductCode,o.Consignee,CONVERT(varchar(100), p.CreationDate, 23),B.CreationDate,p1.ProductName,p1.Dosage,p.Amount,u.UsageFrequencyCount,u.UsageDays,u.UsagePerUseCount,p1.packing,o.AConsigneePhone2 ORDER BY B.CreationDate "; DataAccess.GetValuesV2(sqlcount, ref dt1, parameters.ToArray(), out result); if (dt1 != null && dt1.Rows.Count > 0) { // 把DataTable转换为IList permss1 = ModelConvertHelper.ConvertToModel(dt1); m.UpTime = permss1[0].GoDate; m.MemName = permss1[0].Consignee; int totla1 = 0; int totla2 = 0; string MemPhone = ""; foreach (Mem_UserDrugGoods u in permss1) { if (u.EndCount!=null) { DateTime startTime = Convert.ToDateTime(u.CrDate);//购买时间 DateTime endTime = Convert.ToDateTime(DateTime.Now.ToLocalTime().ToString());//当前时间 TimeSpan ts = endTime - startTime;//使用天数 int? tocount = u.EndCount - ts.Days; if (tocount > 0) {//正在用药 totla1 = totla1 + 1; if (tocount <= 5) {//快用完数 totla2 = totla2 + 1; //m.EndTime = startTime.AddDays(Convert.ToDouble(u.EndCount)); } //if (m.EndTime!=null && (Convert.ToDateTime(m.EndTime)- endTime).Days>0 && (Convert.ToDateTime(m.EndTime) - endTime).Days <= 5) { } else //{ // m.EndTime = startTime.AddDays(Convert.ToDouble(u.EndCount)); //} } else { totla2 = totla2 + 1; //m.EndTime = u.CrDate; } if (tocount<0) { tocount = 0; } u.EndCount = tocount; } if (MemPhone=="" || MemPhone.Length<=0) { MemPhone = m.MemPhone; } m.MemPhone = u.AConsigneePhone2.Substring(0, 3) + "****" + u.AConsigneePhone2.Substring(u.AConsigneePhone2.Length - 4, 4); u.AConsigneePhone2 = MemPhone; } //m.UseCount = totla1; m.Mem_Goods = permss1; } } } var jsonData = JsonConvert.SerializeObject(permss, timejson); return Json(new { items = JsonConvert.DeserializeObject(jsonData), sum = new { }, totalCount = totalcount }); } /// /// 获取终端平台列表 /// /// /// /// [HttpPost] [Route("getTermain")] public ActionResult getTermain([FromBody]dynamic data, QueryFilter[] filters) { #region 获取列表 DataTable dt = new DataTable(); DataTable dt1 = new DataTable(); string result; IList permss = new List(0); IList permss1 = new List(0); List parameters = new List(); string filterstr = QueryFilter.getFilterSqlParam(filters, out parameters, new Mem_Terminaldoc(), "A."); //终端 string commandText3 = " SELECT d.Text AS TerminalDesc, d.Value AS ParentTerminalKey FROM Mall..DataDictory d WHERE d.ParentId IN (785,786) AND d.IsHide=0 "; bool success = DataAccess.GetValues(commandText3, ref dt, parameters.ToArray(), out result); #endregion if (dt != null && dt.Rows.Count > 0) { // 把DataTable转换为IList permss = ModelConvertHelper.ConvertToModel(dt); } IsoDateTimeConverter timejson = new IsoDateTimeConverter { DateTimeFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss" }; var jsonData = JsonConvert.SerializeObject(permss, timejson); //平台 commandText3 = " SELECT d.Text AS TerminalDesc, d.Value AS ParentTerminalKey FROM Mall..DataDictory d WHERE d.ParentId IN (783) AND d.IsHide=0 "; success = DataAccess.GetValues(commandText3, ref dt1, parameters.ToArray(), out result); if (dt1 != null && dt1.Rows.Count > 0) { // 把DataTable转换为IList permss1 = ModelConvertHelper.ConvertToModel(dt1); } var jsonData1 = JsonConvert.SerializeObject(permss1, timejson); return Json(new { items = JsonConvert.DeserializeObject(jsonData), items1 = JsonConvert.DeserializeObject(jsonData1), sum = new { } }); } [HttpPost] [Route("upDurGood")] public JsonResult upDurGood(String ProductCode, String MemPhone, [FromBody]dynamic data) { if (data != null) { ProductCode = data.ProductCode; MemPhone = data.MemPhone; } string date=DateTime.Now.ToString(); #region 添加 string commandText = "INSERT INTO MemberStopDrugMsg(ProductCode,MemPhone,CreationDate)VALUES (@ProductCode,@MemPhone,@CreationDate)"; string result; //准备参数 List> parameters = new List>(); parameters.Add(new List() { "ProductCode", ProductCode }); parameters.Add(new List() { "MemPhone", MemPhone }); parameters.Add(new List() { "CreationDate", date }); List parameters1 = DataAccess.ToParameters(parameters); int success = DataAccess.ExecuteCommandv2(commandText, parameters1, out result); #endregion return Json(new { success = success }); } public static List TagIDList(string tagId) { Object query = null; string MemPhone = ""; List _sourceTag = new List(); if (tagId != null && tagId.Length>0) { #region 会员tag query = new { query = "select MemberPhone from mem_membertag where TagId in(" + tagId + ")" }; //将参数转换成JSON数据 var jsonTag = JsonConvert.SerializeObject(query); //通过传来的SQL语句,转换成DSL语句 string sqlTag = Util.ElasticQuery("_xpack/sql/translate?format=json", "POST", jsonTag); //通过转换的DSL语句,获取数据 var strTag = Util.ElasticQuery("mem_membertag/_search?format=json", "POST", sqlTag); //JSON转Root对象 Root stobjTag = EsCommon.FromJSON>(strTag); //给_source额外的属性赋值 stobjTag.hits.hits.ForEach(x => { x._source._id = x._id; }); //将Root对象中的子对象取出来 _sourceTag = stobjTag.hits.hits.Select(x => x.entity()).ToList(); #endregion } return _sourceTag; } //获取用户分机号 [HttpGet, Route("getUsreTel")] public JsonResult getUsreTel(string accountId, string staffId) { string userid = getStaff(staffId, "userid"); //判断参数是否合法 if (string.IsNullOrEmpty(userid)) { return Json(new { timeout = 1, msg = "没有登陆" }); } var dt = new DataTable(); if (accountId != null) { var param = new List(); string sql = "SELECT top 1 UserTel FROM mem_Account_Tel WHERE IsDelete='1' AND UserId='" + accountId + "' "; DataAccess.GetValues(sql, ref dt, param.ToArray(), out var msg); } return Json(new { tel = dt }); } //保存用户分机号 [HttpPost, Route("addUsreTel")] public JsonResult addUsreTel(string content, string UserTel, string UserId, string staffId, string code, [FromBody]dynamic data) { string accountId = getStaff(staffId, "userid"); //判断参数是否合法 if (string.IsNullOrEmpty(accountId)) { return Json(new { timeout = false, msg = "没有登陆" }); } if (data != null) { UserTel = data.userTel; UserId = data.userId; code = data.code; content = data.content; } int success = 0; string msg = ""; if (code == "1") { //添加 var sql = "INSERT INTO mem_Account_Tel (AccountId,Content,UserTel,UserId,CreateDate)VALUES(@AccountId,@Content,@UserTel,@UserId,@CreateDate)"; var param = new List(); param.Add(new SqlParameter("AccountId", accountId)); param.Add(new SqlParameter("Content", content)); param.Add(new SqlParameter("UserTel", UserTel)); param.Add(new SqlParameter("UserId", UserId)); param.Add(new SqlParameter("CreateDate", DateTime.Now)); success = DataAccess.ExecuteCommand(sql, param, out msg); } else { string sql = "UPDATE mem_Account_Tel SET UserTel=@UserTel,Content=@Content WHERE UserId = @UserId"; //准备参数 List> parametersC = new List>(); parametersC.Add(new List() { "UserTel", UserTel }); parametersC.Add(new List() { "Content", content }); parametersC.Add(new List() { "UserId", UserId }); List parametersC1 = DataAccess.ToParameters(parametersC); success = DataAccess.ExecuteCommand(sql, parametersC1, out msg); } return Json(new { success = success, msg = msg }); } [HttpPost, Route("usreTel")] public JsonResult usreTel(string userPhone, string staffId, string accountTel, [FromBody]dynamic data) { string userid = getStaff(staffId, "userid"); string success = ""; //判断参数是否合法 if (string.IsNullOrEmpty(userid)) { return Json(new { msg = "没有登陆" }); } if (data != null) { string url = "http://119.130.113.244:8001/admin/?m=interface&c=api&a=dial&extension=ACCOUNTTEL&extensionDst=USERPHONE"; userPhone = data.userPhone; accountTel = data.accountTel; if (userPhone != null && accountTel != null) { //获取用户手机号 userPhone = ES_DataStaisController.getPhoneDesEncrypt(userPhone); if (userPhone != "" && userPhone.Length > 0) { string getUrl = "http://mobsec-dianhua.baidu.com/dianhua_api/open/location?tel=" + userPhone;//号码归属地,加拨0 string phoneStr = userTelDialPhone(getUrl); if (!phoneStr.Contains("广州")) { userPhone = "0" + userPhone; } url = url.Replace("ACCOUNTTEL", accountTel).Replace("USERPHONE", userPhone); //拨号 success = userTelDialPhone(url); } } } return Json(new { success = success }); } public string userTelDialPhone(string url) { WebRequest myWebRequest = WebRequest.Create(url); WebResponse myWebResponse = myWebRequest.GetResponse(); myWebRequest.Timeout = 60000; Stream ReceiveStream = myWebResponse.GetResponseStream(); string responseStr = ""; if (ReceiveStream != null) { StreamReader reader = new StreamReader(ReceiveStream, Encoding.UTF8); responseStr = reader.ReadToEnd(); reader.Close(); } myWebResponse.Close(); return responseStr; } } }