BusEquipmentMaintainNoticeService.cs 14.1 KB
using Hh.Mes.Common.log;
using Hh.Mes.Common.Request;
using Hh.Mes.POJO.Entity;
using Hh.Mes.POJO.Response;
using Hh.Mes.Service.Repository;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Hh.Mes.Pojo.System;
using System.Text;
using Microsoft.AspNetCore.Http;
using Hh.Mes.POJO.EnumEntitys;
using Hh.Mes.Service.Base;
using Hh.Mes.Service.SystemAuth;

namespace Hh.Mes.Service.Equipment
{
    /// <summary>
    /// 设备保养提醒服务
    /// </summary>
    public class BusEquipmentMaintainNoticeService : RepositorySqlSugar<daq_equipment_alarm_record>
    {
        private readonly int days = 15;
        private readonly SysFileService _sysFileService;

        public BusEquipmentMaintainNoticeService(SysFileService sysFileService, IAuth auth) : base(auth)
        {
            _sysFileService = sysFileService;
        }

        public dynamic Load(PageReq pageReq, string projectCode, bus_equipment_maintain_record_top busEquipmentMaintainRecordTop)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var result = new Response();
                var project = Context.Queryable<base_project>().Where(x => x.projectCode == projectCode)
                                   .Select(x => new base_project
                                   {
                                       keys = x.keys,
                                       projectName = x.projectName
                                   }).First();
                if (project == null) return result.ResponseError($"项目根节点编号:“{projectCode}”不存在设备数据!");

                var query = Context.Queryable<bus_equipment_maintain_record_top>().Where(GetExpression(project.keys, busEquipmentMaintainRecordTop, days));
                //分页
                if (!busEquipmentMaintainRecordTop.Exel)
                {
                    var total = 0;
                    result.Result = query.Select(x => new
                    {
                        x.id,
                        x.keys,
                        x.projectKeys,
                        x.factoryCode,
                        project.projectName,

                        x.equipmentCode,
                        x.equipmentName,
                        count = SqlFunc.Subqueryable<bus_equipment_maintain_record_detail>().Where(s => s.topKeys == x.keys && s.equipmentCode == x.equipmentCode && s.status != (int)EnumMaintainStatus.Maintained && s.nextMaintainTime <= DateTime.Now.AddDays(days)).Count(),
                    }).OrderBy(x => x.count, OrderByType.Desc).OrderBy(x => x.equipmentCode).ToOffsetPage(pageReq.page, pageReq.limit, ref total);
                    result.Count = total;
                    return result;
                }

