public function backup()
{

    $tables = Db::query('SHOW TABLES');

    // 设置每批处理的表数量
    $batchSize = 5;
    $outputFilePath = env('root_path') . 'public/upload/export.sql';

    if (is_file($outputFilePath)) {
        unlink($outputFilePath);
    }

    // 打开输出流
    $outputFile = fopen($outputFilePath, 'w');

    $tableCount = count($tables);
    for ($i = 0; $i < $tableCount; $i += $batchSize) {
        $batchTables = array_slice($tables, $i, $batchSize);
        foreach ($batchTables as $table) {
            foreach ($table as $tableName) {
                if (in_array($tableName, ['lz_system_log', 'lz_district'])) {
                    continue;
                }
                $this->writeTableStructure($tableName, $outputFile);
                $this->writeTableData($tableName, $outputFile);
            }
        }
    }

    // 关闭输出流
    fclose($outputFile);

    $content = file_get_contents($outputFilePath);

    // // 下载备份文件
    $download =  new \think\response\Download($content, 200, [
        'Content-Disposition' => 'attachment; filename="' . basename($outputFilePath) . '"',
        'Content-Type' => 'application/octet-stream',
    ]);
    $download->isContent(true);
    $download->mimeType('application/octet-stream');
    $download->name(basename($outputFilePath));
    // 删除服务器端文件
    // unlink($outputFilePath);
    return $download->send();
}

private function writeTableStructure($tableName, $outputFile)
{
    $result = Db::query("SHOW CREATE TABLE `{$tableName}`");
    $structure = "DROP TABLE IF EXISTS `{$tableName}`;\n" . $result[0]['Create Table'] . ";\n\n";
    fwrite($outputFile, $structure);
}

private function writeTableData($tableName, $outputFile)
{
    $batchSize = 1000; // 每次查询的行数
    $offset = 0;
    $output = '';

    do {
        $data = Db::query("SELECT * FROM `{$tableName}` LIMIT {$offset}, {$batchSize}");
        if (!empty($data)) {
            foreach ($data as $row) {
                $row = array_map('addslashes', $row);
                $output .= "INSERT INTO `{$tableName}` VALUES ('" . implode("', '", $row) . "');\n";
            }
            fwrite($outputFile, $output);
            $output = '';
            $offset += $batchSize;
        }
    } while (!empty($data));

    fwrite($outputFile, "\n");
}