<?php

namespace App\Admin\Controllers\Content;

use App\Admin\Extensions\Tools\DialogTool;
use App\Http\Controllers\Controller;
use App\Models\AuditReason;
use App\Models\Feedback;
use App\Models\Subsite;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Grid\Filter;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class FeedbackController extends Controller
{
    use HasResourceActions;

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->header('意见建议')
            ->description(' ')
            //->body($this->grid());
            ->body(view('admin.content.feedback')->with(['grid'=>$this->grid()]));
    }

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

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

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

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Feedback);
        if (get_subsite_id() != 0) {
            $where['subsite_id'] = get_subsite_id();
            $grid->model()->where($where)->orderBy('audit', 'asc')->orderBy('created_at', 'desc');
        } else {
            $grid->model()->orderBy('audit', 'asc')->orderBy('created_at', 'desc');
        }
        $grid->type('类型');
        $grid->audit('处理状态')->display(function () {
            $audit_html = '';
            if ($this->audit) {
                $audit_html = '已处理';
            } else {
                $audit_html = '<span style="color:#ff0000;">未处理</span>';
            }
            return $audit_html;
        });
        $grid->content('内容')->display(function () {
            return '<span class="vtip" title="'.$this->content.'">'.cut_str($this->content, 40, 0, "...").'</span>';
        })->width(400);
        $grid->contact('联系方式');
        if(get_subsite_open()){
            $grid->subsite_id('所属分站')->display(function () {
                $subsites = Cache::get('subsites_list');
                if (array_has($subsites, $this->subsite_id)) {
                    return $subsites[$this->subsite_id]['sitename'];
                }
                return '';
            });
        }
        $grid->created_at('添加时间');

        /*$grid->tools(function (Grid\Tools $tools) {
            $tools->disableRefreshButton();
        });*/
        $grid->actions(function ($actions) {
            if (Admin::user()->can('content_appeal_audit')) {
                $actions->append("<button class='btn btn-primary btn-xs jobaudit' data-code=".$actions->row['id'].">处理</button>");
            }
        });
        if (Admin::user()->can('content_feedback_delete')) {
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    $batch->disableDelete(false);
                });
            });
        }

        if (!Admin::user()->can('content_feedback_audit') && !Admin::user()->can('content_feedback_delete')) {
            $grid->disableRowSelector();
        }

        $grid->filter(function (Filter $filter) {
            $filter->disableIdFilter();
            $filter->column(2/3, function ($filter) {
                /*if (get_subsite_id() == 0) {
                    $subsites = Subsite::where(array('effective'=>1))->orderBy('order', 'asc')->get()->pluck('sitename', 'id')->toArray();
                    if ($subsites) {
                        $subsites = array('' => '不限', '0' => '总站') + $subsites;
                        $filter->equal('subsite_id', '所属分站')->radio($subsites);
                    }
                }*/
                $subsites = Subsite::where(array('effective'=>1))->orderBy('order', 'asc')->get()->pluck('sitename', 'id')->toArray();
                if ($subsites) {
                    $subsites = array('' => '不限', '0' => '总站') + $subsites;
                    $filter->equal('subsite_id', '所属分站')->select($subsites);
                }

                $cate_option = array(''=>'不限','1'=>'建议', '2' => '意见', '3' => '求助', '4' => '投诉');
                $filter->equal('type', '所属分类')->radio($cate_option)->default('');

                $where['audit'] = 0;
                if (get_subsite_id() > 0) {
                    $where['subsite_id'] = get_subsite_id();
                }
                $nums = Feedback::where($where)->get()->count();
                $num_html ='';
                if ($nums>0) {
                    $num_html = '('.$nums.')';
                }
                $status_option = array('0'=>'未处理'.$num_html,'1'=>'已处理');
                $status_option = array(''=>'不限')+$status_option;
                $filter->equal('audit', '处理状态')->radio($status_option);

                $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);
            });
        });

        //审核功能
        if (Admin::user()->can('content_feedback_audit')) {
            $grid->tools(function ($tools) {
                $form = new \Encore\Admin\Widgets\Form();
                $form->action(route('feedback.audit'));
                $audit_option = array('0'=>'未处理','1'=>'已处理');
                $form->radio('audit', '将所选意见建议设置为:')->options($audit_option)->default(1)->setWidth(8, 4);
                $form->json('val');
                $config = array('title'=>'处理意见建议','button'=>'处理','dialog_cancel' => "取消", 'dialog_ok' => "确认", 'is_batch' => true);
                $tools->append(new DialogTool($form, $config));
            });
        }

        return $grid;
    }
    public function audit(Request $request)
    {
        $rst = $request->validate(['audit'=>'required'], array('audit.required'=>'请选择处理状态'));
        $ids = $request->input('ids');
        if (empty($ids)) {
            if($request->type){
                admin_toastr('请选择需要处理的数据', 'error');
                return back();
            }else{
                return admin_toastr('请选择需要处理的数据', 'error');
            }
        }
        $id_arr = explode(',', $ids);
        $update_data = array(
            'audit' =>  $request->input('audit'),
            'updated_at' =>date('Y-m-d H:i:s', time())
        );
        if (Feedback::whereIn('id', $id_arr)->update($update_data) === false) {
            if($request->type){
                admin_toastr('处理失败', 'error');
                return back();
            }else{
                return admin_toastr('处理失败', 'error');
            }
        } else {
            //添加审核日志
            $reason_data = array('ids'=>$id_arr,'status'=>$request->input('audit'),'type'=>'5');
            if ($request->input('audit')=='1') {
                $reason_data['reason'] = '将所选意见建议设置为已处理';
            } else {
                $reason_data['reason'] = '将所选意见建议设置为未处理';
            }
            AuditReason::addData($reason_data);
            if($request->type){
                admin_toastr('处理成功', 'success');
                return back();
            }else{
                return admin_toastr('处理成功', 'success');
            }
        }
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Feedback::findOrFail($id));
        $show->id('ID');
        $show->type('类型');
        $show->content('内容');
        $show->contact('联系方式');
        $show->audit('处理状态')->as(function ($audit) {
            if ($audit) {
                return '已处理';
            }
            return '未处理';
        });
        if(get_subsite_open()){
            $show->subsite_id('所属分站')->as(function ($subsite_id) {
                if ($subsite_id) {
                    $Subsite = Subsite::findOrFail($subsite_id);
                    return $Subsite->sitename;
                }
                return '总站';
            });
        }
        $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 Form(new Feedback);
        $form->display('ID');
        $form->display('Created at');
        $form->display('Updated at');
        return $form;
    }
}