                var data = query.ToList();
                result.Result = data;
                result.Count = data.Count;
                return result;
            }, catchRetrunValue: "list");
        }

        public dynamic LoadDesc(PageReq pageReq, bus_equipment_maintain_record_head busEquipmentMaintainRecordHead)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var result = new Response();
                var query = Context.Queryable<bus_equipment_maintain_record_detail>().Where(GetDescExpression(busEquipmentMaintainRecordHead));
                if (!busEquipmentMaintainRecordHead.Exel)
                {
                    int total = 0;
                    var data = query.Select(x => new
                    {
                        x.id,
                        x.topKeys,
                        x.headKeys,
                        x.projectKeys,
                        x.equipmentCode,
                        equipmentName = SqlFunc.Subqueryable<base_equipment>().Where(s => s.equipmentCode == x.equipmentCode).Select(s => s.equipmentName),
                        x.equipmentTypeCode,
                        x.partCode,
                        x.partName,
                        x.lastMaintainTime,
                        x.nextMaintainTime,
                        status = SqlFunc.Subqueryable<bus_equipment_maintain_record_detail>().Where(s => s.topKeys == x.topKeys && s.partCode == x.partCode && s.status != (int)EnumMaintainStatus.Maintained).Select(s => s.status),
                    }).OrderBy(x => x.nextMaintainTime).ToOffsetPage(pageReq.page, pageReq.limit, ref total);

                    result.Result = data.Select(x => new
                    {
                        x.id,
                        x.topKeys,
                        x.headKeys,
                        x.projectKeys,
                        x.equipmentCode,
                        x.equipmentName,
                        x.equipmentTypeCode,
                        x.partCode,
                        x.partName,
                        x.lastMaintainTime,
                        x.nextMaintainTime,
                        url = string.Join(',', Context.Queryable<Sys_File>().Where(t => SqlFunc.Subqueryable<base_equipment_part>().Where(s => s.partCode == x.partCode && s.id == t.targetId).Any() && t.targetTableName == nameof(base_equipment_part)).Select(t => t.url).ToList()),
                        x.status,
                    }).ToList();
                    result.Count = total;
                }
                else
                {
                    result.Result = query.ToList();
                    result.Count = result.Result.Count;
                }
                return result;
            }, catchRetrunValue: "list");
        }

        /// <summary>
        /// /左侧列表 设备类型+设备
        /// </summary>
        public dynamic GetTreeList()
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var stringBuilder = new StringBuilder();
                string equipmentTypeCodes = string.Join("', '", SystemVariable.IotNotContainDevice);
                string user = sysWebUser.Account;

                var nodes = new List<dynamic>();

                var rootNode = new
                {
                    id = Guid.NewGuid(),
                    name = "根节点",
                    keys = "r-1",
                    parentId = "0",
                    isok = false,
                    projectKeys = Guid.Empty,
                };

                var data = Context.Queryable<base_project>().Where(GetTreeExpression(user)).Select(x => new
                {
                    id = x.keys,
                    name = x.projectName,
                    keys = x.projectCode,
                    parentId = rootNode.keys,
                    isok = true,
                    projectKeys = x.keys
                }).ToList();

                nodes.Add(rootNode);
                nodes.AddRange(data);
                return nodes;
            });
        }

        private Expression<Func<base_project, bool>> GetTreeExpression(string user)
        {
            var exp = Expressionable.Create<base_project>();
            //非管理员,查询登陆用户绑定客户管理的项目
            if (user != SystemVariable.DefaultCreated)
            {
                var projectRoleKeys = GetProjectRoleKeys(user);
                exp.And(x => SqlFunc.Subqueryable<sys_role_projects_rel>().Where(c => projectRoleKeys.Contains(c.project_roles_key) && c.project_key == x.keys).Any());
            }
            return exp.ToExpression();//拼接表达式
        }

        private Expression<Func<bus_equipment_maintain_record_top, bool>> GetExpression(Guid projectKey, bus_equipment_maintain_record_top busEquipmentMaintainRecordTop, int days)
        {
            var exp = Expressionable.Create<bus_equipment_maintain_record_top>();
            exp.And(x => x.projectKeys == projectKey);
            exp.And(x => SqlFunc.Subqueryable<bus_equipment_maintain_record_detail>().Where(s => s.topKeys == x.keys && s.equipmentCode == x.equipmentCode && s.status != (int)EnumMaintainStatus.Maintained && s.nextMaintainTime <= DateTime.Now.AddDays(days)).Count() > 0);

            if (!string.IsNullOrWhiteSpace(busEquipmentMaintainRecordTop.equipmentCode))
            {
                exp.And(x => x.equipmentCode.Contains(busEquipmentMaintainRecordTop.equipmentCode));
            }

            if (!string.IsNullOrWhiteSpace(busEquipmentMaintainRecordTop.equipmentName))
            {
                exp.And(x => x.equipmentName.Contains(busEquipmentMaintainRecordTop.equipmentName));
            }

            return exp.ToExpression();
        }

        private Expression<Func<bus_equipment_maintain_record_detail, bool>> GetDescExpression(bus_equipment_maintain_record_head busEquipmentMaintainRecordHead)
        {
            var exp = Expressionable.Create<bus_equipment_maintain_record_detail>();
            exp.And(x => x.topKeys == busEquipmentMaintainRecordHead.topKeys && x.status != (int)EnumMaintainStatus.Maintained && x.nextMaintainTime <= DateTime.Now.AddDays(days));

            if (!string.IsNullOrWhiteSpace(busEquipmentMaintainRecordHead.partCode))
            {
                exp.And(x => x.partCode.Contains(busEquipmentMaintainRecordHead.partCode));
            }

            if (!string.IsNullOrWhiteSpace(busEquipmentMaintainRecordHead.partName))
            {
                exp.And(x => x.partName.Contains(busEquipmentMaintainRecordHead.partName));
            }

            return exp.ToExpression();
        }

        public dynamic Ins(daq_equipment_alarm_record entity)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var response = new Response();
                //entity.createBy = sysWebUser?.Account;
                //entity.createTime = DateTime.Now;
                response.Status = Add(entity);
                if (!response.Status) response.Message = SystemVariable.dataActionError;
                return response;
            });
        }

        public dynamic Upd(daq_equipment_alarm_record entity)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var response = new Response();
                //entity.updateBy = sysWebUser?.Account;
                //entity.updateTime = DateTime.Now;
                response.Status = Update(entity);
                if (!response.Status) response.Message = SystemVariable.dataActionError;
                return response;
            });
        }

        public dynamic DelByIds(Guid[] ids)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var response = new Response();
                Context.Deleteable<daq_equipment_alarm_record>(t => ids.Contains(t.id)).ExecuteCommand();
                return response;
            });
        }

        public Response ExportData(base_equipment entity)
        {
            var response = new Response();
            //if (entity.ProjectCode == "r-1")
            //{
            //    entity.ProjectCode = null;
            //}
            //var sheet1 = Load(null, entity);
            //entity.isHandled = false;
            //var sheet2 = LoadDesc(null, entity);
            ////返回异常数据报错,传空数组给前端
            //response.Result = new
            //{
            //    head = sheet1 is string ? "[]" : sheet1.Result,
            //    body = sheet2 is string ? "[]" : sheet2.Result
            //};
            return response;
        }

        public Dictionary<string, string> GetDicAlarmHandlePeopleList()
        {
            var result = new Dictionary<string, string>();

            //报警处理人 alarmHandlePeople
            var res = Context.Queryable<sys_dict_data>().Where(x => x.dictType == "AlarmHandlePeople").ToList();

            foreach (var item in res)
            {
                result.Add(item.dictValue, item.dictLabel);
            }

            return result;
        }

        public dynamic MaintainHandle(bus_equipment_maintain_record_detail detail, List<IFormFile> excelfile)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var response = new Response();
                var busEquipmentMaintainRecordDetail = Context.Queryable<bus_equipment_maintain_record_detail>().Where(x => x.id == detail.id).First();
                if (busEquipmentMaintainRecordDetail == null)
                {
                    return response.ResponseError($"设备编号“{detail.equipmentCode}”对应部件“{detail.partCode}”不存在待保养的记录数据!");
                }

                if (excelfile.Count > 0)
                {
                    Response saveFileResult = _sysFileService.AddOrUpdate(new sys_File
                    {
                        targetId = busEquipmentMaintainRecordDetail.id.ToString(),
                        fileCode = busEquipmentMaintainRecordDetail.partCode,
                        targetTableName = nameof(bus_equipment_maintain_record_detail),
                        createBy = sysWebUser.Account,
                        createTime = DateTime.Now,
                        excelfile = excelfile,
                        remark = "设备保养",
                    });
                    if (!saveFileResult.Status)
                    {
                        return saveFileResult;
                    }
                }
                //文件上传成功之后再更新
                busEquipmentMaintainRecordDetail.maintainer = detail.maintainer;
                busEquipmentMaintainRecordDetail.maintainTime = detail.maintainTime;
                busEquipmentMaintainRecordDetail.maintainContent = detail.maintainContent;
                busEquipmentMaintainRecordDetail.nextDurationTime = 0;
                busEquipmentMaintainRecordDetail.maintainLevel = detail.maintainLevel;
                busEquipmentMaintainRecordDetail.status = (int)EnumMaintainStatus.Maintained;
                Context.Updateable(busEquipmentMaintainRecordDetail).UpdateColumns(x => new
                {
                    x.status,
                    x.maintainLevel,
                    x.maintainTime,
                    x.maintainer,
                    x.maintainContent,
                    x.nextDurationTime
                }).ExecuteCommand();

                return response;
            });
        }
    }
}