BaseEquipmentService.cs 17.8 KB
using Hh.Mes.Common.Infrastructure;
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 NPOI.SS.Formula.Functions;
using Hh.Mes.Common.DataTableTo;
using Microsoft.AspNetCore.Http;
using System.IO;
using System.Text;
using NPOI.POIFS.FileSystem;


namespace Hh.Mes.Service.Equipment
{
    public class BaseEquipmentService : RepositorySqlSugar<base_equipment>
    {
        public dynamic Load(PageReq pageReq, base_equipment entity)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var result = new Response();

                //先组合查询表达式
                dynamic query = null;

                var currentTime = DateTime.Now;
                //如果非管理员查出对应用户客户管理项目下厂房里的设备:
                string currentUser = sysWebUser.Account;
                if (currentUser != SystemVariable.DefaultCreated)
                {
                    var expression = LinqWhereNoSystem(entity);
                    query = Context.Queryable<sys_user_client_rel, base_project_client_rel, base_equipment, base_project, base_sim_equipment_rel, base_factory, daq_equipment_status_record>
                                                            ((x, y, z, p, s, f, xp) =>
                                                              new JoinQueryInfos(JoinType.Inner, x.userAccount == currentUser && x.clientKeys == y.clientKeys,
                                                                                 JoinType.Inner, y.projectKeys == z.projectKeys,
                                                                                 JoinType.Inner, z.projectKeys == p.keys,
                                                                                 JoinType.Left, s.equipmentCode == z.equipmentCode,
                                                                                 JoinType.Inner, f.projectKeys == z.projectKeys && f.factoryCode == z.factoryCode,
                                                                                 JoinType.Left, xp.equipmentCode == z.equipmentCode
                                                                                 )
                                                            )
                                                          .Where(expression)
                                                          .OrderBy((x, y, z, p, s, f, xp) => p.projectCode,OrderByType.Asc)
                                                          .OrderBy((x, y, z, p, s, f, xp) => z.factoryCode,OrderByType.Asc)
                                                          .OrderBy((x, y, z, p, s, f, xp) => z.equipmentCode,OrderByType.Asc)
                                                          .OrderBy((x, y, z, p, s, f, xp) => z.createTime, OrderByType.Desc)
                                                          .Select((x, y,  z, p, s, f, xp) => new
                                                          {
                                                              z.id,
                                                              z.projectKeys,
                                                              p.projectName,
                                                              z.factoryCode,
                                                              s.simNumber,
                                                              f.factoryName,

                                                              z.equipmentCode,
                                                              z.equipmentName,
                                                              z.equipmentTypeCode,
                                                              z.destinationArea,
                                                              z.isMaintain,

                                                              z.ip,
                                                              z.remark,
                                                              z.equipmentMaintainRuleCode,
                                                              z.isEnable,
                                                              z.startTime,
                                                              z.otherCode,

                                                              z.imgSrc,
                                                              xp.status,
                                                              eqOnLineUpdateTime = z.updateTime,
                                                              eqOnLineNowTime = currentTime,

                                                              z.createBy,
                                                              z.createTime,
                                                              z.updateBy,
                                                              z.updateTime,
                                                          });

                }
                else
                {
                    var expression = LinqWhereSystem(entity);
                    query = Context.Queryable<base_equipment, base_project, base_sim_equipment_rel, base_factory, daq_equipment_status_record>
                                                          ((x,  p, s, f, z) =>
                                                           new JoinQueryInfos(
                                                               JoinType.Inner, x.projectKeys == p.keys,
                                                               JoinType.Left, s.equipmentCode == x.equipmentCode,
                                                               JoinType.Inner, f.projectKeys == x.projectKeys && f.factoryCode == x.factoryCode,
                                                               JoinType.Left, z.equipmentCode == x.equipmentCode
                                                               )
                                                          )
                                                          .Where(expression)
                                                          .OrderBy((x,  p, s, f, z) => p.projectCode, OrderByType.Asc)
                                                          .OrderBy((x,  p, s, f, z) => x.factoryCode, OrderByType.Asc)
                                                           .OrderBy((x, p, s, f, z) => x.equipmentCode, OrderByType.Asc)
                                                          .OrderBy((x,  p, s, f, z) => x.createTime, OrderByType.Desc)
                                                          .Select((x,   p, s, f, z) => new
                                                          {
                                                              x.id,
                                                              x.projectKeys,
                                                              p.projectName,
                                                              x.factoryCode,
                                                              s.simNumber,
                                                              f.factoryName,

                                                              x.equipmentCode,
                                                              x.equipmentName,
                                                              x.equipmentTypeCode,
                                                              x.destinationArea,
                                                              x.isMaintain,

                                                              x.ip,
                                                              x.remark,
                                                              x.equipmentMaintainRuleCode,
                                                              x.isEnable,
                                                              x.startTime,
                                                              x.otherCode,

                                                              x.imgSrc,
                                                              z.status,
                                                              eqOnLineUpdateTime = z.updateTime,
                                                              eqOnLineNowTime = currentTime,

                                                              x.createBy,
                                                              x.createTime,
                                                              x.updateBy,
                                                              x.updateTime,
                                                          });
                }
                //Exel false 分页
                if (!entity.Exel)
                {
                    int total = 0;
                    result.Result = query.ToOffsetPage(pageReq.page, pageReq.limit, ref total);
                    result.Count = total;
                }
                else
                {
                    result.Result = query.ToList();
                    result.Count = result.Result.Count;
                }
                return result;
            }, catchRetrunValue: "list");
        }

        public dynamic Ins(base_equipment entity)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var response = new Response();
                entity.createBy = sysWebUser.Account;
                entity.createTime = DateTime.Now;
                entity.isMaintain = false;

                var pro = Context.Queryable<base_project>().First(x => x.keys == entity.projectKeys);
                pro.eqCount = GetProjectEqCount(pro.keys) + 1;

                Context.Updateable<base_project>(pro)
                                    .UpdateColumns(it => new { it.eqCount})
                                    .Where(x => x.keys == entity.projectKeys)
                                    .AddQueue();
                Context.Insertable(entity).AddQueue();

                response.Status = Context.SaveQueues()>0;
                if (!response.Status) response.Message = SystemVariable.dataActionError;
                return response;
            });
        }

        public dynamic Upd(base_equipment 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;
            });
        }

        /// <summary>
        /// 设备删除
        /// </summary>
        public dynamic DelByIds(int[] ids)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var response = new Response();
                var id = ids[0];
                var projectKeys = Context.Queryable<base_equipment>().First(x => x.id == id).projectKeys;
                var pro = Context.Queryable<base_project>().First(x => x.keys == projectKeys);
                pro.eqCount = GetProjectEqCount(pro.keys)  - 1;

                Context.Updateable<base_project>(pro)
                       .UpdateColumns(it => new { it.eqCount })
                       .Where(x => x.id == pro.id)
                       .AddQueue();
                Context.Deleteable<base_equipment>(t => t.id == id).AddQueue();
                response.Status = Context.SaveQueues() > 0;

                return response;
            });
        }

        public Response ExportData(base_equipment entity)
        {
            return Load(null, entity);
        }

        public Expression<Func<sys_user_client_rel, base_project_client_rel, base_equipment, base_project, bool>> LinqWhereNoSystem(base_equipment model)
        {
            try
            {
                var exp = Expressionable.Create<sys_user_client_rel, base_project_client_rel, base_equipment, base_project>();
                if (!string.IsNullOrWhiteSpace(model.equipmentCode))
                {
                    exp.And((x, y, z, p) => z.equipmentCode.Contains(model.equipmentCode));
                }
                if (!string.IsNullOrWhiteSpace(model.equipmentName))
                {
                    exp.And((x, y, z, p) => z.equipmentName.Contains(model.equipmentName));
                }
                if (model.projectKeys != Guid.Empty)
                {
                    exp.And((x, y, z, p) => z.projectKeys == model.projectKeys);
                }
				exp.And((x, y, z, p) => !SystemVariable.IotNotContainDevice.Contains(z.equipmentTypeCode));

				return exp.ToExpression();//拼接表达式
            }
            catch (Exception ex)
            {
                throw new Exception($"{ex.Message}");
            }
        }

        public Expression<Func<base_equipment, base_project, bool>> LinqWhereSystem(base_equipment model)
        {
            try
            {
                var exp = Expressionable.Create<base_equipment, base_project>();
                if (!string.IsNullOrWhiteSpace(model.equipmentCode))
                {
                    exp.And((x,  p) => x.equipmentCode.Contains(model.equipmentCode));
                }
                if (!string.IsNullOrWhiteSpace(model.equipmentName))
                {
                    exp.And((x, p) => x.equipmentName.Contains(model.equipmentName));
                }
                if (model.projectKeys != Guid.Empty)
                {
                    exp.And((x, p) => x.projectKeys == model.projectKeys);
                }
				exp.And((x, p) => !SystemVariable.IotNotContainDevice.Contains(x.equipmentTypeCode));
				return exp.ToExpression();//拼接表达式
            }
            catch (Exception ex)
            {
                throw new Exception($"{ex.Message}");
            }
        }

        /// <summary>
        /// 获取项目下面所有的设备
        /// </summary>
        /// <returns></returns>
        public int GetProjectEqCount(Guid projectKeys)
        {
            var count = Context.Queryable<base_equipment>().Count(x => x.projectKeys == projectKeys);
            return count;
        }


        /// <summary>
        /// 设备表存在报警记录更新、不存在不处理
        /// </summary>
        public void UpdateRemarkWithAlarmStatus()
        {
            ExceptionsHelp.Instance.ExecuteVoidFunc(() =>
           {
               var stringBuilder = new StringBuilder();

               stringBuilder.AppendLine($@" UPDATE base_equipment
                                             SET remark = CASE
                                                             WHEN EXISTS (
                                                                SELECT 1
                                                                FROM daq_equipment_alarm_record with (nolock)
                                                                WHERE daq_equipment_alarm_record.EquipmentCode = base_equipment.EquipmentCode and IsHandled=0
                                                             ) THEN '有未处理报警记录'
                                                            ELSE ''
                                                          END;");
               base.Context.Ado.ExecuteCommand(stringBuilder.ToString());
           });
        }

        #region 设备上传更新图片
        public dynamic UpdateEquipmentImage(int equipmentId, IFormFile file)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var response = new Response();
                // 检查文件上传
                if (file == null) return response.ResponseError("请选择需要上传的文件");

                // 检查文件类型
                var allowedFileTypes = new List<string> { "image/jpeg", "image/gif", "image/png" };
                if (!allowedFileTypes.Contains(file.ContentType))
                {
                    return response.ResponseError("不支持此文件格式!图片文件仅支持[jpeg、png、gif]文件");
                }

                // 创建目标文件夹路径
                var uploadEquipmentPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "images", "equipment");
                if (!Directory.Exists(uploadEquipmentPath))
                {
                    Directory.CreateDirectory(uploadEquipmentPath);
                }

                // 生成新文件名
                var suffix = Path.GetExtension(file.FileName);
                var fileName = Path.GetFileNameWithoutExtension(file.FileName);
                var newFileName = $"{fileName}_{DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss")}{suffix}";

                // 构建完整文件路径
                var filePath = Path.Combine(uploadEquipmentPath, newFileName);

                // 保存文件
                using (var fs = new FileStream(filePath, FileMode.Create))
                {
                    file.CopyTo(fs);
                    fs.Flush();
                }
                var equipment = new base_equipment()
                {
                    imgSrc = newFileName,
                    updateTime = DateTime.Now,
                    updateBy = sysWebUser.Account
                };

                var result = Context.Updateable(equipment)
                                    .UpdateColumns(it => new { it.imgSrc, it.updateBy, it.updateTime })
                                    .Where(x => x.id == equipmentId)
                                    .ExecuteCommand();
                if (result < 0) response.Message = SystemVariable.dataActionError;
                return response;
            });
        }
        #endregion
    }
}