<?php

namespace App\Models;

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();
    }

}
