<?php

namespace App\Distributor\Controllers;

use App\Distributor\Repositories\DistAdminUsersSetting;
use App\Distributor\Repositories\DistAppearanceTemplate;
use App\Distributor\Repositories\SitePages;
use App\Models\SitePages as Model;
use App\Distributor\Repositories\SitePagesTag;
use App\Libraries\CommonHelper;
use DateTime;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Models\Permission;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Admin;
use Dcat\Admin\Widgets\Form as widgetsForm;

class SitePagesController extends AdminDistController
{
    public function title()
    {
        $pageType = getTempValue('location');
        if ($pageType == 0) {
            return admin_trans( 'admin.pages');
        } else {
            return admin_trans( 'admin.landing_page');
        }
    }

    /**
     * page index
     */
    public function index(Content $content)
    {
        if (isset($_GET['location'])) {
            $location =  $_GET['location'] == 1 ? 1 : 0;
            //保存临时变量
            setTempValue('location', $location);
        } else {
            $location = getTempValue('location');
            return redirect('/dist/site-pages?location='.$location);
        }

        return $content
            ->header($this->title())
            ->description('')
            ->breadcrumb(['text'=>'','url'=>''])
            ->body($this->grid());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        //页面类型
        return Grid::make(SitePages::with(['pagesTag']), function (Grid $grid) {
            //页面类型
            $location = getTempValue('location');
            //默认分页条数
            $grid->paginate(config('admin.per_page'));
            $grid->column('id')->display(function () {
                return $this->_index+1;
            });
            $grid->column('title')->width('25%');
            $grid->column('pagesTag',admin_trans_label('tags'))->pluck('name')->label()->width('15%');
            $grid->column('cover_image')->display(function ($image) {
                // 开始生成 HTML
                $dataImages = [$image];
                return CommonHelper::displayImage($dataImages,100);
            })->width('10%');
            //发布日期
            $grid->column('post_date')->display(function ($date) {
                $dateTime = new DateTime($date);
                $date = $dateTime->format('Y-m-d');
                return $date;
            });
            //状态
            $grid->column('status')->using(admin_trans_array(config('dictionary.pages_status')));
            $grid->column('updated_at')->sortable();
            $grid->column('created_at');
            $grid->filter(function (Grid\Filter $filter) {
                $filter->panel();
                $filter->expand();
                $filter->like('title')->width(2);
                $filter->equal('pagesTag.id',admin_trans_label('tags'))->select('api/tag')->width(2);
            });
            //权限与条件
            $grid->model()->where('dist_id', getDistributorId())->where('page_type', $location)->orderBy('id', 'desc');
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, Model::with(['pagesTag']), function (Show $show) {
            //页面类型
            $location = getTempValue('location');
            $pagesTag  = $show->model()->pagesTag->toArray();
            $show->field('title');
            if ($location == 1) {
                $show->field('template_file');
            }
            $show->field('pagesTag',admin_trans_label('tags'))->as(function ($value) use ($pagesTag) {
                return array_column($pagesTag,'name');
            })->label();
            $show->field('author');
            $show->field('post_date')->as(function ($date) {
                $dateTime = new DateTime($date);
                $date = $dateTime->format('Y-m-d');
                return $date;
            });
            $show->field('cover_image')->as(function ($image) {
                // 开始生成 HTML
                $dataImages = [$image];
                return CommonHelper::displayImage($dataImages,150);
            })->unescape();
            $show->field('content')->unescape();
            $show->field('seo_title');
            $show->field('seo_keywords');
            $show->field('seo_description');
            $show->field('slug',admin_trans_label('url_and_handle'))->as(function ($value) {
                return getSiteDomain().config('dictionary.site_url.pages').'/'.$value;
            });
            $show->field('status')->using(admin_trans_array(config('dictionary.pages_status')));
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(SitePages::with(['pagesTag']), function (Form $form) {
            //页面类型
            $location = getTempValue('location');
            $form->text('title')->required();
            if ($location == 1) {
                $options = DistAppearanceTemplate::getLandingPageTemplateOptions();
                $form->select('template_file')->options($options)->default(current($options))->required();
            }
            $form->text('author');
            $form->date('post_date')->format('YYYY-MM-DD')->default(date('Y-m-d'))->required();
            $form->tags('pagesTag', '文章标签')
                ->setView('admin.form_custom.tags')
                ->pluck('name', 'name') // name 为需要显示的 Tag 模型的字段，id 为主键
                ->options(SitePagesTag::all())
                ->saving(function ($value) {
                    $value = SitePagesTag::handleTags($value);
                    return $value;
                });
            $form->image("cover_image")
                ->retainable()//禁止删OSS图
                ->autoUpload()
                ->uniqueName()
                ->accept(config('distributor.upload.oss_image.accept'))
                ->maxSize(config('distributor.upload.oss_image.max_size'))
                ->dir(config("distributor.upload.directory.image").'/pages/'.date("Ymd"));
            $form->editor('content')->required();
            //SEO
            $form->text('seo_title');
            $form->text('seo_keywords');
            $form->text('seo_description');
            $form->text('slug',admin_trans_label('url_and_handle'))->width(4, 2)->prepend(getSiteDomain().config('dictionary.site_url.pages').'/');
            $form->switch('status',admin_trans_label('publish'))->default(1);
            //隐藏字段
            $form->hidden('dist_id',);
            $form->hidden('page_type');

            //新建时插入JS
            $form->creating(function (Form $form) {
                CommonHelper::seoReplace();
            });

            //保存前
            $form->saving(function (Form $form) use ($location) {
                //强制写死dist_id
                $form->dist_id = getDistributorId();
                //强制写死page_type
                $form->page_type = $location;
                //slug配置是否重复
                $id = $form->getKey();

                $form->slug=trim($form->slug);
                if ($form->slug != '') {
                    //把slug中的空格替换成-，多个空格在一起只用一个-，大写字母转换成小写
                    $form->slug = preg_replace('/\s+/', '-', $form->slug);
                    $form->slug = strtolower($form->slug);

                    if (SitePages::isRepeatedSlug($id, $form->slug)) {
                        //slug重复
                        return $form->response()->error(admin_trans_label('url_repeated'));
                    }
                }
                //当slug为空时生成slug
                if ($form->slug == '') {
                    $form->slug = SitePages::generateSlug($form->title,$id);
                }
                //seo_title不能为空
                if ($form->seo_title == '') {
                    $form->seo_title = $form->title;
                }
            });
        });
    }
}
