Esempio n. 1
0
        public Result UpdatePlatform([FromBody] IEnumerable <AccountInfo> accountInfos)
        {
            if (accountInfos == null || !accountInfos.Any())
            {
                return(Result.GenError <Result>(Error.ParamError));
            }

            if (accountInfos.Any(x => x.Id == 0))
            {
                return(Result.GenError <Result>(Error.AccountNotExist));
            }

            var ids             = accountInfos.Select(x => x.Id).Distinct();
            var oldAccountInfos = AccountInfoHelper.Instance.GetByIds <AccountInfo>(ids);

            if (oldAccountInfos.Count() != accountInfos.Count())
            {
                return(Result.GenError <Result>(Error.AccountNotExist));
            }
            if (oldAccountInfos.Any(x => x.Default))
            {
                return(Result.GenError <Result>(Error.AccountNotOperate));
            }
            var markedDateTime = DateTime.Now;

            foreach (var info in accountInfos)
            {
                info.MarkedDateTime = markedDateTime;
                info.Belong         = oldAccountInfos.First(x => x.Id == info.Id).Belong;
            }
            AccountInfoHelper.Platform(accountInfos);
            WorkFlowHelper.Instance.OnUpdateAccount(markedDateTime, accountInfos, oldAccountInfos);
            return(Result.GenError <Result>(Error.Success));
        }
Esempio n. 2
0
        public Result Delete([FromBody] BatchDelete batchDelete)
        {
            var ids          = batchDelete.ids;
            var accountInfos = AccountInfoHelper.Instance.GetByIds <AccountInfo>(ids);

            if (accountInfos.Count() != ids.Count())
            {
                return(Result.GenError <Result>(Error.AccountNotExist));
            }

            if (accountInfos.Any(x => x.Default))
            {
                return(Result.GenError <Result>(Error.AccountNotExist));
            }

            var createUserId = Request.GetIdentityInformation();
            var accountInfo  = AccountInfoHelper.GetAccountInfo(createUserId);

            if (accountInfo == null)
            {
                return(Result.GenError <CommonResult>(Error.AccountNotExist));
            }

            if (accountInfos.Any(x => x.Id == accountInfo.Id))
            {
                return(Result.GenError <Result>(Error.OperateNotSafe));
            }
            AccountInfoHelper.Instance.Delete(ids);
            WorkFlowHelper.Instance.OnDeleteAccount(ids);
            return(Result.GenError <Result>(Error.Success));
        }
