SysCompanyService.cs 13 KB
using Hh.Mes.Common.config;
using Hh.Mes.Common.log;
using Hh.Mes.Pojo.System;
using Hh.Mes.POJO.Entity;
using Hh.Mes.POJO.Response;
using Hh.Mes.Service.Repository;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using Hh.Mes.Common;
using System.Linq;

namespace Hh.Mes.Service.Configure
{
    /// <summary>
    /// 公司设置
    /// </summary>
    public class SysCompanyService : RepositorySqlSugar<base_company>
    {
        /// <summary>
        /// 新增  
        /// </summary>
        /// <returns></returns>
        public dynamic Ins(base_company model)
        {
            var response = new Response();
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                if (Context.Queryable<base_company>().Where(x => x.isDelete == SystemVariable.AddOrUpdateFlag).Count() > 0)
                {
                    response.Status = false;
                    response.Message = "新增失败:公司默认只有一条,请不要重复添加!";
                    return response;
                }
                model.createBy = sysWebUser.Name;
                model.createTime = DateTime.Now;
                model.isDelete = SystemVariable.AddOrUpdateFlag;
                if (!Add(model))
                {
                    response.Status = false;
                    response.Message = SystemVariable.dataActionError;
                }
                return response;
            });
        }


        /// <summary>
        /// 根据主键数组 删除
        /// </summary>
        public dynamic DeleteByIds(int[] ids)
        {
            var response = new Response();
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                if (GetSysCompanyOne() != null)
                {
                    response.Status = false;
                    response.Message = "删除失败:公司默认需要有一条数据";
                    return response;
                }

                if (Context.Deleteable<base_company>().In(ids).ExecuteCommand() == 0)
                {
                    response.Status = false;
                    response.Message = SystemVariable.dataActionError;
                }
                return response;
            });
        }

        /// <summary>
        /// 更新
        /// </summary>
        public dynamic UpdataById(base_company model)
        {
            var response = new Response();
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                model.updateBy = sysWebUser.Name;
                model.updateTime = DateTime.Now;
                if (!Update(model))
                {
                    response.Status = false;
                    response.Message = SystemVariable.dataActionError;
                }
                return response;
            });
        }

        /// <summary>
        /// 返回公司表第一条数据
        /// </summary>
        /// <returns></returns>
        public base_company GetSysCompanyOne()
        {
            return Context.Queryable<base_company>().Take(1).First(x => x.isDelete == SystemVariable.AddOrUpdateFlag);
        }

        public List<sys_File> GetSysFile(int id)
        {
            var sql = string.Format("select * from sys_file where targetId={0}", id);

            var files = Context.Ado.SqlQuery<sys_File>(sql);
            return files;
        }



        /// <summary>
        ///  获取字典 select * from[dbo].[sys_dict_data] where dictType = 'url'
        /// </summary>
        /// <param name="dictLabel">值</param>
        /// <param name="dictType">类型</param>
        /// <returns>返回dictValue 字段值</returns>
        public override string GetDictionaryDictValue(string dictLabel, string dictType = "GetUrl")
        {
            return Context.Queryable<sys_dict_data>().With(SqlWith.NoLock).Where(x => x.dictType == dictType && x.dictLabel == dictLabel).First()?.dictValue;
        }

        public dynamic Upload(IFormFileCollection file, IHostingEnvironment environment, sys_File model)
        {
            var response = new Response();
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                List<sys_File> sysFiles = new List<sys_File>
                {
                    model
                };
                var result = UploadFile(file, environment, sysFiles);
                if (!result)
                {
                    response.Status = false;
                    response.Message = SystemVariable.dataActionError;
                }
                return response;
            });
        }


        /// <summary>
        /// 未完成工单信息
        /// </summary>
        /// <returns></returns>
        public dynamic UnfinishedOrderInfo()
        {
            var response = new Response();
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                response.Status = false;
                double Percentage = Convert.ToDouble(AppSettings.GetAppSeting("UnfinishedOrderPercentage").Substring(0, AppSettings.GetAppSeting("UnfinishedOrderPercentage").IndexOf("%")));
                //#region 今日任务
                //var TodayUnfinishedOrderList = Context.Queryable<weld_detail_work_order>().Where(x => x.State < (int)EnumWelDetailStatus.释放完成 && SqlFunc.DateIsSame(x.createTime, DateTime.Now)).ToList();
                //var TodayOrderList = Context.Queryable<weld_detail_work_order>().Where(x => SqlFunc.DateIsSame(x.createTime, DateTime.Now)).ToList();

                //response.Message = $"今日任务未完成数:<span>【{TodayUnfinishedOrderList.Count}】</span>,今日任务数:<span>【{TodayOrderList.Count}】</span>,</br></br>";
                //if (TodayOrderList.Count != 0 && TodayUnfinishedOrderList.Count != 0)
                //    response.Message += $"今日任务未完成百分比:<span>【{((double)TodayUnfinishedOrderList.Count / (double)TodayOrderList.Count).ToString("0.0%")}】</span>。</br></br>";
                //else
                //    response.Message += $"今日任务未完成百分比:<span>【0.0%】</span>。</br></br>";
                //if (((double)TodayUnfinishedOrderList.Count / (double)TodayOrderList.Count) * 100 > Percentage)
                //{
                //    response.Status = true;
                //}
                //#endregion

                //#region 目前总任务
                //var AllUnfinishedOrderList = Context.Queryable<weld_detail_work_order>().Where(x => x.State < (int)EnumWelDetailStatus.释放完成 && x.createTime < Convert.ToDateTime(DateTime.Now.AddDays(1).ToString("yyyy-MM-dd"))).ToList();
                //var AllOrderList = Context.Queryable<weld_detail_work_order>().Where(x => x.createTime < Convert.ToDateTime(DateTime.Now.AddDays(1).ToString("yyyy-MM-dd"))).ToList();

                //response.Message += $"目前总任务未完成数:<span>【{AllUnfinishedOrderList.Count}】</span>,目前总任务数:<span>【{AllOrderList.Count}】</span>,</br></br>";

                //if (AllUnfinishedOrderList.Count != 0 && AllOrderList.Count != 0)
                //    response.Message += $"目前总任务未完成百分比:<span>【{((double)AllUnfinishedOrderList.Count / (double)AllOrderList.Count).ToString("0.0%")}】</span>。</br></br>";
                //else
                //    response.Message += $"目前总任务未完成百分比:<span>【0.0%】</span>。</br></br>";
                //if (((double)AllUnfinishedOrderList.Count / (double)AllOrderList.Count) * 100 > Percentage)
                //{
                //    response.Status = true;
                //}
                //#endregion

                return response;
            });
        }

        /// <summary>
        /// 主页面错误信息提示
        /// </summary>
        public dynamic LogTips()
        {
            var response = new Response();
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                #region cpu,硬盘,内存
                var tempServerLog = string.Empty;//"cpu 使用率:80%,内存使用率:80%,C盘使用率:80%,"
                var cpu = ComputerHelp.GetCpuUsage();
                if (int.TryParse(cpu.Replace("%", ""), out int cpuUsage) && cpuUsage >= 80)
                {
                    tempServerLog += $"cpu 使用率:{cpu};";
                }
                var memory = ComputerHelp.GetMemery();
                if (int.TryParse(memory.Item4.Replace("%", ""), out int memoryUsage) && memoryUsage >= 80)
                {
                    tempServerLog += $"内存 使用率:{memory.Item4};";
                }
                var disk = ComputerHelp.GetDriveInfos();
                var driveInfos = disk.Where(x => ((x.TotalSize - x.TotalFreeSpace) * 100 / x.TotalSize) >= 80).Select(x => new
                {
                    dirName = x.Name,
                    usage = ((x.TotalSize - x.TotalFreeSpace) * 100 / x.TotalSize).ToString("N1") + "%"
                }).ToList();
                foreach (var item in driveInfos)
                {
                    tempServerLog += $"{item.dirName}盘使用率:{item.usage};";
                }
                #endregion

                //接口日志
                var log = @" select count(1) as total from sys_interface_log t (nolock) 
                             where t.flag is null 
                             and t.response NOT LIKE '%200%'
                             --and t.createTime>=convert(varchar(15),getdate(),111)
                             --and t.createTime<convert(varchar(15),DATEADD(day,1,getdate()),111)
                             --and (t.method='POST' or t.method='post') 
                             --and (t.response like '%500%' or t.response like '%由于连接%' )

                             select count(1) as total from sys_job_log t (nolock) 
                             where t.flag is null 
                             --and t.createTime>=convert(varchar(15),getdate(),111)
                             --and t.createTime<convert(varchar(15),DATEADD(day,1,getdate()),111)

                              select count(1) as total from sys_interface_log t (nolock) 
                             where t.flag is null and [system] ='app Android'
                             and t.response NOT LIKE '%200%'

                              select count(1) as total from sys_interface_log t (nolock) 
                             where t.flag is null and [system] ='api' and [type]  like 'API%'
                             and t.response NOT LIKE '%200%'";

                var ds = Context.Ado.GetDataSetAll(log);
                var interLog = ds.Tables[0].Rows[0]["total"].ToString();
                if (interLog == "0") interLog = "";
                var jobLog = ds.Tables[1].Rows[0]["total"].ToString();
                if (jobLog == "0") jobLog = "";
                var pdaLog = ds.Tables[2].Rows[0]["total"].ToString();
                if (pdaLog == "0") pdaLog = "";
                var upstreamLog = ds.Tables[3].Rows[0]["total"].ToString();
                if (upstreamLog == "0") upstreamLog = "";
                response.Result = new
                {
                    interLog,

                    jobLog,

                    pdaLog,

                    upstreamLog,

                    serverLog = string.IsNullOrWhiteSpace(tempServerLog) ? "" : tempServerLog
                };
                return response;
            });
        }

        public dynamic UpdateLogTips(string flag)
        {
            var response = new Response();
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                if (flag == "inter")
                {
                    string sql = "update sys_interface_log set flag=1 where flag is null";
                    var result = base.Context.Ado.ExecuteCommand(sql);
                    return result > 0 ? response.ResponseSuccess() : response.ResponseError();
                }
                else if (flag == "job")
                {
                    string sql = "update sys_job_log set flag=1 where flag is null";
                    var result = base.Context.Ado.ExecuteCommand(sql);
                    return result > 0 ? response.ResponseSuccess() : response.ResponseError();
                }
                else if (flag == "upstream")
                {
                    string sql = "update sys_interface_log set flag=1 where flag is null and [system] ='api' and [type]  like 'API%'";
                    var result = base.Context.Ado.ExecuteCommand(sql);
                    return result > 0 ? response.ResponseSuccess() : response.ResponseError();
                }
                else if (flag == "pda")
                {
                    string sql = "update sys_interface_log set flag=1 where flag is null and [system] ='app Android'";
                    var result = base.Context.Ado.ExecuteCommand(sql);
                    return result > 0 ? response.ResponseSuccess() : response.ResponseError();
                }
                return response;
            });
        }

    }
}