<?php

namespace App\Admin\Controllers\Content;

use App\Models\Category;
use App\Models\Policy;
use App\Http\Controllers\Controller;
use App\Models\PolicyCategory;
use App\Models\PolicyProperty;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use Illuminate\Support\Facades\Input;

class PolicyController extends Controller
{
    use HasResourceActions;

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->header('政策管理')
            ->description(' ')
            ->body($this->grid());
    }

    /**
     * Show interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header('政策管理')
            ->description(' ')
            ->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->header('政策管理')
            ->description(' ')
            ->body($this->editForm($id)->edit($id));
    }
    public function update($id)
    {
        return $this->editForm($id)->update($id);
    }
    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header('政策管理')
            ->description(' ')
            ->body($this->form());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Policy);
        $grid->id('ID');
        $grid->model()->orderBy('article_order', 'DESC')->orderBy('created_at', 'DESC');

        $grid->column('文章标题')->display(function () {
            $style="color:".$this->tit_color.';';
            if ($this->tit_b=='1') {
                $style .='font-weight:bold;';
            }

            $cate = PolicyCategory::where(array('id'=>$this->parentid))->first();
            if ($this->parentid=='0') {
                $params = '?parentid='.$this->type_id;
            } else {
                $params = '?parentid='.$this->parentid;
            }
            $title_url = url(admin_base_path().'/content/policy'.$params);
            $pbstr='';
            if($this->is_display==0){
                $pbstr= '<span style="color:#999999">&nbsp;&nbsp;&nbsp;&nbsp;[已屏蔽]</span>';
            }

            $title_url1 = url('content/policys/show/'.$this->id);
            if ($cate) {
                return $pbstr.'<a href='.$title_url.' style="color: #006699;">['.$cate->categoryname.']</a> <a target="_blank"  href='.$title_url1.'><span style="'.$style.'">'.$this->title.'</span></a>';
            } else {
                return $pbstr.'<span style="'.$style.'">'.$this->title.'</span>';
            }
        })->width(200);

        $grid->policyproperty()->categoryname('政策层次');
        $grid->article_order('排序');
        $grid->click('点击');
        $grid->created_at('添加时间');
        $grid->disableCreateButton(false);
        $grid->actions(function ($actions) {
            $actions->disableEdit(false);
            $actions->disableDelete(false);
        });
        $grid->tools(function ($tools) {
            $tools->batch(function ($batch) {
                $batch->disableDelete(false);
            });
        });
        $grid->filter(function ($filter) {
            $filter->equal('id', 'ID');
            $filter->like('title', '标题');

            $policy_cates = PolicyCategory::where(['parent_id'=>0])->orderBy("id", 'asc')->get()->pluck('categoryname', 'id');
            $filter->where(function ($query) {
                $query->where('parentid', '=', "{$this->input}")->orWhere('type_id', '=', "{$this->input}");
            }, '政策分类', 'parentid')->select($policy_cates);

            $policy_propertys = PolicyProperty::select()->orderBy("id", 'asc')->get()->pluck('categoryname', 'id');
            $filter->where(function ($query) {
                $query->where('focos', '=', "{$this->input}");
            }, '政策层次', 'focos')->select($policy_propertys);

            $date3   = date('Y-m-d', strtotime("-3 day"));
            $date7   = date('Y-m-d', strtotime("-7 day"));
            $date30  = date("Y-m-d", strtotime("-1 month"));
            $date180 = date("Y-m-d", strtotime("-6 month"));
            $date360 = date("Y-m-d", strtotime("-1 year"));
            $date_option = array(
                ''    => '不限',
                $date3   => '三天内',
                $date7   => '一周内',
                $date30  => '一月内',
                $date180 => '半年内',
                $date360 => '一年内',
            );
            $filter->where(function ($query) {
                $query->where('created_at', '>=', "{$this->input}");
            }, '添加时间', 'created_at')->radio($date_option);
        });
        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Policy::findOrFail($id));

        $show->id('ID');
        $show->created_at('Created at');
        $show->updated_at('Updated at');

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new Policy);
        $form->text('title', '标题')->rules('required|max:100', array('required'=>'标题不能为空。','max'=>'标题长度不能大于100。'))->setWidth(4)->setMustMark();
        $form->color('tit_color', '标题颜色')->rules('required|regex:/^#[a-fA-F0-9]{6}$/', array('required'=>'标题颜色不能为空。','regex'=>'标题颜色格式不正确。'))->default('#000000');

        $cate_option = PolicyCategory::selectOptions(function ($query) {
            return $query->orderBy('category_order', 'desc')->orderBy('created_at', 'desc');
        });

        unset($cate_option[0]);
        $form->select('type_id', '政策分类')->options($cate_option)->default(key($cate_option))->rules('required', array('required'=>'请选择政策分类。'))->setWidth(4)->setMustMark();

        $policyProperty = PolicyProperty::select()->pluck('categoryname', 'id');
//        $policyProperty[0] ='不限';
        $arr = array(
            '1' => 'RC_category_fj',
            '2' => 'RC_category_qz',
            '7' => 'RC_category_jj',
            '8' => 'RC_category'
        );
        $form->select('focos', '政策层次')->options($policyProperty)->load('level_ids', admin_base_path('/content/policys/treats/category'))->rules("required")->setMustMark();
        $form->multipleSelect('level_ids', '面向人才')->rules(['required'], ['required'=>'请填写面向人才'])->setMustMark();

        $form->image('small_img', '缩略图')->uniqueName()->rules('image|mimes:jpeg,bmp,png', array('image'=>'缩略图请选择图片文件。','mimes'=>'请选择jpeg,bmp,png格式的缩略图上传。'))->setWidth(3);
        $form->editor('content', '内容')->rules('required', array('required'=>'内容不能为空。'))->setMustMark();
        $display_option = [
            'on'  => ['value' => 1, 'text' => '是', 'color' => 'success'],
            'off' => ['value' => 0, 'text' => '否', 'color' => 'danger'],
        ];
        $form->switch('is_display', '是否显示')->default(1)->states($display_option)->setMustMark();
        $form->switch('tit_b', '标题加粗')->states($display_option)->setMustMark();
//        $form->date('addtime', '发布日期')->format('YYYY-MM-DD')->rules('required|date', array('required'=>'发布日期不能为空。', 'date'=>'发布日期格式不正确。'));
        $form->number('article_order', '新闻排序')->min(0)->default(255)->rules('required', array('required'=>'新闻排序不能为空。'))->help('(数字越大越靠前)');
        $form->text('author', '作者')->rules('max:20', array('max'=>'作者长度不能大于20。'))->setWidth(3);
        $form->text('source', '来源')->rules('max:20', array('max'=>'来源长度不能大于20。'))->setWidth(3);
        $form->url('is_url', '外部链接')->rules('max:250', array('max'=>'外部链接长度不能超过250。'))->help('(请输入包含http://或https://的完整链接)');
        $form->text('seo_keywords', 'Keywords')->placeholder('合理设置Keywords有利于搜索引擎排名')->rules('max:80', array('max:Keywords不能大于80个字符。'));
        $form->textarea('seo_description', 'Description')->placeholder('合理设置Description有利于搜索引擎排名')->rules('max:80', array('max'=>'Description不能大于80个字符。'));
        $form->hidden('addtime');//添加时间
        $form->hidden('parentid');//政策大类
        $form->hidden('level_name');//面向人才
        $form->hidden('level_id');//面向人才
        $form->ignore(['level_ids']);

        $form->saving(function (Form $form){
            //设置添加时间
            $form->addtime=time();

//            设置政策大类
            $policyCategory= PolicyCategory::where(['id'=>$form->type_id])->first();

            if($policyCategory->parent_id==0){
                $form->parentid=$form->type_id;
            }else{
                $form->parentid=$policyCategory->parent_id;
            }

            $level_id= Input::get('level_ids');
            $level_id = array_filter($level_id);
            $form->level_id=implode(',',$level_id);

            $levels=Category::whereIn('id',$level_id)->select('demand')->get()->toArray();
            $form->level_name=implode(",", array_column($levels, 'demand'));

        });
        return $form;
    }
    protected function editForm($id)
    {
        $form = new Form(new Policy);
        $policyData = Policy::where('id', $id)->first()->toArray();
        $form->text('title', '标题')->rules('required|max:100', array('required'=>'标题不能为空。','max'=>'标题长度不能大于100。'))->setWidth(4)->setMustMark();
        $form->color('tit_color', '标题颜色')->rules('required|regex:/^#[a-fA-F0-9]{6}$/', array('required'=>'标题颜色不能为空。','regex'=>'标题颜色格式不正确。'))->default('#000000');

        $cate_option = PolicyCategory::selectOptions(function ($query) {
            return $query->orderBy('category_order', 'desc')->orderBy('created_at', 'desc');
        });

        unset($cate_option[0]);
        $form->select('type_id', '政策分类')->options($cate_option)->default(key($cate_option))->rules('required', array('required'=>'请选择政策分类。'))->setWidth(4)->setMustMark();

        $policyProperty = PolicyProperty::select()->pluck('categoryname', 'id');
//        $policyProperty[0] ='不限';
        $arr = array(
            '1' => 'RC_category_fj',
            '2' => 'RC_category_qz',
            '7' => 'RC_category_jj',
            '8' => 'RC_category'
        );
        $form->select('focos', '政策层次')->options($policyProperty)->load('level_ids', admin_base_path('/content/policys/treats/category'))->rules("required")->setMustMark();

        $form->multipleSelect('level_ids', '面向人才')->options(Category::categoryType($arr[$policyData['focos']]))->default(explode(",", $policyData['level_id']))->rules(['required'], ['required'=>'请填写面向人才'])->setMustMark();

        $form->image('small_img', '缩略图')->uniqueName()->rules('image|mimes:jpeg,bmp,png', array('image'=>'缩略图请选择图片文件。','mimes'=>'请选择jpeg,bmp,png格式的缩略图上传。'))->setWidth(3);
        $form->editor('content', '内容')->rules('required', array('required'=>'内容不能为空。'))->setMustMark();
        $display_option = [
            'on'  => ['value' => 1, 'text' => '是', 'color' => 'success'],
            'off' => ['value' => 0, 'text' => '否', 'color' => 'danger'],
        ];
        $form->switch('is_display', '是否显示')->states($display_option)->setMustMark();
        $form->switch('tit_b', '标题加粗')->states($display_option)->setMustMark();
//        $form->date('created_at', '发布日期')->format('YYYY-MM-DD')->rules('required|date', array('required'=>'发布日期不能为空。', 'date'=>'发布日期格式不正确。'));
        $form->number('article_order', '新闻排序')->min(0)->default(0)->rules('required', array('required'=>'新闻排序不能为空。'))->help('(数字越大越靠前)');
        $form->text('author', '作者')->rules('max:20', array('max'=>'作者长度不能大于20。'))->setWidth(3);
        $form->text('source', '来源')->rules('max:20', array('max'=>'来源长度不能大于20。'))->setWidth(3);
        $form->url('is_url', '外部链接')->rules('max:250', array('max'=>'外部链接长度不能超过250。'))->help('(请输入包含http://或https://的完整链接)');
        $form->text('seo_keywords', 'Keywords')->placeholder('合理设置Keywords有利于搜索引擎排名')->rules('max:80', array('max:Keywords不能大于80个字符。'));
        $form->textarea('seo_description', 'Description')->placeholder('合理设置Description有利于搜索引擎排名')->rules('max:80', array('max'=>'Description不能大于80个字符。'));
        $form->hidden('addtime');//添加时间
        $form->hidden('parentid');//政策大类
        $form->hidden('level_name');//面向人才
        $form->hidden('level_id');//面向人才
        $form->ignore(['level_ids']);

        $form->saving(function (Form $form){

            //设置政策大类
            $policyCategory= PolicyCategory::where(['id'=>$form->type_id])->first();

            if($policyCategory->parent_id==0){
                $form->parentid=$form->type_id;
            }else{
                $form->parentid=$policyCategory->parent_id;
            }

            $level_id= Input::get('level_ids');
            $level_id = array_filter($level_id);
            $form->level_id=implode(',',$level_id);

            $levels=Category::whereIn('id',$level_id)->select('demand')->get()->toArray();
            $form->level_name=implode(",", array_column($levels, 'demand'));

        });

        return $form;
    }
    public function destroy($id)
    {
        $ids = array();
        if ($id) {
            $ids = explode(',', $id);
        }
        if (!$ids) {
            return admin_toastr('请勾选需要删除的政策', 'error');
        }
        \DB::beginTransaction();
        try {
            Policy::whereIn('id', $ids)->delete();
            $data = [
                'status'  => true,
                'message' => '删除成功!',
            ];
            \DB::commit();
            return response()->json($data);
        } catch (\Exception $e) {
            \DB::rollback();
            $data = [
                'status'  => false,
                'message' => '删除失败!',
            ];
            return response()->json($data);
        }
    }

}