Esempio n. 3
0
        public DataResult Pages([FromQuery] PlatForm Plat)
        {
            var userId      = Request.GetIdentityInformation();
            var accountInfo = AccountInfoHelper.GetAccountInfo(userId);

            if (accountInfo == null)
            {
                return(Result.GenError <DataResult>(Error.AccountNotExist));
            }

            var result      = new DataResult();
            var permissions = PermissionGroupHelper.PermissionGroupsList.Values
                              //.Where(x => !x.IsDelete && x.IsPage && accountInfo.PermissionsList.Any(y => y == x.Id)).Select(x => new { x.Id, x.Name, x.Url, x.Order, x.Label }));
                              .Where(x => !x.MarkedDelete && x.IsPage && accountInfo.PermissionsList.Any(y => y == x.Id)).ToList();
            var parents = permissions.GroupBy(x => x.Parent).Select(x => x.Key).Distinct();
            var not     = parents.Where(x => permissions.All(y => y.Id != x));

            permissions.AddRange(PermissionGroupHelper.PermissionGroupsList.Values.Where(x => not.Contains(x.Id)));
            permissions = permissions.Where(x => x.Type != 0).ToList();
            var rp = new List <PermissionGroup>();
            var p  = permissions.Where(x => x.Parent == 0).OrderBy(x => x.Order);

            rp.AddRange(p);
            rp.AddRange(permissions.Where(x => x.Parent != 0).OrderBy(x => p.FirstOrDefault(y => x.Parent == y.Id)?.Order).ThenBy(x => x.Order));
            if (Plat == PlatForm.设备平台)
            {
                rp = rp.Where(x => x.Parent != 0).OrderBy(x => x.Parent).ThenBy(x => x.Order).ToList();
            }
            result.datas.AddRange(rp);
            return(result);
        }
        public static IEnumerable <WarningClearDetail> GetWarningClears(int wId, DateTime startTime, DateTime endTime, int setId,
                                                                        WarningType warningType, WarningDataType dataType, IEnumerable <int> deviceIds)
        {
            var clears = new List <WarningClearDetail>();
            var param  = new List <string> {
                "DealTime >= @startTime", "DealTime <= @endTime"
            };

            if (wId != 0)
            {
                param.Add("WorkshopId = @wId");
            }
            if (warningType != WarningType.默认)
            {
                param.Add("b.WarningType = @warningType");
            }
            if (dataType != WarningDataType.默认)
            {
                param.Add("b.DataType = @dataType");
            }
            if (setId != 0)
            {
                param.Add("SetId = @setId");
            }
            if (deviceIds != null && deviceIds.Any())
            {
                var t = new List <WarningClearDetail>();
                param.Add("FIND_IN_SET(@deviceId, a.DeviceIds)");
                foreach (var deviceId in deviceIds)
                {
                    t.AddRange(ServerConfig.ApiDb.Query <WarningClearDetail>(
                                   $"SELECT a.* FROM `warning_clear` a " +
                                   $"JOIN `warning_set` b ON a.SetId = b.Id {(param.Any() ? $" WHERE {param.Join(" AND ")}" : "")} ORDER BY DealTime DESC;",
                                   new { startTime, endTime, setId, deviceId }));
                }
                clears.AddRange(t.GroupBy(x => x.SetId).Select(x => x.First()));
            }
            else
            {
                clears.AddRange(ServerConfig.ApiDb.Query <WarningClearDetail>(
                                    $"SELECT a.* FROM `warning_clear` a " +
                                    $"JOIN `warning_set` b ON a.SetId = b.Id {(param.Any() ? $" WHERE {param.Join(" AND ")}" : "")} ORDER BY DealTime DESC;",
                                    new { startTime, endTime, setId, warningType, dataType }));
            }

            if (clears.Any())
            {
                var sets          = WarningSetHelper.GetMenus(wId, clears.Select(x => x.SetId).Distinct()).ToDictionary(x => x.Id);
                var devices       = DeviceHelper.GetMenus(wId, clears.SelectMany(x => x.DeviceIdList).Distinct()).ToDictionary(x => x.Id);
                var createUserIds = AccountInfoHelper.GetAccountInfoByAccounts(clears.Select(x => x.CreateUserId).Distinct()).ToDictionary(x => x.Account);
                foreach (var d in clears)
                {
                    d.Name    = createUserIds.ContainsKey(d.CreateUserId) ? createUserIds[d.CreateUserId].Name : "";
                    d.SetName = sets.ContainsKey(d.SetId) ? sets[d.SetId].Name : "";
                    d.DeviceList.AddRange(d.DeviceIdList.Select(x => devices.ContainsKey(x) ? devices[x].Code : x.ToString()));
                }
            }

            return(clears);
        }
        /// <summary>
        /// Delete a particular role for a user. This option will reduce their role rank by one. A user will never be without a role.
        /// </summary>
        /// <param name="UserName">The user whose rank will be reduced.</param>
        private void DeleteRoleForUser(string UserName)
        {
            ApplicationUser user = context.Users.FirstOrDefault(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase));

            if (user == null)
            {
                ViewBag.ResultMessageError = "Cannot find \"" + UserName + "\" in the database.";
            }

            else
            {
                // Don't let them be removed from the admin role to prevent lockout.
                if (UserManager.GetRoles(user.Id).Contains("Admin") && AccountInfoHelper.NumberAdminsLeft() == 1)
                {
                    ViewBag.ResultMessageError = UserName + " is an admin and the only admin remaining. The user must be deleted instead.";
                }

                else
                {
                    // Get all the user roles (will only be 1).
                    var oldRole = (string)UserManager.GetRoles(user.Id).ElementAt(0);

                    // Get the list of roles.
                    Dictionary <int, string> roleList = CustomRoles.Roles();

                    // Get the key associated with the role name.
                    var key = roleList.Keys.Single(k => roleList[k] == oldRole);

                    // If they are already the lowest user role, then we cannot remove them from that role.
                    if (key == roleList.Count - 1)
                    {
                        ViewBag.ResultMessageError = "Role was unsuccessfully reduced from " + oldRole + " because that is the lowest role possible. If you like, you may delete " + UserName + " instead. ";
                    }

                    else
                    {
                        // Remove the user from their previous role.
                        UserManager.RemoveFromRole(user.Id, oldRole);

                        // Now we add the user to the role right below their old role.
                        AddUserToRole(UserName, roleList[key + 1]);

                        ViewBag.ResultMessage = "Role removed from this user successfully! User has been added to the " + roleList[key + 1] + " role.";
                    }
                }
            }

            // Populate the roles for a dropdown. This is required else an error will occur.
            var list = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem {
                Value = rr.Name.ToString(), Text = rr.Name
            }).ToList();

            ViewBag.Roles = list;
        }
