BaseEquipmentService.cs 18.5 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.Expressions;
using Hh.Mes.Pojo.System;
using Microsoft.AspNetCore.Http;
using System.IO;
using System.Text;
using Hh.Mes.Service.SystemAuth;
using Hh.Mes.POJO.WMSEntity;
using Hh.Mes.POJO.WebEntity;
using System.Linq;

namespace Hh.Mes.Service.Equipment
{
    public class BaseEquipmentService : RepositorySqlSugar<base_equipment>
    {
        public BaseEquipmentService(IAuth auth) : base(auth) { }

        public dynamic Load(PageReq pageReq, base_equipment entity)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var result = new Response();
                //先组合查询表达式
                var currentTime = DateTime.Now;
                var expression = LinqWhereEquipment(entity);

                string currentUser = sysWebUser.Account;
                var query = Context.Queryable<base_project, base_equipment, base_sim_equipment_rel, daq_equipment_status_record>
                                                         ((p, eq, sim, eqStatus) =>
                                                           new JoinQueryInfos(JoinType.Right, p.keys == eq.projectKeys,
                                                                              JoinType.Left, eq.equipmentCode == sim.equipmentCode,
                                                                              JoinType.Left, eq.equipmentCode == eqStatus.equipmentCode)
                                                         ).Where(expression)
                                                       .OrderBy((p, eq, sim, eqStatus) => p.projectCode, OrderByType.Asc)
                                                       .OrderBy((p, eq, sim, eqStatus) => eq.equipmentTypeCode, OrderByType.Asc)
                                                       .OrderBy((p, eq, sim, eqStatus) => eq.equipmentCode, OrderByType.Asc)
                                                       .Select((p, eq, sim, eqStatus) => new
                                                       {
                                                           eq.id,
                                                           eq.projectKeys,
                                                           p.projectName,
                                                           eq.factoryCode,
                                                           sim.simNumber,
                                                           eq.equipmentGroupId,
                                                           eq.equipmentCode,
                                                           eq.equipmentName,
                                                           eq.equipmentTypeCode,
                                                           eq.destinationArea,
                                                           eq.isMaintain,

                                                           eq.ip,
                                                           remark = SqlFunc.Subqueryable<daq_equipment_alarm_record>().Where(c => c.equipmentCode == eq.equipmentCode && c.isHandled == false).Any() ? "有未处理报警记录" : null,
                                                           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();
                string account = sysWebUser.Account;
                entity.createBy = 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;
                }
                var wmsSn = DimsContextWms.Queryable<Sn>().Where(x => x.code == entity.equipmentCode).First();
                if (wmsSn != null)
                {
                    var operationDetail = new SnPartDetailHistory
                    {
                        snId = wmsSn.id,
                        projectNo = wmsSn.correlatedCode,
                        containerCode = DimsContextWms.Queryable<SnPartDetailHistory>().Where(x => x.snCode == wmsSn.code && !string.IsNullOrEmpty(x.containerCode)).Select(x => x.containerCode).First(),
                        materialCode = DimsContextWms.Queryable<SnPartDetailHistory>().Where(x => x.snCode == wmsSn.code && !string.IsNullOrEmpty(x.materialCode)).Select(x => x.materialCode).First(),
                        billCode = DimsContextWms.Queryable<SnPartDetailHistory>().Where(x => x.snCode == wmsSn.code && !string.IsNullOrEmpty(x.billCode)).Select(x => x.billCode).First(),
                        referCode = DimsContextWms.Queryable<SnPartDetailHistory>().Where(x => x.snCode == wmsSn.code && !string.IsNullOrEmpty(x.referCode)).Select(x => x.referCode).First(),
                        part = DimsContextWms.Queryable<SnPartDetailHistory>().Where(x => x.snCode == wmsSn.code && !string.IsNullOrEmpty(x.part)).Select(x => x.part).First(),
                        snCode = wmsSn.code,
                        operation = "IOT使用SN",
                        operationTime = DateTime.Now.ToString(),
                        operationUser = account,
                        operationUserName = Context.Queryable<sys_user>().Where(x => x.account == account).Select(x => x.name).First(),
                        created = DateTime.Now,
                        createdBy = account,
                    };
                    DimsContextWms.Insertable(operationDetail).ExecuteCommand();
                }
                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)
                                    .AddQueue();

