<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\SiteAlbum;
use App\Admin\Repositories\SiteAlbumFolder;
use App\Libraries\CommonHelper;
use App\Models\SiteAlbumFolder as SiteAlbumFolderModel;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Admin;
use App\Admin\Repositories\NullRepository;
use Dcat\Admin\Traits\HasUploadedFile;
use function Symfony\Component\Translation\t;

class SiteAlbumController extends AdminController
{
    use HasUploadedFile;
    /**
     * page index
     */
    public function index(Content $content)
    {
        $html =  $content
            ->header(admin_trans( 'admin.album'))
            ->body($this->indexForm());
        $html = $html->render();


        $html = preg_replace('/<form(.*?)method="post"(.*?)>/s', '<form$1method="get"$2>', $html, 1);

        preg_match('/<form[^>]*id="([^"]*)"[^>]*>/', $html, $matches);
        if (isset($matches[1])) {
            $formId = $matches[1]; // 获取 id 的值
           // echo "找到的 form id: " . $formId . "\n";
            // 2. 根据 id 值，删除对应的 JavaScript 代码
            $pattern = '/\$\(\'#' . preg_quote($formId, '/') . '\'\)\.form\(\{.*?\}\);/s';
            $html = preg_replace($pattern, '', $html);
        }

        return $html;
    }

    protected function indexForm()
    {
        return Form::make(new NullRepository(), function (Form $form) {
            $form->action('/site-album');
            $folderModel = new SiteAlbumFolderModel();
            $folderTree = $folderModel->allNodes();
            $form->block(2, function (Form\BlockForm $form) use ($folderTree) {
                $type = [
                    'default'  => [
                        'icon' => true,
                    ],
                ];
                $plugins = ['types'];
                $form->tree()
                    ->setTitleColumn('title')
                    ->nodes($folderTree)
                    ->type($type)
                    ->plugins($plugins)
                    ->width(12,0);
            });

            $form->block(10, function (Form\BlockForm $form)  {
                $form->html($this->grid())->width(12);
            });
        });
    }

    protected function grid()
    {
        return Grid::make(new SiteAlbum(), function (Grid $grid) {
            //默认分页条数
            $grid->paginate(config('admin.per_page'));
            $grid->column('id')->sortable();
            $grid->column('title');
            $grid->column('model');
            $grid->column('order')->sortable();
            $grid->column('enabled')->switch();
            $grid->column('created_at')->sortable();

           // $grid->quickSearch(['title','model']);

            // 筛选
            $grid->filter(function (Grid\Filter $filter) {
                $filter->panel();
                $filter->expand();
                $filter->like('title')->width(2);
                $filter->equal('folder_id',admin_trans_label('folder'))->select(SiteAlbumFolderModel::selectOptions())->width(3);
            });

            $grid->disableViewButton();
            //$grid->showQuickEditButton();
            $grid->disablePerPages();
            $grid->disableRefreshButton();

            $grid->model()->orderBy('order', 'asc')->orderBy('id', 'desc');


            //弹窗大小
            $grid->setDialogFormDimensions('830px','670px');
        });
    }

