<?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_name', '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' => trim($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) {
            $currentContent = $content;
            $previousContent = $data->content;
            //保存
            $data->content = $content;
            $data->save();
            //加入模版修改日志
            DistAppearanceTemplateLog::insertLog($appearanceId,$distId,$data->file_name,$data->file_path,$templateCode,$currentContent,$previousContent);
            return true;
        }
        return false;
    }

    public static function addDelTree($appearanceId,$distId,$fileId,$fileName, $filePath,$type) {
        if (empty($appearanceId) || empty($distId)) {
            return ['status' => 0,'msg' => 'Missing required parameters'];
        }
        $model = new Model();
        if ($type == 'add') {
            $count = $model->where('appearance_id', $appearanceId)->where('dist_id', $distId)->where('file_name', $fileName)->count();
            if ($count > 0) {
                return ['status' => 0,'msg' => 'File name already exists'];
            }
            $filePath = empty($filePath)?'':$filePath;
            $model = new Model();
            $model->dist_id = $distId;
            $model->appearance_id = $appearanceId;
            $model->file_name = $fileName;
            $model->file_path = $filePath;
            $model->content = '';
            $model->template_code = uniqueCode('');
            $model->save();
            return ['status' => 1];
        } else {
            $row = $model->where('appearance_id', $appearanceId)->where('dist_id', $distId)->where('id', $fileId)->first();
            if ($row) {
                $row->delete();
                //加入模版修改日志
                DistAppearanceTemplateLog::insertLog($appearanceId,$distId,$row->file_name,$row->file_path,$row->template_code,'',$row->content);
                return ['status' => 1];
            }
            return ['status' => 0,'msg' => 'File ID not found'];
        }
    }

    /*
     * 请空指定模板
     */
    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)
    {
        $model = new Model();
        return $model->syncAppearanceTemplates($appearanceId,$distId);
    }




}
