<?php

namespace App\Admin\Controllers\Company;

use App\Http\Controllers\Controller;
use App\Models\Company;
use App\Models\Jobs;
use App\Models\Promotion;
use Encore\Admin\Auth\Permission;
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;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;

class PromotionController 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('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('企业推广')
            ->description('修改')
            ->body($this->editForm()->edit($id));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header('企业推广')
            ->description('添加')
            ->body(view('admin.promotion.add')->with('grid', $this->jobGrid()->render()));
    }

    protected function jobGrid()
    {

        $form = new \Encore\Admin\Widgets\Form();
        $form->text('id', '职位ID');
        $form->text('jobs_name', '职位名称');
        $form->text('company_name', '企业名称');
        $form->text('company_id', '企业ID');
        $form->disableReset();
        $form->disableSubmit();
        return $form;
    }

    public function adds(Request $request)
    {
        $jid = $request->jid;
        $type = $request->ptype;
        $cid = $request->cid;
        $days = $request->days;
        $where = [
            ['jobid',$jid],
            ['ptype',$type]
        ];
        if (Promotion::get($where)) {
            admin_toastr('该职位推广已存在', 'error');
            return back();
        }
        if (!$jid || !$cid) {
            admin_toastr('请选择要推广的企业的职位', 'error');
            return back();
        }
        if (!$days) {
            admin_toastr('请填写推广天数', 'error');
            return back();
        }
        switch ($type) {
            case 1:
                $flied = 'stick';
                break;
            case 2:
                $flied = 'emergency';
        }
        $data['companyid'] = $cid;
        $data['jobid'] = $jid;
        $data['days'] = $days;
        $data['ptype'] = $type;
        $data['starttime'] = time();
        $data['endtime'] = time()+$days*86400;
        if (!Promotion::create($data)) {
            admin_toastr('保存失败', 'error');
        }
        $set_data = [$flied=>1];
        if ($type==1) {
            $set_data['stime']=$data['endtime'];
        }
        Jobs::where('id', $jid)->update($set_data);
        event_search_update(Jobs::class, $jid, 'update');
        admin_toastr('保存成功', 'success');
        return redirect(route('promotion.index'));
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        Permission::check('promotion_manager');
        $grid = new Grid(new Promotion);
        $grid->model()->when(get_subsite_id()>0, function ($querys) {
            $querys->whereHas('job', function ($query) {
                $query->where('subsite_id', get_subsite_id());
            });
        })->whereHas('company')->whereHas('job')->orderBy('id', 'desc');
        $grid->column('job.jobs_name', '推广职位');
        $grid->column('company.companyname', '企业名称')->width(200);
        $grid->ptype('推广类型')->display(function ($ptype) {
            return $ptype==1?"置顶":"紧急";
        });
        $grid->starttime('开始时间')->display(function ($starttime) {
            return date('Y-m-d', $starttime);
        });
        $grid->endtime('结束时间')->display(function ($endtime) {
            return date('Y-m-d', $endtime);
        });
        $grid->actions(function ($actions) {
            if (Admin::user()->can('promotion_manager_edit')) {
                $actions->disableEdit(false);
            }
            if (Admin::user()->can('promotion_manager_delete')) {
                $actions->disableDelete(false);
            }
        });

        if (Admin::user()->can('promotion_manager_add')) {
            $grid->disableCreateButton(false);
        }
        $grid->filter(function ($filter) {
            $filter->like('company.companyname', '企业名称');
            $filter->like('company.id', '企业ID');
            $filter->like('job.jobs_name', '职位名称');
            $filter->like('job.id', '职位ID');
            $filter->equal('ptype', '推广类型')->select([1=>'置顶', 2=>'紧急']);
        });

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Promotion::findOrFail($id));
        $show->companyid('企业名称')->as(function ($companyid) {
            $comInfo = Company::select('companyname')->find($companyid);
            if ($comInfo) {
                return $comInfo->companyname;
            }
            return '';
        });
        $show->ptype('推广类型')->as(function ($ptype) {
            switch ($ptype) {
                case 1:
                    return '职位置顶';
                    break;
                case 2:
                    return '职位紧急';
                    break;
            }
        });
        $show->jobid('职位名称')->as(function ($jobid) {
            $jobInfo = Jobs::select('jobs_name')->find($jobid);
            if ($jobInfo) {
                return $jobInfo->jobs_name;
            }
            return '';
        });
        $show->days('推广天数');
        $show->starttime('开始时间')->as(function ($starttime) {
            return date('Y-m-d H:i:s', $starttime);
        });
        $show->endtime('开始时间')->as(function ($endtime) {
            return date('Y-m-d H:i:s', $endtime);
        });

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function editForm()
    {
        Permission::check('promotion_manager_edit');
        $form = new Form(new Promotion);
        $form->display('id');
        $form->display('company.companyname', '企业名称');
        $form->display('job.jobs_name', '职位名称');
        $form->display('ptype', '推广方案')->with(function ($ptype) {
            return $ptype==1?'置顶':'紧急';
        });
        $form->display('days', '推广天数');
        $form->display('dead_line', '推广期限');
        $form->hidden('endtime', '结束时间');
        $form->text('day', '延迟推广天数')->rules('required', ['required'=>'请输入延迟推广天数']);

        return $form;
    }

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


        return $form;
    }

    /**
     * @param $id推广ID
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function update($id)
    {
        if (!Input::get('day')) {
            admin_toastr('请输入延迟推广天数!', 'error');
            return back();
        }
        $data = [
            'endtime' =>Input::get('endtime')+Input::get('day')*86400,
            'days' =>Input::get('day'),
        ];
        return $this->editForm()->update($id, $data);
    }

    public function destroy($id)
    {
        Permission::check('promotion_manager_delete');
        $model = Promotion::where('id', $id)->first();
        switch ($model->ptype) {
            case 1:
                $type = 'stick';
                $html = "置顶";
                $data['stime'] = 0;
                break;
            case 2:
                $type = 'emergency';
                $html = "紧急";
                break;
        }
        if (Promotion::destroy($id)) {
            if (Jobs::where('id', $model->jobid)->first()) {
                $data[$type] = 0;
                Jobs::where('id', $model->jobid)->update($data);
            }
            return admin_toastr('职位'.$html.'删除成功', 'success');
        }
        return admin_toastr('职位'.$html.'删除失败', 'error');
    }

}