<?php

namespace App\Models;

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

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

class DistAppearanceVariable extends Model
{
	use HasDateTimeFormatter;
    protected $table = 'dist_appearance_variable';

    protected $fillable = ['dist_id', 'appearance_id', 'variable_name','variable_value','variable_type','created_at','updated_at','template_id'];

    /*
     * 关联到分销商表
     */
    public function distributor()
    {
        return $this->hasOne(DistAdminDistributor::class, 'id', 'dist_id');
    }

    /*
     * 关联到外观表
     */
    public function appearance()
    {
        return $this->hasOne(DistAppearance::class, 'id', 'appearance_id');
    }


    /*
     * 把原始变量复制给分销商
     */
    public static function copyAppearanceVariable($appearanceId, $distId){
        $distId = intval($distId);
        $appearanceId = intval($appearanceId);

        $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_variable` (`dist_id`, `appearance_id`, `variable_name`, `variable_value`, `variable_type`, `created_at`, `updated_at`, `template_code`,`variable_code`)
SELECT {$distId}, `appearance_id`, `variable_name`, `variable_value`, `variable_type`, NOW(), NOW(), `template_code`,`variable_code`
FROM `dist_appearance_variable`
WHERE `dist_id` = {$baseDistId} AND `appearance_id` = {$appearanceId};
        ");
    }

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

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

        // Define criteria for filtering
        $criteria = ['dist_id' => $distId, 'appearance_id' => $appearanceId];

        $tmpModel = $this;
        // Retrieve records from both tables
        $tempVariables = $tmpModel
            ->where($criteria)
            ->get();

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

        foreach ($tempVariables as $tempVariable) {
            $siteVariable = $siteVariables->get($tempVariable->id);

            if ($siteVariable) {
                // If record exists in `site_appearance_variable`, check for updates
                if ($tempVariable->updated_at > $siteVariable->updated_at) {
                    $siteModel
                        ->where('id', $siteVariable->id)
                        ->update([
                            'variable_name' => $tempVariable->variable_name,
                            'variable_value' => $tempVariable->variable_value,
                            'variable_type' => $tempVariable->variable_type,
                            'template_code' => $tempVariable->template_code,
                            'variable_code' => $tempVariable->variable_code,
                            'updated_at' => Carbon::now(),
                        ]);
                }
            } else {
                // If record does not exist, insert it
                $siteModel->insert([
                    'id' => $tempVariable->id,
                    'dist_id' => $tempVariable->dist_id,
                    'appearance_id' => $tempVariable->appearance_id,
                    'variable_name' => $tempVariable->variable_name,
                    'variable_value' => $tempVariable->variable_value,
                    'variable_type' => $tempVariable->variable_type,
                    'template_code' => $tempVariable->template_code,
                    'variable_code' => $tempVariable->variable_code,
                    'created_at' => Carbon::now(),
                    'updated_at' => Carbon::now(),
                ]);
            }
        }

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

    }

}