                //同步修改daq_equipment表设备名称
                var isHave = Context.Queryable<daq_equipment>().Any(x => x.code == entity.equipmentCode);
                if (isHave)
                {
                    string updateBy = sysWebUser?.Account;
                    Context.Updateable<daq_equipment>()
                           .SetColumns(x => x.name == entity.equipmentName)
                           .SetColumns(x => x.equipmentTypeId == entity.equipmentGroupId)
                           .SetColumns(x => x.updated == DateTime.Now)
                           .SetColumns(x => x.updatedBy == updateBy)
                           .Where(x => x.code == entity.equipmentCode)
                           .AddQueue();
                }
                Context.Updateable(entity).AddQueue();
                response.Status = Context.SaveQueues() > 0;
                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);
        }

        private Expression<Func<sys_user_project_rel, bool>> GetExpression(string currentUser)
        {
            var exp = Expressionable.Create<sys_user_project_rel>();
            if (currentUser != SystemVariable.DefaultCreated)
            {
                //非管理员,查询登陆用户绑定客户管理的项目
                exp.And(x => x.userAccount == currentUser);
            }
            return exp.ToExpression();
        }

        public Expression<Func<base_project, base_equipment, base_sim_equipment_rel, daq_equipment_status_record, bool>> LinqWhereEquipment(base_equipment model)
        {
            try
            {
                var exp = Expressionable.Create<base_project, base_equipment, base_sim_equipment_rel, daq_equipment_status_record>();
                if (!string.IsNullOrWhiteSpace(model.equipmentCode))
                {
                    exp.And((p, eq, sim, eqStatus) => eq.equipmentCode.Contains(model.equipmentCode));
                }
                if (!string.IsNullOrWhiteSpace(model.equipmentName))
                {
                    exp.And((p, eq, sim, eqStatus) => eq.equipmentName.Contains(model.equipmentName));
                }
                if (model.projectKeys != Guid.Empty)
                {
                    exp.And((p, eq, sim, eqStatus) => eq.projectKeys == model.projectKeys);
                }
                else
                {
                    string user = sysWebUser.Account;
                    if (user != SystemVariable.DefaultCreated)
                    {
                        var projectRoleKeys = GetProjectRoleKeys(user);
                        exp.And((p, eq, sim, eqStatus) => SqlFunc.Subqueryable<sys_role_projects_rel>().Where(c => projectRoleKeys.Contains(c.project_roles_key) && c.project_key == p.keys).Any());
                    }
                }

                exp.And((p, eq, sim, eqStatus) => !SystemVariable.IotNotContainDevice.Contains(eq.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
                                                                 && !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;
            });
        }

        /// <summary>
        /// 获取SN信息
        /// </summary>
        /// <param name="projectCode">项目号</param>
        /// <returns></returns>
        public Response GetSnCodes(string projectCode)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var response = new Response();
                var result = Context.Queryable<bus_sn_project_info_wms_head>().Where(x => !string.IsNullOrEmpty(x.sn)
                //&& x.correlatedCode == projectCode
                && !SqlFunc.Subqueryable<base_equipment>().Where(s => s.equipmentCode == x.sn).Any()).Select(x => x.sn).Distinct().ToList();
                response.Result = result;
                response.Count = result.Count;
                return response;
            });
        }

        public dynamic GetEquipmntGroup()
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var response = new Response<List<BaseEquipmentGroup>>();
                var data = Context.Queryable<BaseEquipmentGroup>().ToList();
                var treeData = BuiderTree(data);
                response.Result = treeData;
                response.Count = treeData.Count;
                return response;
            });
        }

        private List<BaseEquipmentGroup> BuiderTree(List<BaseEquipmentGroup> equipmentGroups, BaseEquipmentGroup parentNode = null)
        {
            var nodes = new List<BaseEquipmentGroup>();
            if (parentNode == null)
            {
                nodes = equipmentGroups.Where(x => x.parentId == default).ToList();
            }
            else
            {
                nodes = equipmentGroups.Where(x => x.parentId == parentNode.id).ToList();
                parentNode.children = nodes;
            }

            foreach (var item in nodes)
            {
                item.children = BuiderTree(equipmentGroups, item);
            }
            return nodes;
        }

        #endregion
    }
}