Esempio n. 6
0
        public DataResult GetAccount([FromQuery] int qId, bool menu, bool ws, bool all, string ids, string eIds)
        {
            var result = new DataResult();

            if (ws)
            {
                if (qId == 0)
                {
                    result.errno = Error.AccountNotExist;
                    return(result);
                }

                var acc = AccountInfoHelper.Instance.Get <AccountInfo>(qId);
                if (acc == null)
                {
                    result.errno = Error.AccountNotExist;
                    return(result);
                }

                if (acc.Id == 1 || acc.Belongs.Any())
                {
                    result.datas.AddRange(WorkshopHelper.GetMenus(acc.Belongs));
                }
                return(result);
            }
            var idList  = !ids.IsNullOrEmpty() ? ids.Split(",").Select(int.Parse) : new List <int>();
            var eIdList = !eIds.IsNullOrEmpty() ? eIds.Split(",").Select(int.Parse) : new List <int>();

            if (menu)
            {
                result.datas.AddRange(AccountInfoHelper.GetMenu(all, qId, idList, eIdList));
            }
            else
            {
                var data      = AccountInfoHelper.GetAccountInfos(qId, all, idList, eIdList);
                var wIds      = data.SelectMany(x => x.Belongs);
                var workshops = WorkshopHelper.Instance.GetByIds <Workshop>(wIds);
                foreach (var d in data)
                {
                    d.WorkShops = d.Belongs.Where(wId => workshops.Any(x => x.Id == wId)).Select(wId => workshops.First(x => x.Id == wId).Name).Join();
                }
                result.datas.AddRange(data);
            }
            if (qId != 0 && !result.datas.Any())
            {
                result.errno = Error.AccountNotExist;
                return(result);
            }
            return(result);
        }
Esempio n. 7
0
        private async Task DeleteUser()
        {
            try
            {
                using (var context = new IdentityDbContext())
                {
                    string username = User.Identity.Name;

                    if (User.IsInRole("Admin") && AccountInfoHelper.NumberAdminsLeft() == 1)
                    {
                        ViewBag.DeleteError = "Cannot delete this user because they are the last admin. That would result in being locked out.";
                    }

                    else
                    {
                        var user = await UserManager.FindByNameAsync(username);

                        var logins = user.Logins;

                        // Remove the logins if any.
                        foreach (var login in logins.ToList())
                        {
                            await _userManager.RemoveLoginAsync(login.UserId, new UserLoginInfo(login.LoginProvider, login.ProviderKey));
                        }

                        var rolesForUser = await UserManager.GetRolesAsync(user.Id);

                        // Remove the user roles if any.
                        if (rolesForUser.Count() > 0)
                        {
                            foreach (var role in rolesForUser.ToList())
                            {
                                var result = await UserManager.RemoveFromRoleAsync(user.Id, role);
                            }
                        }

                        // Finally remove the user.
                        await UserManager.DeleteAsync(user);

                        ViewBag.ResultMessage = "User successfully removed.";
                    }
                }
            }

            catch (Exception e)
            {
                ViewBag.DeleteError = "The user was unable to be removed from the system. Error Message: " + e.Message;
            }
        }
        /// <summary>
        /// Completely removes a user from the system. This will maintain their content however. Note, the last admin will not be able to be removed.
        /// </summary>
        /// <param name="UserName">The username of the user to be deleted.</param>
        private async Task DeleteUser(string UserName)
        {
            try
            {
                var user = await UserManager.FindByNameAsync(UserName);

                // If we are trying to remove an admin and there is only a single admin left, we CANNOT remove that admin. We don't want to get locked out.
                if (user.Roles.First().Equals(CustomRoles.Administrator) && AccountInfoHelper.NumberAdminsLeft() == 1)
                {
                    ViewBag.ResultMessageError = "Cannot delete " + UserName + " because they are the last admin. This action would result in a lockout.";
                }

                else
                {
                    var logins = user.Logins;

                    // Remove the logins if any.
                    foreach (var login in logins.ToList())
                    {
                        await _userManager.RemoveLoginAsync(login.UserId, new UserLoginInfo(login.LoginProvider, login.ProviderKey));
                    }

                    var rolesForUser = await UserManager.GetRolesAsync(user.Id);

                    // Remove the user's role.
                    if (rolesForUser.Count() > 0)
                    {
                        foreach (var role in rolesForUser.ToList())
                        {
                            var result = await UserManager.RemoveFromRoleAsync(user.Id, role);
                        }
                    }

                    // Finally remove the user.
                    await UserManager.DeleteAsync(user);

                    ViewBag.ResultMessage = "User successfully removed.";
                }
            }

            catch (Exception e)
            {
                ViewBag.ResultMessageError = "The user was unable to be removed from the system. Error Message: " + e.Message;
            }
        }
        public Result ConfirmDeviceOperateSchedule([FromBody] DeviceOperateSchedule schedule)
        {
            var qId = schedule.Id;
            var old = DeviceOperateScheduleHelper.GetOpDetail(qId);

            if (old == null)
            {
                return(Result.GenError <Result>(Error.DeviceOperateScheduleNotExist));
            }

            //if (old.OperatorId != schedule.OperatorId)
            //{
            //    return Result.GenError<Result>(Error.DeviceOperateScheduleOperatorError);
            //}
            if (old.State != DeviceOperateScheduleState.待检验)
            {
                return(Result.GenError <Result>(Error.DeviceOperateScheduleNotComplete));
            }

            var userId         = Request.GetIdentityInformation();
            var account        = AccountInfoHelper.GetAccountInfoByAccount(userId);
            var markedDateTime = DateTime.Now;

            old.MarkedDateTime = markedDateTime;
            old.Remark         = schedule.Remark ?? old.Remark;
            old.ConfirmId      = account?.Id ?? 0;
            old.ConfirmTime    = markedDateTime;
            old.IsPass         = schedule.IsPass;
            if (old.IsPass)
            {
                old.PassCount++;
            }
            else
            {
                old.FailCount++;
            }

            var log = ClassExtension.CopyTo <DeviceOperateScheduleDetail, DeviceOperateLog>(old);

            log.CreateUserId = userId;
            log.Type         = DeviceOperateLogType.检验;
            log.Id           = old.LastLogId;
            DeviceOperateScheduleHelper.ConfirmSchedule(old, log);
            return(Result.GenError <Result>(Error.Success));
        }
