<?php

namespace App\Admin\Repositories;

use App\Models\DistAppearanceTemplate as Model;
use App\Models\SiteAppearanceTemplate;
use Dcat\Admin\Repositories\EloquentRepository;
use Illuminate\Support\Carbon;

class DistAppearanceTemplate extends EloquentRepository
{
    /**
     * Model.
     *
     * @var string
     */
    protected $eloquentClass = Model::class;

    public static function getContent($appearanceId,$distId,$templateCode)
    {
        $appearanceId = intval($appearanceId);
        $distId = intval($distId);
        $data = Model::where('appearance_id', $appearanceId)->where('dist_id', $distId)->where('template_code', $templateCode)->first();
        if ($data) {
            return $data->content;
        }
        return '';
    }
    public static function getTemplateTree($appearance_id,$dist_id)
    {
        $data = Model::where('appearance_id', $appearance_id)->where('dist_id', $dist_id)->orderBy('file_path', 'asc')->get(['id', 'file_name', 'file_path','template_code']);
        return self::buildTree($data->toArray());
    }

    public static function buildTree(array $data) {
        $result = [];
        foreach ($data as $item) {
            // Extract the path and file information
            $path = $item['file_path'];
            $id = $item['id'];
            $file_name = $item['file_name'];

            // Initialize a new entry for this path if it doesn't exist
            if (!isset($result[$path])) {
                $result[$path] = [
                    'id' => 0, // default, as there's no parent ID
                    'dist_id' => 0, // assuming dist_id for path
                    'file_name' => basename($path), // using the directory name for file_name
                    'children' => []
                ];
            }

            // Add the file to the children of the respective path
            $result[$path]['children'][] = [
                'id' => $id,
                'dist_id' => 0, // assuming dist_id
                'file_name' => $file_name,
                'template_code' => $item['template_code']
            ];
        }

        $result = array_values($result);
        return $result;
    }

    /*
     * 保存模板内容
     */
    public static function saveContent($appearanceId,$distId,$templateCode, $content)
    {
        $appearanceId = intval($appearanceId);
        $distId = intval($distId);
        $data = Model::where('dist_id', $distId)->where('appearance_id', $appearanceId)->where('appearance_id', $appearanceId)->where('template_code', $templateCode)->first();
        if ($data) {
            $data->content = $content;
            $data->save();
            //加入模版修改日志
            DistAppearanceTemplateLog::insertLog($appearanceId,$distId,$templateCode,$content);
            return true;
        }
        return false;
    }

    /*
     * 请空指定模板
     */
    public static function deleteTemplates($appearanceId,$distId) {
        Model::deleteTemplates($appearanceId, $distId);
        return true;
    }

    /*
     * 插入模版文件夹
     */
//    public static function insertTemplateFolder($distId,$appearanceId,$filePath,$fileName,$parentId) {
//        $self = new self();
//        $model = $self->model();
//        $model->dist_id = $distId;
//        $model->appearance_id = $appearanceId;
//        $model->file_name = $fileName;
//        $model->parent_id = $parentId;
//        $model->file_type = 0;
//        $model->file_path = $filePath;
//        $model->template_code = uniqueCode('');
//        $model->save();
//        // 获取插入数据的 ID
//        $insertedId = $model->id;
//        return $insertedId;
//    }

    /*
     * 插入模版文件内容
     */
    public static function insertTemplateContent($distId,$appearanceId,$filePath,$fileName,$content) {
        $self = new self();
        $model = $self->model();
        $model->dist_id = $distId;
        $model->appearance_id = $appearanceId;
        $model->file_name = $fileName;
        $model->file_path = $filePath;
        $model->content = $content;
        $model->template_code = uniqueCode('');
        $model->save();
        // 获取插入数据的 ID
        $insertedId = $model->id;
        return $insertedId;
    }

    /*
     * 把原始模板复制给分销商
     */
    public static function copyTemplateToDist($appearanceId,$distId) {
        return Model::copyTemplateToDist($appearanceId, $distId);
    }


    /*
     * 同步模版到正式表上
     */
    public static function syncAppearanceTemplates($appearanceId,$distId)
    {
        $appearanceId = intval($appearanceId);
        $distId = intval($distId);

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

        $tmpModel = new Model();
        $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();
    }

    /*
     * 发布模版与变量
     */
    public static function publish($appearanceId,$distId) {
        //同步模版
        self::syncAppearanceTemplates($appearanceId,$distId);
        //同步变量
        DistAppearanceVariable::syncAppearanceVariables($appearanceId, $distId);
        return true;
    }


}