<?php

namespace App\Admin\Controllers\Content;

use App\Admin\Extensions\Form\ValidateForm;
use App\Http\Controllers\Controller;
use App\Models\Hrtools;
use App\Models\HrtoolsCategory;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;

class HrtoolsController extends Controller
{
    use HasResourceActions;

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->header('HR工具箱')
            ->description(' ')
            ->body($this->grid());
    }

    /**
     * Show interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header('HR工具箱')
            ->description(' ')
            ->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->header('HR工具箱')
            ->description(' ')
            ->body($this->editForm()->edit($id));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header('HR工具箱')
            ->description(' ')
            ->body($this->form());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Hrtools);

        $grid->model()->orderBy('list_order', 'desc')->orderBy('created_at', 'DESC');
        $grid->id('ID');
        $grid->title('名称')->display(function () {
            $style="color:".$this->tit_color.';';
            if ($this->tit_b=='1') {
                $style .='font-weight:bold;';
            }
            return '<span style="'.$style.'">'.$this->title.'</span>';
        })->width(250);
        $grid->column('文件路径')->display(function () {
            if (preg_match('/^files\//', $this->file_url)) {
                $filepath = public_path('uploads').'/'.$this->file_url;
                if (file_exists($filepath)) {
                    return '<a href="download/'.$this->file_url.'">'.$this->file_url.'</a>';
                } else {
                    return '';
                }
            } else {
                return '<a href="'.$this->file_url.'">'.$this->file_url.'</a>';
            }
        })->width(250);
        $grid->show_category()->category_name('所属分类');
        $grid->list_order('排序');

        $grid->created_at('添加时间');
        //新增按钮
        if (Admin::user()->can('content_hrtools_list_create')) {
            $grid->disableCreateButton(false);
        }
        //批量删除
        if (Admin::user()->can('content_hrtools_list_delete')) {
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    $batch->disableDelete(false);
                });
            });
        } else {
            $grid->disableRowSelector();
        }
        $grid->actions(function ($actions) {
            if (Admin::user()->can('content_hrtools_list_edit')) {
                $actions->disableEdit(false);
            }
            if (Admin::user()->can('content_hrtools_list_delete')) {
                $actions->disableDelete(false);
            }
        });

        $grid->filter(function ($filter) {
            $filter->disableIdFilter();
            $filter->like('title', '名称');
            $cate_option = HrtoolsCategory::orderBy('list_order', 'desc')->orderBy('created_at', 'desc')->pluck('category_name', 'id');
            if ($cate_option) {
                $cate_option = $cate_option->toArray();
                $cate_option = array(''=>'不限') + $cate_option;
            } else {
                $cate_option = array(''=>'不限');
            }
            $filter->equal('type_id', '所属分类')->select($cate_option);
        });

        return $grid;
    }

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

        $show->id('ID');
        $show->title('名称');
        $show->tit_color('标题颜色')->as(function ($tit_color) {
            $html = '<i style="background-color: '.$tit_color.';padding: 5px 15px;"></i>';
            return $html;
        })->setEscape(false);
        $show->tit_b('标题加粗')->as(function ($tit_b) {
            return $tit_b?'是':'否';
        });
        $show->file_url('文件路径');
        /*$show->show_category()->category_name('所属分类');*/
        $show->show_category("所属分类")->as(function ($show_category) {
            return $show_category->category_name;
        });
        $show->list_order('排序');
        $show->created_at('添加时间');
        $show->updated_at('更新时间');

       /* $show->panel()
            ->tools(function ($tools) {
                $tools->disableEdit();
                $tools->disableDelete();
            });*/

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new ValidateForm(new Hrtools);

        $form->text('title', '名称')->rules('required|max:25', array('required'=>'名称不能为空。', 'max'=>'名称长度不能大于25个字符。'))->setWidth(4)->setMustMark();
        $form->color('tit_color', '名称颜色')->default('#000000');
        $display_option = [
            'on'  => ['value' => 1, 'text' => '是', 'color' => 'success'],
            'off' => ['value' => 0, 'text' => '否', 'color' => 'danger'],
        ];
        $form->switch('tit_b', '名称加粗')->states($display_option)->default(0)->setMustMark();
        $cate_option = HrtoolsCategory::orderBy('list_order', 'desc')->orderBy('created_at', 'desc')->pluck('category_name', 'id');
        $form->select('type_id', '所属分类')->options($cate_option)->rules('required', array('required'=>'请选择所属分类。'))->setWidth(4)->setMustMark();

        $form->file('up_file', '上传文件')->uniqueName()
             ->rules('required_without:url|mimes:doc,docx,ppt,xls,rtf', array('required_without'=>'上传文件或者文件路径填写一项。','mimes'=>'上传文件格式不正确。'))
             ->help('(只能上传doc/ppt/xls/rtf文件)')
             ->setMustMark()
             ->setWidth(4);
        $form->url('url', '或填写文件路径')
             ->rules('required_without:up_file', array('required_without'=>'上传文件或者文件路径填写一项。'))
             ->help('(请输入完整文件路径,如:http://www.91caiqing.com/123.doc)')
             ->setWidth(4);
        $form->number('list_order', '排序')->min(0)->default(0)
             ->rules('required', array('required'=>'排序不能为空。'))
             ->attribute('maxlength', '10')->help('(数字越大越靠前)')->setMustMark();

        $form->footer(function ($footer) {
            $footer->disableViewCheck();
            $footer->disableEditingCheck();
            $footer->disableCreatingCheck();
            $footer->disableReset();
        });
        return $form;
    }
    protected function editForm()
    {
        $form = new ValidateForm(new Hrtools);

        $form->text('title', '名称')->rules('required|max:25', array('required'=>'名称不能为空。', 'max'=>'名称长度不能大于25个字符。'))->setWidth(4)->setMustMark();
        $form->color('tit_color', '名称颜色')->default('#000000');
        $display_option = [
            'on'  => ['value' => 1, 'text' => '是', 'color' => 'success'],
            'off' => ['value' => 0, 'text' => '否', 'color' => 'danger'],
        ];
        $form->switch('tit_b', '名称加粗')->states($display_option)->default(0)->setMustMark();
        $cate_option = HrtoolsCategory::orderBy('list_order', 'desc')->orderBy('created_at', 'desc')->pluck('category_name', 'id');
        $form->select('type_id', '所属分类')->options($cate_option)->rules('required', array('required'=>'请选择所属分类。'))->setWidth(4)->setMustMark();
        $form->file('up_file', '上传文件')->uniqueName()->rules('mimes:doc,docx,ppt,xls,rtf', array('mimes'=>'上传文件格式不正确。'))->help('(只能上传doc/ppt/xls/rtf文件)')->setWidth(4)->setMustMark()->options(['layoutTemplates' => ['actionDelete'    => '']]);
        $form->url('url', '或填写文件路径')->help('(请输入完整文件路径,如:http://www.baidu.com/123.doc)')->setWidth(4);
        $form->number('list_order', '排序')->min(0)->default(0)->rules('required', array('required'=>'排序不能为空。'))->attribute('maxlength', '10')->help('(数字越大越靠前)')->setMustMark();

        $form->footer(function ($footer) {
            $footer->disableViewCheck();
            $footer->disableEditingCheck();
            $footer->disableCreatingCheck();
            $footer->disableReset();
        });
        $form->tools(function (Form\Tools $tools) {
            $tools->disableDelete();
            $tools->disableView();
        });
        return $form;
    }
    public function update($id)
    {
        $data=$this->editForm()->getValidateInput();
        $time = date('Y-m-d H:i:s', time());
        $up_file = null;
        $url = $data['url'];
        if (array_key_exists('up_file', $data)) {
            $up_file = $data['up_file'];
        }
        $file_url = $up_file?$up_file:$url;
        $form_data = array(
            'title'           => $data['title'],
            'type_id'         => $data['type_id'],
            'tit_color'       => $data['tit_color']?$data['tit_color']:'#000000',
            'tit_b'           => $data['tit_b'],
            'list_order'      => $data['list_order'],
            'updated_at'      => $time
        );
        if ($file_url) {
            $form_data['file_url'] = $file_url;
        }
        if (Hrtools::where(array('id'=>$id))->update($form_data)) {
            admin_toastr(trans('admin.save_succeeded'));
            return redirect(admin_base_path('/content/hrtools/index'));
        } else {
            throw new \Exception(trans('admin.save_failed'));
        }
    }
    public function store()
    {
        $data=$this->form()->getValidateInput();
        $time = date('Y-m-d H:i:s', time());
        $up_file = null;
        if (array_key_exists('up_file', $data)) {
            $up_file = $data['up_file'];
        }
        $url = $data['url'];
        $file_url = $up_file?$up_file:$url;
        $form_data = array(
            'title'           => $data['title'],
            'type_id'         => $data['type_id'],
            'tit_color'       => $data['tit_color']?$data['tit_color']:'#000000',
            'tit_b'           => $data['tit_b'],
            'file_url'        => $file_url,
            'list_order'      => $data['list_order'],
            'created_at'      => $time,
            'updated_at'      => $time
        );
        if (Hrtools::insert($form_data)) {
            admin_toastr(trans('admin.save_succeeded'));
            return redirect(admin_base_path('/content/hrtools/index'));
        } else {
            throw new \Exception(trans('admin.save_failed'));
        }
    }
    public function download($type, $filename)
    {
        $filepath = public_path('uploads').'/'.$type . '/' . $filename;
        $file = fopen($filepath, "r");
        Header("Content-type: application/octet-stream");
        Header("Accept-Ranges: bytes");
        Header("Accept-Length: " . filesize($filepath));
        Header("Content-Disposition: attachment; filename=" . $filename);
        fclose($file);
    }
}