setName('HandleBatchAccount')->setDescription('处理批量添加的账户数据'); } protected function execute(Input $input, Output $output) { $key = 'handle_batch_account'; $redis = Cache::store('redis')->get($key); if (!$redis) { Cache::set($key, 1, 60); $rs = AccountBatchLogModel::field(true) ->where('status', AccountBatchLogModel::$status_wait_handle) ->findOrEmpty() ->toArray(); if (!empty($rs)) { //处理中 $this->call($rs['id'], AccountBatchLogModel::$status_handle_ing); try { self::$account_username_prefix = env('account_username_prefix'); $temp = AccountModel::field('id,username') ->where('is_del', CommonModel::$del_normal) ->whereLike('username', self::$account_username_prefix . $rs['username_prefix'] . $rs['username_year'] . '____') ->findOrEmpty() ->toArray(); if (!empty($temp)) throw new Exception($temp['username'] . '账号已存在'); $sql = $this->getSql($rs); $num = Db::execute($sql); //处理成功 $this->call($rs['id'], AccountBatchLogModel::$status_handle_success); $output->writeln('处理成功,共添加了' . $num . '个账号'); } catch (Exception $exception) { //处理失败 $this->call($rs['id'], AccountBatchLogModel::$status_handle_fail, $exception->getMessage()); } } Cache::set($key, 0); } } private function getSql(array $rs = []): string { $date = date('Y-m-d H:i:s'); $insert = 'INSERT INTO `' . Config::get('database.connections.mysql.database') . '`.`' . Config::get('database.connections.mysql.prefix') . 'account` (`username`,`pwd`,`salt`,`password`,`company_id`,`card_id`,`status`,`is_del`,`starttime`,`expiretime`,`createrid`,`creater`,`addtime`,`updaterid`,`updater`,`updatetime`) VALUES '; for ($i = 0; $i <= 9999; $i++) { $pwd = randomkeys(6); $salt = randomkeys(6); //拼接SQL语句 $insert .= "('" . self::$account_username_prefix . $rs['username_prefix'] . $rs['username_year'] . str_pad((string)$i, 4, '0', STR_PAD_LEFT) . "','" . $pwd . "','" . $salt . "','" . get_password($pwd, $salt) . "'," . $rs['company_id'] . "," . $rs['card_id'] . "," . AccountModel::$status_not_active . "," . CommonModel::$del_normal . ",'" . $rs['starttime'] . "','" . $rs['expiretime'] . "'," . $rs['createrid'] . ",'" . $rs['creater'] . "','" . $date . "'," . $rs['createrid'] . ",'" . $rs['creater'] . "','" . $date . "'),"; } return substr($insert, 0, -1) . ';'; } //处理结果的回调 private function call(int $id = 0, int $status = 0, string $reason = ''): bool { return (bool)AccountBatchLogModel::where('id', $id) ->save(['status' => $status, 'reason' => $reason, 'updatetime' => date('Y-m-d H:i:s')]); } }