BaseEquipmentService.cs 13.4 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;
                var expression = LinqWhereEquipment(entity);
                query = Context.Queryable<base_project, sys_user_project_rel,  base_equipment, base_sim_equipment_rel, daq_equipment_status_record>
                                                        ((p, upRel,  eq, sim,  eqStatus) =>
                                                          new JoinQueryInfos(JoinType.Left, upRel.clientKeys == p.keys,
                                                                             JoinType.Inner, p.keys == eq.projectKeys,
                                                                             JoinType.Left, eq.equipmentCode == sim.equipmentCode,
                                                                             JoinType.Left, eq.equipmentCode == eqStatus.equipmentCode
                                                                             )
                                                        )
                                                      .Where(expression)
                                                      .OrderBy((p,  upRel, eq, sim, eqStatus) => p.projectCode, OrderByType.Asc)
                                                      .OrderBy((p,  upRel, eq, sim, eqStatus) => eq.factoryCode, OrderByType.Asc)
                                                      .OrderBy((p,  upRel, eq, sim, eqStatus) => eq.equipmentCode, OrderByType.Asc)
                                                      .OrderBy((p,  upRel, eq, sim, eqStatus) => eq.createTime, OrderByType.Desc)
                                                      .Select((p,   upRel, eq, sim,  eqStatus) => new
                                                      {
                                                          eq.id,
                                                          eq.projectKeys,
                                                          p.projectName,
                                                          eq.factoryCode,
                                                          sim.simNumber,

                                                          eq.equipmentCode,
                                                          eq.equipmentName,
                                                          eq.equipmentTypeCode,
                                                          eq.destinationArea,
                                                          eq.isMaintain,

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

                                                          eq.imgSrc,
                                                          eqStatus.status,
                                                          eqOnLineUpdateTime = eqStatus.updateTime,
                                                          eqOnLineNowTime = currentTime,

                                                          eq.createBy,
                                                          eq.createTime,
                                                          eq.updateBy,
                                                          eq.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;

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

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

                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<base_project, sys_user_project_rel, base_equipment, base_sim_equipment_rel, daq_equipment_status_record, bool>> LinqWhereEquipment(base_equipment model)
        {
            try
            {
                var exp = Expressionable.Create<base_project, sys_user_project_rel, base_equipment, base_sim_equipment_rel, daq_equipment_status_record>();
                if (!string.IsNullOrWhiteSpace(model.equipmentCode))
                {
                    exp.And((p, upRel, eq, sim, eqStatus) => eq.equipmentCode.Contains(model.equipmentCode));
                }
                if (!string.IsNullOrWhiteSpace(model.equipmentName))
                {
                    exp.And((p, upRel, eq, sim, eqStatus) => eq.equipmentName.Contains(model.equipmentName));
                }
                if (model.projectKeys != Guid.Empty)
                {
                    exp.And((p, upRel, eq, sim, eqStatus) => eq.projectKeys == model.projectKeys);
                }
                exp.And((p, upRel, eq, sim, eqStatus) => !SystemVariable.IotNotContainDevice.Contains(eq.equipmentTypeCode));
                //非管理员,查询登陆用户绑定客户管理的项目
                string currentUser = sysWebUser.Account;
                if (currentUser != SystemVariable.DefaultCreated)
                {
                    exp.And((p, upRel, eq, sim, eqStatus) => upRel.userAccount == currentUser);
                }
                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
                                                                 && !SystemVariable.IotNotContainDevice.Contains(x.equipmentTypeCode));
            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
    }
}