BaseSimService.cs 15.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.POIFS.FileSystem;
using NPOI.SS.Formula.Functions;
using Org.BouncyCastle.Crypto;
using System.Text;
using NPOI.OpenXmlFormats.Dml;

namespace Hh.Mes.Service.Base
{
    public class BaseSimService : RepositorySqlSugar<base_sim>
    {
        public dynamic Load(PageReq pageReq, base_sim entity)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var result = new Response();
                var expression = LinqWhere(entity);
                //先组合查询表达式
                var query = Context.Queryable<base_sim>().Where(expression);

                //Exel为ture就不分页,因为导出的话是全部导出
                if (pageReq != null)
                {
                    int total = 0;
                    var list = query.ToOffsetPage(pageReq.page, pageReq.limit, ref total);
                    result.Result = HandleSimInfo(list);
                    result.Count = total;
                }
                else
                {
                    result.Result = HandleSimInfo(query.ToList());
                    result.Count = result.Result.Count;
                }
                return result;
            }, catchRetrunValue: "list");
        }

        public dynamic Ins(base_sim entity)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var response = new Response();
                var key = Guid.NewGuid();
                entity.simKey = key;
                entity.simId = entity.simNumber;
                entity.createBy = sysWebUser.Account;
                entity.createTime = DateTime.Now;
                entity.getCardDate = null;
                entity.debugDate = null;
                //新增sim卡信息
                Context.Insertable(entity).AddQueue();
                var res = Context.SaveQueues();
                if (res < 1) response.Message = SystemVariable.dataActionError;
                return response;
            });
        }

        public dynamic Upd(base_sim entity)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var response = new Response();
                //判断如果关联了设备,禁止修改卡号
                var historySimInfo = Context.Queryable<base_sim_equipment_rel>().First(x => x.simNumber == entity.simNumber);
                if (historySimInfo != null && entity.simNumber != historySimInfo.simNumber)
                {
                    response.Code = 500;
                    response.Status = false;
                    response.Message = $"当前sim卡已经关联了设备,禁止修改卡号【{historySimInfo.simNumber}】,如果要修改请先解绑sim卡关联的设备!";
                    return response;
                }
                entity.updateBy = sysWebUser.Account;
                entity.updateTime = DateTime.Now;
                Context.Updateable(entity).AddQueue();//修改sim卡信息
                var res = Context.SaveQueues();
                if (res < 0) response.Message = SystemVariable.dataActionError;
                return response;
            });
        }

        public dynamic DelByIds(int[] ids)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var response = new Response();
                List<int> vpnRelIds = new List<int>();//存sim-vpn关联表的id
                List<int> gatewayRelIds = new List<int>();//存sim-gateway关联表的id;
                foreach (var id in ids)
                {
                    //判断如果关联了设备,禁止删除
                    var simInfo = Context.Queryable<base_sim>().Where(x => x.id == id).First();
                    var isEqRel = Context.Queryable<base_sim_equipment_rel>().Any(x => x.simNumber == simInfo.simNumber);
                    if (isEqRel)
                    {
                        response.Code = 500;
                        response.Status = false;
                        response.Message = "当前sim卡已经关联了设备,禁止删除SIM卡,如果要删除请先解绑与sim卡关联的设备!";
                        return response;
                    }

                    //删除vpn,判断是否关联了sim卡, 删除sim卡时同时删除vpn、网关关联
                    var simkey = simInfo.simKey;
                    var vpnRel = Context.Queryable<base_sim_vpn_rel>().Where(x => x.simKey == simkey);
                    if (vpnRel.Any()) vpnRelIds.Add(vpnRel.First().id);

                    var gatewayRel = Context.Queryable<base_sim_gateway_rel>().Where(x => x.simKey == simkey);
                    if (gatewayRel.Any()) gatewayRelIds.Add(gatewayRel.First().id);
                }
                try
                {
                    Context.Ado.BeginTran();
                    Context.Deleteable<base_sim>().In(ids).ExecuteCommand();
                    Context.Deleteable<base_sim_vpn_rel>().In(vpnRelIds).ExecuteCommand();
                    Context.Deleteable<base_sim_gateway_rel>().In(gatewayRelIds).ExecuteCommand();
                    Context.Ado.CommitTran();
                }
                catch (Exception ex)
                {
                    Context.Ado.RollbackTran();
                    Log4NetHelper.Instance.Error($"删除sim卡操作失败:" + ex.Message);
                }
                return response;
            });
        }

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

        public Expression<Func<base_sim, bool>> LinqWhere(base_sim model)
        {
            try
            {
                var exp = Expressionable.Create<base_sim>();
                //数据过滤条件
                //if (!string.IsNullOrWhiteSpace(model.XXX)) exp.And(x => x.XXX.Contains(model.XXX));
                if (!string.IsNullOrWhiteSpace(model.simNumber))
                {
                    exp.And(x => x.simNumber.Contains(model.simNumber));
                }
                if (!string.IsNullOrWhiteSpace(model.simIP))
                {
                    exp.And(x => x.simIP.Contains(model.simIP));
                }
                if (!string.IsNullOrWhiteSpace(model.suppliersInfo))
                {
                    exp.And(x => x.suppliersInfo.Contains(model.suppliersInfo));
                }
                return exp.ToExpression();//拼接表达式
            }
            catch (Exception ex)
            {
                throw new Exception($"{ex.Message}");
            }
        }

        public dynamic BindEquipment(string simNumber, bool checkeds, string equipmentCode, string projectKeys)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var response = new Response();
                string[] strArray = equipmentCode.Split(new char[] { ',' });
                var simBindCount = Context.Queryable<base_sim_equipment_rel>().Where(x => x.simNumber == simNumber).ToList().Count;
                if (strArray != null && strArray.Length > 0)
                {
                    var query = Context.Queryable<base_sim_equipment_rel>().Where(x => x.simNumber == simNumber && x.projectKey == new Guid(projectKeys));
                    foreach (var item in strArray)
                    {
                        if (checkeds)
                        {
                            var isHave = query.Any(x=>x.equipmentCode == item);
                            if (isHave) continue;
                            //添加
                            if (simBindCount < 250 && !isHave)
                            {
                                base_sim_equipment_rel bser = new base_sim_equipment_rel();
                                bser.simNumber = simNumber;
                                bser.equipmentCode = item;
                                bser.projectKey = new Guid(projectKeys);
                                Context.Insertable(bser).AddQueue();
                                response.Status = Context.SaveQueues() > 0;
                                if (!response.Status)
                                {
                                    response.Message = "添加SIM卡关联设备数据失败!";
                                    return response;
                                }
                            }
                            else
                            {
                                response.Message = "不可重复绑定!一张SIM卡只允许绑定250个设备,请选择其它SIM卡绑定";
                                return response;
                            }
                        }
                        else
                        {
                            Context.Deleteable<base_sim_equipment_rel>(x => x.simNumber == simNumber && x.projectKey == new Guid(projectKeys) && x.equipmentCode == item).AddQueue();
                            response.Status = Context.SaveQueues() > 0;
                            if (!response.Status)
                            {
                                response.Message = "删除sim卡与设备绑定关系数据失败!";
                                return response;
                            }
                        }
                    }
                }
                response.Message = "业务数据操作成功,稍后刷新列表数据!";
                return response;
            });
        }

        /// <summary>
        /// 领卡操作 更新字段 领卡日期、调试日期、网关客户信息
        /// 领卡操作 的时候 绑定 网关、vpn 信息操作
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="getCardDate"></param>
        /// <param name="debugDate"></param>
        /// <param name="client"></param>
        /// <returns></returns>
        public dynamic UseSim(base_sim entity)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var response = new Response();

                var e_simKey = entity.simKey;
                var e_vpnKey = entity.vpnKey;
                var e_gatewayKey = entity.gatewayKey;
                if (e_vpnKey == Guid.Empty || e_gatewayKey == Guid.Empty)
                {
                    response.Code = 500;
                    response.Status = false;
                    response.Message = $"vpn/网关不能为空";
                    return response;
                }

                var simInfo = Context.Queryable<base_sim>().First(sim => sim.id == entity.id);
                simInfo.getCardDate = entity.getCardDate;
                simInfo.debugDate = entity.debugDate;
                simInfo.getCardUser = entity.getCardUser;
                simInfo.gatewayClient = entity.gatewayClient;
                simInfo.updateBy = sysWebUser.Account;
                simInfo.updateTime = DateTime.Now;

                base_sim_vpn_rel sim_Vpn_Rel = new base_sim_vpn_rel() { simKey = e_simKey, vpnKey = e_vpnKey };
                base_sim_gateway_rel sim_Gateway_Rel = new base_sim_gateway_rel() { simKey = e_simKey, gatewayKey = e_gatewayKey };
                //vpn关联
                //添加之前判断有没有绑定其他sim卡
                var isHaveVpn = Context.Queryable<base_sim_vpn_rel>().Where(x => x.simKey != e_simKey && x.vpnKey == e_vpnKey);
                if (isHaveVpn.Any())
                {
                    response.Code = 500;
                    response.Status = false;
                    response.Message = $"该VPN已经绑定了SIM卡{isHaveVpn.First().simKey},请选择其它的VPN !";
                    return response;
                }
                var isHaveVpnSim = Context.Queryable<base_sim_vpn_rel>().Where(x => x.simKey == e_simKey);
                if (isHaveVpnSim.Any())
                {
                    //修改
                    sim_Vpn_Rel = isHaveVpnSim.First();
                    sim_Vpn_Rel.vpnKey = e_vpnKey;
                    Context.Updateable(sim_Vpn_Rel).AddQueue();
                }
                else
                {
                    //添加
                    Context.Insertable(sim_Vpn_Rel).AddQueue();
                }

                //绑定网关
                //添加之前判断有没有绑定其他sim卡
                var isHaveGate = Context.Queryable<base_sim_gateway_rel>().Where(x => x.simKey != e_simKey && x.gatewayKey == e_gatewayKey);
                if (isHaveGate.Any())
                {
                    response.Code = 500;
                    response.Status = false;
                    response.Message = $"该网关已经绑定了SIM卡{isHaveGate.First().simKey},请选择其它的网关 !";
                    return response;
                }
                var isHaveGateSim = Context.Queryable<base_sim_gateway_rel>().Where(x => x.simKey == e_simKey);
                if (isHaveGateSim.Any())
                {
                    //修改
                    sim_Gateway_Rel = isHaveGateSim.First();
                    sim_Gateway_Rel.gatewayKey = e_gatewayKey;
                    Context.Updateable(sim_Gateway_Rel).AddQueue();
                }
                else
                {
                    //添加
                    Context.Insertable(sim_Gateway_Rel).AddQueue();
                    simInfo.simRemark += $" {DateTime.Now.ToString("yyyy-MM-dd")}已领用";
                }

                Context.Updateable(simInfo).AddQueue();

                var res = Context.SaveQueues();
                if (res < 0) response.Message = SystemVariable.dataActionError;

                return response;
            });
        }

        /// <summary>
        /// 对返回多条sim信息,
        /// </summary>
        /// <param name="simList"></param>
        /// <returns></returns>
        public List<base_sim> HandleSimInfo(List<base_sim> simList)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                if (simList != null)
                {
                    var all = Context.Queryable<base_sim, base_sim_vpn_rel, base_vpn, base_sim_gateway_rel, base_gateway>((s, sv, v, sg, g) =>
                                                 new JoinQueryInfos(JoinType.Left, s.simKey == sv.simKey,
                                                    JoinType.Left, sv.vpnKey == v.vpnKey,
                                                    JoinType.Left, s.simKey == sg.simKey,
                                                    JoinType.Left, g.gatewayKey == sg.gatewayKey))
                                            .Select((s, sv, v, sg, g) => new
                                            {
                                                s.simKey,
                                                v.vpnNumber,
                                                g.gatewaySerialNumber,
                                                v.vpnKey,
                                                g.gatewayKey
                                            })
                                            .ToList();
                    foreach (var sim in simList)
                    {
                        var query = all.Where(x => x.simKey == sim.simKey).First();
                        sim.gatewaySerialNumber = query.gatewaySerialNumber;
                        sim.vpnNumber = query.vpnNumber;
                        sim.gatewayKey = query.gatewayKey;
                        sim.vpnKey = query.vpnKey;
                        if (query.gatewayKey != Guid.Empty && query.vpnKey != Guid.Empty) sim.isUse = true;
                    }
                }
                return simList;
            });
        }
    }
}