Esempio n. 10
0
        public CommonResult Permission()
        {
            var createUserId = Request.GetIdentityInformation();
            var accountInfo  = AccountInfoHelper.GetAccountInfo(createUserId);

            if (accountInfo == null)
            {
                return(Result.GenError <CommonResult>(Error.AccountNotExist));
            }

            //if (!PermissionHelper.CheckPermission(Request.Path.Value))
            //{
            //    return Result.GenError<CommonResult>(Error.NoAuth);
            //}
            var result = new CommonResult {
                data = accountInfo.Permissions
            };

            return(result);
        }
Esempio n. 11
0
        public Result Add([FromBody] IEnumerable <AccountInfo> accountInfos)
        {
            if (accountInfos == null || !accountInfos.Any())
            {
                return(Result.GenError <Result>(Error.ParamError));
            }

            if (accountInfos.Any(x => x.Account.IsNullOrEmpty()))
            {
                return(Result.GenError <Result>(Error.AccountNotEmpty));
            }
            if (accountInfos.Any(x => x.Name.IsNullOrEmpty()))
            {
                return(Result.GenError <Result>(Error.AccountNameNotEmpty));
            }

            if (accountInfos.Any(x => x.Default))
            {
                return(Result.GenError <Result>(Error.AccountNotOperate));
            }

            if (accountInfos.GroupBy(x => x.Account).Any(y => y.Count() > 1))
            {
                return(Result.GenError <Result>(Error.AccountDuplicate));
            }

            var sames = accountInfos.Select(x => x.Account).Distinct();

            if (AccountInfoHelper.GetHaveSame(sames))
            {
                return(Result.GenError <Result>(Error.AccountIsExist));
            }

            var wIds = accountInfos.SelectMany(x => x.Belongs).Distinct();

            if (wIds.Any())
            {
                var cnt = WorkshopHelper.Instance.GetCountByIds(wIds);
                if (cnt != wIds.Count())
                {
                    return(Result.GenError <Result>(Error.WorkshopNotExist));
                }
            }

            var userId         = Request.GetIdentityInformation();
            var markedDateTime = DateTime.Now;
            var rIds           = accountInfos.SelectMany(x => x.RoleList).Distinct();
            var roleList       = RoleHelper.Instance.GetByIds <Role>(rIds);

            foreach (var accountInfo in accountInfos)
            {
                accountInfo.CreateUserId   = userId;
                accountInfo.MarkedDateTime = markedDateTime;
                accountInfo.EmailAddress   = accountInfo.EmailAddress ?? "";
                accountInfo.Password       = !accountInfo.Password.IsNullOrEmpty() ? AccountInfoHelper.GenAccountPwdByOriginalPwd(accountInfo.Account, accountInfo.Password) : "";

                var roleInfos           = roleList.Where(x => accountInfo.RoleList.Contains(x.Id));
                var rolePermissionsList = roleInfos.SelectMany(x => x.PermissionsList).Distinct();
                accountInfo.SelfPermissions = accountInfo.PermissionsList.Distinct().Where(x => !rolePermissionsList.Contains(x)).Join(",");
            }
            AccountInfoHelper.Instance.Add(accountInfos);
            var accs = AccountInfoHelper.GetAccountInfoByAccounts(sames);

            WorkFlowHelper.Instance.OnAddAccount(markedDateTime, accs);
            return(Result.GenError <Result>(Error.Success));
        }