    protected function form()
    {
        $thisObj = $this;
        return Form::make(new SiteAlbum(), function (Form $form) use ($thisObj) {

            $form->width(9, 1);
            $form->disableViewButton();
            $form->disableViewCheck();
            $form->saving(function (Form $form) use ($thisObj) {
                //处理video
                $videos = $form->input('video');
                if ($videos) {
                    foreach ($videos as $key => $value) {
                        if (empty($value['cover']) && $value['_remove_'] != 1) {
                            //自动生成封面
                            $result = $thisObj->autoGenerateCover($value['video_src']);
                            if ($result['status']) {
                                $videos[$key]['cover'] = $result['path'];
                            } else {
                                return $form->response()->error($result['msg']);
                            }
                        }
                    }
                } else {
                    $videos = [];
                }
                $form->input('video', $videos);
                //处理pdf
                $pdfs = $form->input('pdf');
                $pdfs = empty($pdfs) ? [] : $pdfs;
                $form->input('pdf', $pdfs);
            });
            $form->tab(admin_trans_label('basic_info'), function (Form $form) {
                $form->select('folder_id')->options(SiteAlbumFolder::selectOptions())->required();
                $form->text('title')->required();
                $form->text('model');
            })->tab(admin_trans_label('cover'), function (Form $form) {
                $form->multipleImage('cover')
                    ->retainable()//禁止删OSS图
                    ->sortable() // 可拖动排序
                    ->removable() // 可移除图片
                    ->autoUpload() // 自动上传
                    ->uniqueName()
                    ->limit(config('admin.upload.oss_image.limit'))
                    ->accept(config('admin.upload.oss_image.accept'))
                    ->maxSize(config('admin.upload.oss_image.max_size'))
                    ->dir(config("admin.upload.directory.image").'/uploads/'.date("Ymd"))
                    ->saving(function ($images) use ($form) {
                        return json_encode($images);
                    });
            })->tab(admin_trans_label('en_detail'), function (Form $form) {
                $form->multipleImage('en_detail')
                    ->retainable()//禁止删OSS图
                    ->sortable() // 可拖动排序
                    ->removable() // 可移除图片
                    ->autoUpload() // 自动上传
                    ->uniqueName()
                    ->limit(config('admin.upload.oss_image.limit'))
                    ->accept(config('admin.upload.oss_image.accept'))
                    ->maxSize(config('admin.upload.oss_image.max_size'))
                    ->dir(config("admin.upload.directory.image").'/uploads/'.date("Ymd"))
                    ->saving(function ($images) use ($form) {
                        return json_encode($images);
                    });
            })->tab(admin_trans_label('cn_detail'), function (Form $form) {
                $form->multipleImage('cn_detail')
                    ->retainable()//禁止删OSS图
                    ->sortable() // 可拖动排序
                    ->removable() // 可移除图片
                    ->autoUpload() // 自动上传
                    ->uniqueName()
                    ->limit(config('admin.upload.oss_image.limit'))
                    ->accept(config('admin.upload.oss_image.accept'))
                    ->maxSize(config('admin.upload.oss_image.max_size'))
                    ->dir(config("admin.upload.directory.image").'/uploads/'.date("Ymd"))
                    ->saving(function ($images) use ($form) {
                        return json_encode($images);
                    });
            })->tab(admin_trans_label('video'), function (Form $form) {
                $count = 0;
                $form->hasMany('video', function (Form\NestedForm $form)  use (&$count) {
                    $videos = $form->model()->video;
                    $imgArray = "";
                    if ($videos) {
                        $videos = json_decode($videos,true);
                        foreach ($videos as $key => $value) {
                            if ($value['cover'] && $key == $count-1) {
                                $imgArray = [$value['cover']];
                            }
                        }
                    }
                    $imgHtml = CommonHelper::displayImage($imgArray);
                    $form->html($imgHtml,admin_trans_label('image_preview'));
                    $count++;

                    $form->text('cover',admin_trans_label('video_cover'))->placeholder('为空则自动生成');
                    $form->tradFile('video_src')
                        ->retainable()//禁止删OSS图
                        ->removable() // 可移除图片
                        ->autoUpload() // 自动上传
                        ->uniqueName()
                        ->accept(config('admin.upload.oss_video.accept'))
                        ->maxSize(config('admin.upload.oss_video.max_size'))
                        ->dir(config("admin.upload.directory.video").'/uploads/'.date("Ymd"))
                        ->chunkSize(1024)
                        ->required();
                })->useTable()
                    ->customFormat(function ($data) {return json_decode($data,true);})
                    ->setView('admin.form_custom.hasmanytable')
                    ->saving(function ($input) {
                        $data = [];
                        foreach ($input as $value) {
                            if ($value['_remove_'] != 1){
                                $data[] = ['cover'=>$value['cover'],'video_src'=>$value['video_src']];
                            }
                        }
                        return json_encode($data);
                    });
            })->tab(admin_trans_label('poster'), function (Form $form) {
                $form->multipleImage('poster')
                    ->retainable()//禁止删OSS图
                    ->sortable() // 可拖动排序
                    ->removable() // 可移除图片
                    ->autoUpload() // 自动上传
                    ->uniqueName()
                    ->limit(config('admin.upload.oss_image.limit'))
                    ->accept(config('admin.upload.oss_image.accept'))
                    ->maxSize(config('admin.upload.oss_image.max_size'))
                    ->dir(config("admin.upload.directory.image").'/uploads/'.date("Ymd"))
                    ->saving(function ($images) use ($form) {
                        return json_encode($images);
                    });
            })->tab(admin_trans_label('cert'), function (Form $form) {
                $form->multipleImage('cert')
                    ->retainable()//禁止删OSS图
                    ->sortable() // 可拖动排序
                    ->removable() // 可移除图片
                    ->autoUpload() // 自动上传
                    ->uniqueName()
                    ->limit(config('admin.upload.oss_image.limit'))
                    ->accept(config('admin.upload.oss_image.accept'))
                    ->maxSize(config('admin.upload.oss_image.max_size'))
                    ->dir(config("admin.upload.directory.image").'/uploads/'.date("Ymd"))
                    ->saving(function ($images) use ($form) {
                        return json_encode($images);
                    });
            })->tab(admin_trans_label('pdf'), function (Form $form) {
                 $form->hasMany('pdf', function ($form) {
                     $form->text('pdf_title')->required();
                     $form->tradFile('pdf_src')
                         ->retainable()//禁止删OSS图
                         ->removable() // 可移除图片
                         ->autoUpload() // 自动上传
                         ->uniqueName()
                         ->accept(config('admin.upload.oss_pdf.accept'))
                         ->maxSize(config('admin.upload.oss_pdf.max_size'))
                         ->dir(config("admin.upload.directory.pdf").'/uploads/'.date("Ymd"))
                         ->chunkSize(1024)
                         ->required();
                })->useTable()
                     ->customFormat(function ($data) {
                         return json_decode($data,true);
                     })
                     ->setView('admin.form_custom.hasmanytable')
                     ->saving(function ($input) {
                         $data = [];
                         foreach ($input as $value) {
                             if ($value['_remove_'] != 1){
                                 $data[] = ['pdf_title'=>$value['pdf_title'],'pdf_src'=>$value['pdf_src']];
                             }
                         }
                         return json_encode($data);
                     });
            });
        });
    }

    /*
     * 自动生成视频封面
     */
    private function autoGenerateCover($videoSrc)
    {
        $cover = $videoSrc.'?x-oss-process=video/snapshot,t_2000,f_jpg,h_500,m_fast';
        //TODO 上传到OSS
        $cover = CommonHelper::ossUrl($cover);
        $path = $this->upload($cover,'.jpg');
        return $path;
    }

    private function upload($file,$imgType='.jpg')
    {
        $disk = $this->disk('oss');
        $newName = uniqueCode("video_cover_").$imgType;
        $dir = config("admin.upload.directory.image").'/uploads/'.date("Ymd").'/'.$newName;
        $contents = file_get_contents($file);
        if (!$contents) {
            return ['status'=>false,'msg'=>'图片上传失败,请检查PHP配置'];
        }
        $disk->put($dir, $contents);
        return ['status'=>true,'path'=>$dir];
    }
}
