<?php

namespace App\Models;

use Carbon\Carbon;
use Dcat\Admin\Traits\HasDateTimeFormatter;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class DistAppearanceBak extends Model
{
	use HasDateTimeFormatter;
    protected $table = 'dist_appearance_bak';

    protected $fillable = [
        'original_table',
        'data',
        'created_at',
        'updated_at',
        'dist_id',
        'appearance_id',
        'version'
    ];

    /*
     * 备份数据dist_appearance_template和dist_appearance_variable到dist_appearance_bak的data字段中
     */
    public static function backupData($appearanceId,$distId)
    {
        $version = generateVersionNumber();
        // 获取需要备份的数据
        $templates = DistAppearanceTemplate::where('dist_id', $distId)->where('appearance_id', $appearanceId)->get();
        $variables = DistAppearanceVariable::where('dist_id', $distId)->where('appearance_id', $appearanceId)->get();

        // 备份模板数据
        foreach ($templates as $template) {
            self::create([
                'dist_id' => $distId,
                'appearance_id' => $appearanceId,
                'original_table' => 'dist_appearance_template',
                'data' => json_encode($template->getAttributes()),
                'created_at' => Carbon::now(),
                'updated_at' => Carbon::now(),
                'version' => $version
            ]);
        }

        // 备份变量数据
        foreach ($variables as $variable) {
            self::create([
                'dist_id' => $distId,
                'appearance_id' => $appearanceId,
                'original_table' => 'dist_appearance_variable',
                'data' => json_encode($variable->getAttributes()),
                'created_at' => Carbon::now(),
                'updated_at' => Carbon::now(),
                'version' => $version
            ]);
        }
    }


    /*
     * 用于恢复指定版本的备份数据
     * @param $version 版本号
     */
    public function restoreDataByVersion($version)
    {
        DB::beginTransaction();

        try {
            // Fetch all backup records with the specified version
            $backupRecords = DistAppearanceBak::where('version', $version)->get();

            // Group records by appearance_id and dist_id
            $groupedRecords = [];
            foreach ($backupRecords as $record) {
                $key = "{$record->appearance_id}-{$record->dist_id}";
                $groupedRecords[$key][] = $record;
            }

            // Process each group
            foreach ($groupedRecords as $key => $records) {
                list($appearanceId, $distId) = explode('-', $key);

                // Delete existing records in dist_appearance_template
                DB::table('dist_appearance_template')
                    ->where('appearance_id', $appearanceId)
                    ->where('dist_id', $distId)
                    ->delete();

                // Delete existing records in dist_appearance_variable
                DB::table('dist_appearance_variable')
                    ->where('appearance_id', $appearanceId)
                    ->where('dist_id', $distId)
                    ->delete();

                // Insert backup data into original tables
                foreach ($records as $record) {
                    $originalTable = $record->original_table;
                    $data = json_decode($record->data, true);

                    if (!is_array($data)) {
                        continue; // Skip if data is not an array
                    }

                    // Insert data into the original table
                    DB::table($originalTable)->insert($data);
                }
            }

            DB::commit();
        } catch (\Exception $e) {
            DB::rollback();
            Log::error('Error restoring data: ' . $e->getMessage());
            throw $e; // Rethrow or handle the exception as needed
        }
    }





}
