<?php

namespace App\Http\Controllers\Admin;

use Crypt;
use Storage;
use App\Models\Setting;
use Illuminate\Http\Request;
use App\Traits\JsonResponseTrait;

class TemplateController extends AdminController
{
    use JsonResponseTrait;
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $filePath = base_path('themes/'.config('setting.theme'));
        $files = json_encode($this->fileTree($filePath)['children']);

        return view('admin.tpl.tpl', compact('files'));
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function lists()
    {
        // 当前主题
        $data = [];
        $theme = config('setting.theme');

        foreach (config('system.template_dirs') as $key => $value) {
            $data[$key] = ['name' => $value, 'isFolder' => true];
            $data[$key]['children'] = $this->getChildren($theme . '/' . $value);
        }

        return $this->success($data);
    }

    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getFile(Request $request)
    {
        $data = Storage::get($request->input('key'));

        if (!Storage::has($request->input('key'))) {
            return $this->error('文件不存在！');
        }

        return $this->success($data);
    }

    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function editFile(Request $request)
    {
        $key = $request->input('key');

        if (!Storage::has($key)) {
            return $this->error('文件不存在！');
        }

        if (!$request->has('value')) {
            return $this->error('请传输内容！');
        }

        Storage::put($key, $request->input('value'));

        return $this->success();
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function brand()
    {
        $brand = Setting::where('lang', 'single')->where('name', 'brand_name')->value('value');

        return $this->success($brand);
    }

    public function getChildren($dir)
    {
        $dirArr = Storage::directories($dir);
        $childrenData = [];

        if ($dirArr) {
            foreach ($dirArr as $key => $value) {
                $childrenData[$key] = ['name' => basename($value), 'isFolder' => true];
                $childrenData[$key]['children'] = $this->getChildren($value);
            }
        }

        $data = $this->getChildrenFiles($dir);

        return array_merge($childrenData, $data);
    }

    public function getChildrenFiles($dir)
    {
        $data = [];
        $files = Storage::files($dir);

        foreach ($files as $key => $value) {
            $data[$key] = [
                'isFolder' => false,
                'key' => $value,
                'name' => basename($value),
                'showDel' => false,
                'showRename' => false,
                'src' => url('themes/' . $value)
            ];
        }

        return $data;
    }

    //获取文件树
    public function fileTree($filePath, $exclude = 'fonts')
    {
        $exclude = (array) $exclude;

        if (filetype($filePath) == 'file') {

            $tempPath = str_replace('/', '-', str_replace(base_path('themes/'.config('setting.theme').'/'), '', $filePath));

            return [
                'text'       => basename($filePath),
                'href'       => url("admin/template/{$tempPath}/edit/"),
                'hrefTarget' => 'filemain',
            ];
        } elseif (filetype($filePath) == 'dir') {
            $data = [
                'text'       => basename($filePath),
                'isFolder'   => true,
            ];

            // 目录 + 文件
            $directories = \File::directories($filePath);
            $files       = \File::files($filePath);
            $glob        = array_merge($directories, $files);

            foreach ($glob as $key => $value) {
                if (!in_array(basename($value), $exclude)) {
                    $data['children'][] = $this->fileTree($value);
                }
            }

            return $data;
        }
       
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $data['name'] = str_replace('-', '/', $id);

        $filePath = base_path('themes/'.config('setting.theme').'/'.$data['name']);
        
        $data['content'] = file_get_contents($filePath);

        $data['url'] = url('admin/template/'.Crypt::encrypt($data['name']));

        return view('admin.tpl.tpl_edit', compact('data'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $filePath = base_path('themes/'.config('setting.theme').'/'.Crypt::decrypt($id));

        \File::put($filePath, $request->input('content'));

        return response()->json(['status' => 'success', 'message' => '修改成功！']);
    }

}
