<?php

namespace App\Models;

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

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

class DistAppearanceTemplate extends Model
{
	use HasDateTimeFormatter;
    protected $table = 'dist_appearance_template';

    /*
     * 把原始模板复制给分销商
     */
    public static function copyTemplateToDist($appearanceId,$distId) {
        $appearanceId = intval($appearanceId);
        $distId = intval($distId);
        $count = self::where('dist_id', $distId)->where('appearance_id', $appearanceId)->count();
        if ($count > 0) {
            return;
        }
        $baseDistId = config('dictionary.base_dist_id');
        //复制
        DB::statement("
INSERT INTO `dist_appearance_template` (`dist_id`, `appearance_id`, `file_name`, `file_path`, `content`, `created_at`, `updated_at`,  `template_code`)
SELECT {$distId}, `appearance_id`, `file_name`, `file_path`, `content`, NOW(), NOW(), `template_code`
FROM `dist_appearance_template`
WHERE `dist_id` = {$baseDistId} AND `appearance_id` = {$appearanceId};
        ");
    }

    public static function deleteTemplates($appearanceId,$distId) {
        self::where('dist_id',$distId)->where('appearance_id',$appearanceId)->delete();
        return true;
    }



    public function syncAppearanceTemplates($appearanceId,$distId)
    {
        $appearanceId = intval($appearanceId);
        $distId = intval($distId);

        $criteria = ['dist_id' => $distId, 'appearance_id' => $appearanceId];

        $tmpModel = $this;
        $tempRecords = $tmpModel
            ->where($criteria)
            ->get();

        $siteModel = new SiteAppearanceTemplate();
        $siteRecords = $siteModel
            ->where($criteria)
            ->get()
            ->keyBy('id'); // Use IDs as keys for easier comparison


        foreach ($tempRecords as $tempRecord) {
            $siteRecord = $siteRecords->get($tempRecord->id);
            if ($siteRecord) {
                // If record exists in `site_appearance_template`, check for updates
                if ($tempRecord->updated_at > $siteRecord->updated_at) {
                    $siteModel->where('id', $siteRecord->id)
                        ->update([
                            'file_name' => $tempRecord->file_name,
                            'file_path' => $tempRecord->file_path,
                            'content' => $tempRecord->content,
                            'updated_at' => Carbon::now(),
                        ]);
                }
            } else {
                // If record does not exist, insert it
                $siteModel->insert([
                    'id' => $tempRecord->id,
                    'dist_id' => $tempRecord->dist_id,
                    'appearance_id' => $tempRecord->appearance_id,
                    'file_name' => $tempRecord->file_name,
                    'file_path' => $tempRecord->file_path,
                    'content' => $tempRecord->content,
                    'created_at' => Carbon::now(),
                    'updated_at' => Carbon::now(),
                    'template_code' => $tempRecord->template_code,
                ]);
            }
        }

        // Delete records from `site_appearance_template` that don’t match `dist_id=1` and `appearance_id=1`
        $siteModel
            ->where($criteria)
            ->whereNotIn('id', $tempRecords->pluck('id')->toArray())
            ->delete();
    }

}