Esempio n. 12
0
        public Result UpdateAccount([FromBody] IEnumerable <AccountInfo> details)
        {
            if (details == null || !details.Any())
            {
                return(Result.GenError <Result>(Error.ParamError));
            }
            if (details.Any(x => x.Id == 0))
            {
                return(Result.GenError <Result>(Error.AccountNotExist));
            }
            var markedDateTime = DateTime.Now;

            foreach (var detail in details)
            {
                detail.MarkedDateTime = markedDateTime;
            }
            if (details.Any(x => x.Name.IsNullOrEmpty()))
            {
                var ids = details.Select(x => x.Id);
                var cnt = AccountInfoHelper.Instance.GetCountByIds(ids);
                if (cnt != details.Count())
                {
                    return(Result.GenError <Result>(Error.AccountNotExist));
                }
                AccountInfoHelper.Enable(details);
            }
            else
            {
                if (details.Any(x => x.Default))
                {
                    return(Result.GenError <Result>(Error.AccountNotOperate));
                }

                if (details.GroupBy(x => x.Name).Any(y => y.Count() > 1))
                {
                    return(Result.GenError <Result>(Error.AccountDuplicate));
                }

                //var sames = accountInfos.Select(x => x.Account);
                var ids = details.Select(x => x.Id).Distinct();
                //if (AccountInfoHelper.GetHaveSame(sames, ids))
                //{
                //    return Result.GenError<Result>(Error.AccountIsExist);
                //}

                var oldAccountInfos = AccountInfoHelper.Instance.GetByIds <AccountInfo>(ids);
                if (oldAccountInfos.Count() != details.Count())
                {
                    return(Result.GenError <Result>(Error.AccountNotExist));
                }

                var rIds     = details.SelectMany(x => x.RoleList).Distinct();
                var roleList = RoleHelper.Instance.GetByIds <Role>(rIds);
                foreach (var detail in details)
                {
                    var old = oldAccountInfos.FirstOrDefault(x => x.Id == detail.Id);
                    detail.EmailAddress = detail.EmailAddress ?? "";
                    detail.DeviceIds    = detail.DeviceIds ?? "";
                    detail.Password     = !detail.NewPassword.IsNullOrEmpty()
                        ? AccountInfoHelper.GenAccountPwdByOriginalPwd(old?.Account ?? "", detail.NewPassword)
                        : old?.Password ?? "";

                    var roleInfos           = roleList.Where(x => detail.RoleList.Contains(x.Id));
                    var rolePermissionsList = roleInfos.SelectMany(x => x.PermissionsList).Distinct();
                    detail.SelfPermissions = detail.PermissionsList.Distinct().Where(x => !rolePermissionsList.Contains(x)).Join(",");
                }

                AccountInfoHelper.Instance.Update(details);
                WorkFlowHelper.Instance.OnUpdateAccount(markedDateTime, details, oldAccountInfos);
            }
            return(Result.GenError <Result>(Error.Success));
        }
Esempio n. 13
0
        public static void Init(IConfiguration configuration)
        {
            RedisHelper.Init(configuration);
            RedisHelper.CloseWrite = _close;
            ServerId   = configuration.GetAppSettings <int>("ServerId");
            IsAnalysis = configuration.GetAppSettings <bool>("Analysis");
            ApiDb      = new DataBase(configuration.GetConnectionString("ApiDb"))
            {
                CloseWrite = _close
            };
            _loads = new Dictionary <string, Action>
            {
                //{PermissionHelper.TableName, PermissionHelper.LoadConfig},
                { "ReadDB", LoadDateBase },
                { PermissionHelper.TableName, PermissionHelper.LoadConfig },
                { PermissionGroupHelper.TableName, PermissionGroupHelper.LoadConfig },
                { NpcProxyLinkServerHelper.TableName, NpcProxyLinkServerHelper.LoadConfig },
            };

            foreach (var action in _loads.Values)
            {
                action();
            }

            GateUrl = configuration.GetAppSettings <string>("GateUrl");
            ErpUrl  = configuration.GetAppSettings <string>("ErpUrl");
            GlobalConfig.LoadGlobalConfig();
            AccountInfoHelper.Init(configuration);
            WorkFlowHelper.Init();
            OldWorkFlowHelper.Init();
            //HMaterialHelper.MaterialChange3();
            //return;
            if (ServerId == 1)
            {
                HKanBanHelper.Init();
            }
            else if (ServerId == 2)
            {
                HNotifyHelper.Init();
                HWarningHelper.Init();
                HOpScheduleHelper.Init();
                //HFlowCardHelper.Init();
                //SimulateHelper.Init();
                HScheduleHelper.Init();
                TimerHelper.Init();
                //HMaterialHelper.Init();
            }
            else if (ServerId == 3)
            {
                AnalysisHelper.Init();
                HKanBanHelper.Init();
            }
            if (!RedisHelper.Exists(IsSetProcessDataKey))
            {
                RedisHelper.SetForever(IsSetProcessDataKey, 1);
            }
            if (!RedisHelper.Exists(IsSetDataIgnoreKey))
            {
                RedisHelper.SetForever(IsSetDataIgnoreKey, 0);
            }

            _loads.Add(HWarningHelper.RedisReloadKey, HWarningHelper.NeedReload);
            _loads.Add(HOpScheduleHelper.RedisReloadKey, HOpScheduleHelper.NeedReload);
            Log.InfoFormat("ServerConfig Done");
        }
        ///// <summary>
        /////  获取某类型的设备
        ///// </summary>
        ///// <param name="deviceCategoryId">设备类型</param>
        ///// <returns></returns>
        //public static string GenDevice(int deviceCategoryId)
        //{
        //    _devices = RedisHelper.Get<List<SmartDeviceProcess>>(DeviceKey);
        //    var 闲置设备 = _devices.Where(x=>x.State == SmartDeviceState.未加工)
        //    return results.FirstOrDefault() ?? "";
        //}

        private static void Simulate()
        {
            var createUserId   = "System";
            var markedDateTime = DateTime.Now;
            var faults         = new List <SmartProcessFault>();
            var processDevices = ServerConfig.ApiDb.Query <SmartFlowCardProcessDevice>("SELECT a.*, b.CategoryId, b.ProcessNumber, b.ProcessData FROM " +
                                                                                       "(SELECT * FROM `t_flow_card_process` WHERE MarkedDelete = 0 AND `State` != @state GROUP BY FlowCardId) a " +
                                                                                       "JOIN (SELECT a.Id, b.CategoryId, b.Process, a.ProcessNumber, a.ProcessData FROM `t_product_process` a " +
                                                                                       "JOIN (SELECT a.Id, b.CategoryId, b.Process FROM `t_process_code_category_process` a " +
                                                                                       "JOIN `t_process` b ON a.ProcessId = b.Id) b ON a.ProcessId = b.Id) b ON a.ProcessId = b.Id WHERE a.MarkedDelete = 0 ORDER BY a.Id;", new { state = SmartFlowCardProcessState.已完成 });
            var categroy0   = new List <int>();
            var categroy_0  = new List <int>();
            var dict        = new Dictionary <int, bool>();
            var processTime = 10;
            var checkTime   = 10;
            var rate        = 85;

            foreach (var processDevice in processDevices)
            {
                if (processDevice.Fault)
                {
                    continue;
                }
                if (processDevice.Before <= 0)
                {
                    faults.Add(new SmartProcessFault
                    {
                        CreateUserId   = createUserId,
                        MarkedDateTime = markedDateTime,
                        FaultTime      = markedDateTime,
                        Type           = ProcessFault.缺少原材料,
                        DeviceId       = processDevice.DeviceId,
                        FlowCardId     = processDevice.FlowCardId,
                        ProcessId      = processDevice.Id,
                    });
                    processDevice.State = SmartFlowCardProcessState.暂停中;
                    processDevice.Fault = true;
                    categroy0.Add(processDevice.Id);
                    continue;
                }

                if (processDevice.CategoryId == 0)
                {
                    if (!dict.ContainsKey(processDevice.CategoryId))
                    {
                        dict.Add(processDevice.CategoryId, true);
                    }
                    if (processDevice.State == SmartFlowCardProcessState.未加工 || processDevice.State == SmartFlowCardProcessState.等待中)
                    {
                        if (dict[processDevice.CategoryId])
                        {
                            if (ArrangeProcess("检验", out var processorId) == ScheduleState.成功)
                            {
                                processDevice.State       = SmartFlowCardProcessState.加工中;
                                processDevice.ProcessorId = processorId;
                                processDevice.StartTime   = markedDateTime;
                                processDevice.Count++;
                                var productProcess = SmartProductProcessHelper.Instance.Get <SmartProductProcess>(processDevice.ProcessId);
                                processDevice.Doing = processDevice.Left < productProcess.ProcessNumber ? processDevice.Left : productProcess.ProcessNumber;
                                categroy0.Add(processDevice.Id);
                            }
                        }
                        else
                        {
                            dict[processDevice.CategoryId] = false;
                        }
                    }
                    else if (processDevice.State == SmartFlowCardProcessState.加工中)
                    {
                        var productProcess = SmartProductProcessHelper.Instance.Get <SmartProductProcess>(processDevice.ProcessId);
                        var endTime        = processDevice.StartTime.AddSeconds((double)(productProcess.TotalSecond < checkTime ? checkTime : productProcess.TotalSecond));
                        if (endTime <= markedDateTime)
                        {
                            processDevice.EndTime = markedDateTime;
                            processDevice.State   = SmartFlowCardProcessState.等待中;
                            var 合格率         = (RateWeight)RandomSeed.GetWeightRandom(SimulateHelper.合格率);
                            var qualified   = processDevice.Doing * 合格率.Rate / 100;
                            var unqualified = processDevice.Doing - qualified;
                            processDevice.Qualified   += qualified;
                            processDevice.Unqualified += unqualified;
                            processDevice.Doing        = 0;
                            var last = processDevice.Left == 0;
                            if (last)
                            {
                                processDevice.State = SmartFlowCardProcessState.已完成;
                                ReleaseProcess(processDevice.ProcessorId);
                                SmartFlowCardProcessHelper.UpdateSmartFlowCardProcessNextBefore(processDevice.FlowCardId, processDevice.Id, processDevice.Qualified);
                                if (processDevice.Rate < rate)
                                {
                                    processDevice.Fault = true;
                                    faults.Add(new SmartProcessFault
                                    {
                                        CreateUserId   = createUserId,
                                        MarkedDateTime = markedDateTime,
                                        FaultTime      = markedDateTime,
                                        Type           = ProcessFault.合格率低,
                                        Remark         = $"合格率{processDevice.Rate.ToRound()}%,低于{rate}%",
                                        DeviceId       = processDevice.DeviceId,
                                        FlowCardId     = processDevice.FlowCardId,
                                        ProcessId      = processDevice.Id,
                                    });
                                }
                            }
                            var processor = AccountInfoHelper.GetAccountInfo(processDevice.ProcessorId)?.Account ?? "";
                            //todo
                            var log = new SmartFlowCardProcessLog(0, processor, markedDateTime, processDevice, qualified, unqualified);
                            SmartFlowCardProcessLogHelper.Instance.Add(log);
                            categroy0.Add(processDevice.Id);
                        }
                    }
                }
                else
                {
                    if (processDevice.State == SmartFlowCardProcessState.加工中)
                    {
                        var weight = (DeviceStateWeight)RandomSeed.GetWeightRandom(故障_暂停概率);
                        if (weight != null)
                        {
                            switch (weight.State)
                            {
                            case SmartDeviceOperateState.故障中:
                                faults.Add(new SmartProcessFault
                                {
                                    CreateUserId   = createUserId,
                                    MarkedDateTime = markedDateTime,
                                    FaultTime      = markedDateTime,
                                    Type           = ProcessFault.设备故障,
                                    DeviceId       = processDevice.DeviceId,
                                    FlowCardId     = processDevice.FlowCardId,
                                    ProcessId      = processDevice.Id,
                                });
                                processDevice.State = SmartFlowCardProcessState.暂停中;
                                processDevice.Fault = true;
                                UpdateDeviceState(processDevice.DeviceId, processDevice.CategoryId, weight.State);
                                categroy_0.Add(processDevice.Id);
                                break;

                            case SmartDeviceOperateState.暂停中:
                                processDevice.State = SmartFlowCardProcessState.暂停中;
                                UpdateDeviceState(processDevice.DeviceId, processDevice.CategoryId, weight.State);
                                categroy_0.Add(processDevice.Id);
                                break;
                            }
                        }
                    }
                    else if (processDevice.State == SmartFlowCardProcessState.未加工)
                    {
                        if (!dict.ContainsKey(processDevice.CategoryId))
                        {
                            dict.Add(processDevice.CategoryId, true);
                        }

                        if (dict[processDevice.CategoryId])
                        {
                            var totalSecond  = processDevice.TotalSecond < processTime ? processTime : processDevice.TotalSecond;
                            var processorId  = processDevice.ProcessorId;
                            var processCount = (int)Math.Ceiling((decimal)processDevice.Before / processDevice.ProcessNumber);
                            if (Arrange(processDevice.CategoryId, processDevice.Id, processDevice.ProcessNumber, processCount, (int)totalSecond,
                                        out var deviceId, ref processorId) == ScheduleState.成功)
                            {
                                processDevice.State       = SmartFlowCardProcessState.等待中;
                                processDevice.DeviceId    = deviceId;
                                processDevice.ProcessorId = processorId;
                                categroy_0.Add(processDevice.Id);
                            }
                            else
                            {
                                dict[processDevice.CategoryId] = false;
                            }
                        }
                    }
                }
            }
        /// <summary>
        /// 完成本次加工
        /// </summary>
        public bool CompleteThisProcess(out int processorId)
        {
            processorId = 0;
            var now = DateTime.Now;
            var f   = false;

            if (State == SmartDeviceOperateState.加工中)
            {
                if (EndTime <= now)
                {
                    f = true;
                    if (ProcessId != 0)
                    {
                        var process = SmartFlowCardProcessHelper.Instance.Get <SmartFlowCardProcess>(ProcessId);
                        if (process != null)
                        {
                            var 合格率         = (RateWeight)RandomSeed.GetWeightRandom(SimulateHelper.合格率);
                            var qualified   = process.Doing * 合格率.Rate / 100;
                            var unqualified = process.Doing - qualified;
                            process.Qualified   += qualified;
                            process.Unqualified += unqualified;
                            process.Doing        = 0;
                            process.EndTime      = now;
                            var second = (int)(process.EndTime - process.StartTime).TotalSeconds;
                            ThisTotalSecond += second;
                            TotalSecond     += second;
                            var last = process.Left == 0;
                            process.State = last ? SmartFlowCardProcessState.已完成 : SmartFlowCardProcessState.等待中;
                            var createUserId = AccountInfoHelper.GetAccountInfo(process.ProcessorId)?.Account ?? "";
                            if (last)
                            {
                                processorId = ProcessorId;
                                NextProcesses.Remove(NextProcesses.First());
                                SmartFlowCardProcessHelper.UpdateSmartFlowCardProcessNextBefore(process.FlowCardId, process.Id, process.Qualified);
                                if (process.Rate < Rate)
                                {
                                    process.Fault = true;
                                    SmartProcessFaultHelper.Instance.Add(new SmartProcessFault
                                    {
                                        CreateUserId   = createUserId,
                                        MarkedDateTime = now,
                                        FaultTime      = now,
                                        Type           = ProcessFault.合格率低,
                                        Remark         = $"合格率{process.Rate.ToRound()}%,低于{Rate}%",
                                        DeviceId       = process.DeviceId,
                                        FlowCardId     = process.FlowCardId,
                                        ProcessId      = process.Id,
                                    });
                                }

                                Init();
                                LastDone = true;
                            }
                            SmartFlowCardProcessHelper.Instance.Update(process);

                            process.StartTime = StartTime;
                            //todo
                            var log = new SmartFlowCardProcessLog(0, createUserId, now, process, qualified, unqualified);
                            SmartFlowCardProcessLogHelper.Instance.Add(log);
                        }
                    }
                    State     = SmartDeviceOperateState.准备中;
                    StartTime = now;
                    EndTime   = now.AddSeconds(30);
                }
            }
            return(f);
        }