<?php

namespace App\Admin\Controllers\PersonalTalents;

use App\Admin\Exports\PersonalTalents\PersonalTalentsExport;
use App\Models\Admin\AdminUser;
use App\Models\Category;
use App\Models\Company;
use App\Models\PersonalTalents;
use App\Models\PersonalTalentsLog;
use App\Http\Controllers\Controller;
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 App\Repositories\CategoryRepository;
use App\Repositories\CategoryMajorRepository;
use App\Services\Person\ResumeService;
use Encore\Admin\Widgets\Table;
use Illuminate\Http\Request;

class PersonalTalentsController extends Controller
{
    use HasResourceActions;
    protected $CategoryRepository;
    protected $CategoryMajorRepository;
    protected $ResumeService;
    protected $role_id_1 = 30;

    public function __construct(CategoryRepository $CategoryRepository, CategoryMajorRepository $CategoryMajorRepository, ResumeService $ResumeService)
    {

        $this->CategoryRepository = $CategoryRepository;
        $this->CategoryMajorRepository = $CategoryMajorRepository;
        $this->ResumeService = $ResumeService;
    }

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        $grid = $this->grid()->render();
        return $content
            ->header('人才服务')
            ->description('人才服务列表')
            //  ->body($this->grid());
            ->body(view('admin.personalTalents.index')->with('grid', $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));
    }

    /**
     * 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 PersonalTalents);
        $grid->model()->orderBy('id', 'desc');
        $grid->rc_username('会员名称');
        $grid->rc_level('人才等级')->display(function () {
            if ($this->ifconform == 1) {
                return $this->rc_level;
            } elseif ($this->ifconform == 2) {
                return '不符合人才标准';
            }
        });
        $grid->rc_where('人才来源')->display(function () {
            if ($this->rc_where == 1) {
                return '自主申报';
            } elseif ($this->rc_where == 2) {
                return '企业申报';
            } elseif ($this->rc_where == 3) {
                return '信息采集';
            }
        });
        $grid->rc_audit('审核状态')->display(function () {
            if ($this->rc_audit == 1) {
                return '<span style="color: #009900">认证通过</span><a class="logview" data-id='.$this->id.'><i class="fa fa-eye"></i></a>';
            } elseif ($this->rc_audit == 2) {
                return '<span style="color:#FF6600">预判</span><a class="logview" data-id='.$this->id.'><i class="fa fa-eye"></i></a>';
            } elseif ($this->rc_audit == 3) {
                return '<span style="color:#666666">认证不通过</span><a class="logview" data-id='.$this->id.'><i class="fa fa-eye"></i></a>';
            }
        });

        if (Admin::user()->id == 1) {
            $states = [
                '1' => ['value' => 1, 'text' => '已完结', 'color' => 'primary'],
                '0' => ['value' => 0, 'text' => '未完结', 'color' => 'default'],
            ];
            $grid->if_finish('完结状态')->switch($states);
        }

        $grid->created_at('添加时间');
        $grid->if_agree('推送简历')->display(function () {
            if ($this->if_agree == 1) {
                return '<span style="color: #009900">同意</span>';
            } elseif ($this->if_agree == 2) {
                return '<span style="color:#666666">不同意</span>';
            } elseif ($this->if_agree == 0) {
                return '<span style="color:#FF6600">待定</span>';
            }
        });

        $grid->column('admin_user.name', '所属客服')->display(function ($name) {
            return $name ? $name : '<span style="color:#FF6600">待分配</span>';
        });


        /*批量删除*/
        $grid->tools(function ($tools) {
            $admin_user = <<<EOT
            <div class="btn-group" data-toggle="buttons">
                <label class="btn btn-google btn-sm" id="admin_user" title="分配客服">
                    <i class="fa fa-audio-description"></i>
                    <input type="radio" class="user-gender">分配客服
                </label>
            </div>
EOT;
            $admin_user_result = AdminUser::where('id', 3)->get();
            if ($admin_user_result) {
                $tools->append($admin_user);

            }

            $tools->batch(function ($batch) {
                $batch->disableDelete(false);
            });
        });
        $grid->disableExport(false); //显示导出按钮
        $grid->exporter(new PersonalTalentsExport()); //传入自己在第1步创建的导出类
        $grid->disableCreateButton(true);
        $grid->actions(function ($actions) {
            $actions->disableEdit();
            $actions->disableDelete();
            $actions->disableView();
            if ($actions->row['if_finish'] != 1) {
                $actions->append("<button class='btn btn-primary btn-xs levelSet' data-code=" . $actions->row['id'] . ">人才审核</button>");
                $actions->append('<button class="btn btn-primary btn-xs" title="录入进度" onclick="window.open(\'' . route('personalTalentsLog.create',
                        ['id' => $actions->row['id']]) . '\')">录入进度</button>');
            }
            $actions->append('<button class="btn btn-primary btn-xs" title="查看进度" onclick="window.open(\'' . route('personalTalentsLog.list',
                    ['id' => $actions->row['id']]) . '\')">查看进度</button>');
            if ($actions->row['if_agree'] == 1) {
                $actions->append('<button class="btn btn-primary btn-xs" title="推送简历" onclick="window.open(\'' . route('push.set',
                        ['id' => $actions->row['id'], 'uid' => $actions->row['uid']]) . '\')">推送简历</button>');
            } else {
                $actions->append("<button class='btn btn-primary btn-xs agreeSet' data-code=" . $actions->row['id'] . ">设置推送</button>");
            }
        });
        $grid->filter(function ($filter) {
            $filter->column(1 / 2, function ($filter) {
                $filter->like('rc_username', '姓名');
                $filter->equal('rc_where', '人才来源')->select([1 => '自主申报', 2 => '企业申报', 3 => '信息申报']);
                $filter->equal('rc_audit', '审核状态')->select([1 => '认证通过', 2 => '预判', 3 => '认证不通过']);
                $filter->equal('if_agree', '推送简历')->select([0 => '待确定', 1 => '同意', 2 => '不同意']);
            });

            $filter->column(1 / 2, function ($filter) {
                $admin_user_result = AdminUser::where('admin_role_users.role_id', 30)->leftJoin('admin_role_users', 'admin_role_users.user_id', '=', 'admin_users.id');
                if ($admin_user_result) {
                    $admin_user_arr = AdminUser::where('admin_role_users.role_id', 30)->leftJoin('admin_role_users', 'admin_role_users.user_id', '=', 'admin_users.id')->pluck('admin_users.name', 'admin_users.id');
                    $filter->equal('admin_id', '客服')->select($admin_user_arr);
                }
                $RC_categoryArr = array_column($this->CategoryRepository->getCategoryByAlias(['alias' => 'RC_category'])->toArray(), 'demand', 'id');
                $filter->equal('rc_level_id', '人才等级')->select($RC_categoryArr);
                $filter->equal('if_finish', '完结状态')->select([1 => '已完结', 0 => '未完结']);
            });
        });
        return $grid;
    }

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

        $show->id('ID');
        $show->name('学校名称');
        $show->address('学校地址');
        $show->created_at('创建时间');
        $show->updated_at('修改时间');

        return $show;
    }

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

        $form->display('ID');
        $form->display('Created at');
        $form->display('Updated at');

        return $form;
    }
    public function personalTalentsLog(Request $request)
    {

        $id = $request->id;
        $headers = ['content'=>'日志内容', 'log_time'=>'操作时间', 'auth_man'=>'操作人员'];
        $data = [];
        $res = PersonalTalentsLog::where(['talents_id'=>$id])->orderBy('id', 'desc')->get();
        if (!$res) {
            $rows = $data;
        } else {
            foreach ($res as $k => $v) {
                $data[$k]['content'] = $v['content'];
                $data[$k]['log_time'] = $v['created_at'];
                $data[$k]['auth_man'] = $v['auth_man'];
            }
            $rows = $data;
        }

        $table = new Table($headers, $rows);
        return ['html'=>$table->render(),'detail'=>'日志信息'];
    }


    // 人才审核
    public function levelSet(Request $request)
    {
        $id = $request->id;
        $form = new \Encore\Admin\Widgets\Form();
        $form->action(route('level.set.update'));
        $form->disableReset();
        $form->hidden('id', 'ID')->default($id);
        $RC_categoryArr = array_column($this->CategoryRepository->getCategoryByAlias(['alias' => 'RC_category'])->toArray(), 'demand', 'id');
        $form->select('rc_level_id', '人才等级')->options(
            $RC_categoryArr
        )->rules([
            'required',
        ])->setMustMark();
        $form->radio('rc_audit', '人才认证状态')->options([1 => '认证通过', 3 => '认证未通过']);
        return json_encode(['html' => $form->render(), 'detail' => '人才审核']);
    }

    // 人才审核
    public function levelSetUpdate(Request $request)
    {
        $id = $request->id;
        $arr = array_filter(explode(',', $id));
        if (empty($arr)) {
            admin_toastr('请勾选需要人才审核的会员', 'error');
            return back();
        }

        $rc_level_id = $request->rc_level_id;
        if (empty($rc_level_id)) {
            admin_toastr('人才等级不能为空', 'error');
            return back();
        }

        $rc_level = Category::where('id', $rc_level_id)->first();

        if (!$rc_level) {
            admin_toastr('参数错误', 'error');
            return back();
        }

        $role_arr = [];
        if (!empty(Admin::user()->roles)) {
            foreach (Admin::user()->roles as $key => $val) {
                $role_arr[] = $val->id;
            }
        }

        if (!in_array($this->role_id_1, $role_arr)) {
            admin_toastr('人才客服才可以操作', 'error');
            return back();
        }

        //判断是否为此人才的所属客服在操作
        $adminid = PersonalTalents::where(array('id' => $id))->value('admin_id');
        if ($adminid != Admin::user()->id) {
            admin_toastr('此人才的客服才可以操作', 'error');
            return back();
        }

        $time = time();
        $data = array();
        $data['rc_level_id'] = $rc_level_id;
        $data['rc_level'] = $rc_level->demand;
        $data['rc_sort'] = $rc_level->order;
        $data['audit_time'] = $time;//审核时间
        $data['rc_audit'] = $request->rc_audit;

        if(!empty($rc_level)){
            $data['ifconform'] = 1;
        }

        try {
            PersonalTalents::where('id', $id)->update($data);
            $log = array();
            if ($request->audit == 1) {
                $authinfo = "认证通过";
            } else {
                $authinfo = "认证不通过";
            }
            $log['talents_id'] = $id;
            $log['log_class'] = 2;//日志类型
            $log['content'] = Admin::user()->username . "将人才认证为'" . $rc_level->demand . "',审核状态设置为'" . $authinfo . "'";
            $log['log_time'] = time();
            $log['auth_man'] = Admin::user()->username;
            PersonalTalentsLog::create($log);
            admin_toastr('审核成功', 'success');
            return back();
        } catch (\Exception $e) {
            admin_toastr('审核失败', 'error');
            return back();
        }
    }

    public function adminUserSet(Request $request)
    {
        $id = $request->id;
        $form = new \Encore\Admin\Widgets\Form();
        $form->action(route('adminUser.set.update'));
        $form->disableReset();
        $form->hidden('id', 'ID')->default($id);
        $form->select('admin_id', '客服名称')->options(
            AdminUser::where('admin_role_users.role_id', 30)->leftJoin('admin_role_users', 'admin_role_users.user_id', '=', 'admin_users.id')->pluck('admin_users.name', 'admin_users.id')
        )->rules([
            'required',
        ])->setMustMark();
        return json_encode(['html' => $form->render(), 'detail' => '分配客服']);
    }

    public function adminUserSetUpdate(Request $request)
    {
        $id = $request->id;
        $arr = array_filter(explode(',', $id));
        if (empty($arr)) {
            admin_toastr('请勾选需要分配客服的会员', 'error');
            return back();
        }
        $admin_user_id = $request->admin_id;
        if (empty($admin_user_id)) {
            admin_toastr('客服不能为空', 'error');
            return back();
        }
        if (Admin::user()->id != 1) {
            admin_toastr('高级管理员才可以操作', 'error');
            return back();
        }

        try {
            $time = time();
            $admin_user = AdminUser::find($admin_user_id);
            foreach ($arr as $key => $val) {
                $info = array();
                PersonalTalents::where('id', $val)->update(array('admin_id' => $admin_user_id));
                //填入日志
                $info['talents_id'] = $val;
                $info['log_class'] = 3;//日志类型高级管理员分配客服
                $info['content'] = Admin::user()->username . "将此人才的客服更改为客服人员‘" . $admin_user->username . "’";
                $info['log_time'] = $time;
                $info['auth_man'] = Admin::user()->username;
                PersonalTalentsLog::create($info);
            }
            admin_toastr('分配成功', 'success');
            return back();
        } catch (\Exception $e) {
            admin_toastr('分配失败', 'error');
            return back();
        }
    }

    // 设置推送
    public function agreeSet(Request $request)
    {
        $id = $request->id;
        $form = new \Encore\Admin\Widgets\Form();
        $form->action(route('agree.set.update'));
        $form->disableReset();
        $form->hidden('id', 'ID')->default($id);
        $form->radio('rc_agree', '推送简历')->options([1 => '同意', 2 => '不同意']);
        $form->textarea('agree_content', '备注');
        return json_encode(['html' => $form->render(), 'detail' => '设置推送']);
    }

    // 设置推送
    public function agreeSetUpdate(Request $request)
    {
        $id = $request->id;
        $arr = array_filter(explode(',', $id));
        if (empty($arr)) {
            admin_toastr('请选择需要推送的会员', 'error');
            return back();
        }

        $rc_agree = $request->rc_agree;
        if (empty($rc_agree)) {
            admin_toastr('参数有误', 'error');
            return back();
        }

        try {
            PersonalTalents::where('id', $id)->update(array('if_agree' => $rc_agree));
            $log = array();
            //存入日志
            if ($rc_agree == 1) {
                $agree = '同意';
            } elseif ($rc_agree == 2) {
                $agree = '不同意';
            }
            $log['talents_id'] = $id;
            $log['log_class'] = 6;//日志类型
            $content = $request->agree_content;
            if ($content != '') {
                $log['content'] = Admin::user()->username . "设置此人才" . $agree . '推送简历' . ',备注:' . $content;
            } else {
                $log['content'] = Admin::user()->username . "设置此人才" . $agree . '推送简历';
            }
            $log['log_time'] = time();
            $log['auth_man'] = Admin::user()->username;
            PersonalTalentsLog::create($log);
            admin_toastr('操作成功', 'success');
            return back();
        } catch (\Exception $e) {
            admin_toastr('操作失败', 'error');
            return back();
        }
    }

    // 推送简历
    public function pushSet(Content $content)
    {
        $id = request()->id;
        $form = new Form(new PersonalTalents);
        $form->setAction(route('push.set.update'));
        $form->disableReset();
        $form->hidden('ids')->default($id);
        $form->multipleSelect('company_id', '企业名称')->options(
            Company::where('audit', 1)->pluck('companyname', 'id')->all()
        )->rules([
            'required',
        ])->setMustMark();
        return $content
            ->header('推送简历')
            ->description('创建')
            ->body($form);
    }


    // 推送简历
    public function pushSetUpdate(Request $request)
    {
        $data = $request->all();
        $arr = array_filter(explode(',', $data['ids']));
        if (empty($arr)) {
            admin_toastr('请选择需要推送的会员', 'error');
            return back();
        }

        if (empty($data['company_id'])) {
            admin_toastr('请选择要推送的企业名称', 'error');
            return back();
        }

        $company_id_arr = [];
        $company_name_arr = [];
        foreach ($data['company_id'] as $key => $val) {
            if (!empty($val)) {
                $company_id_arr[] = $val;
                $company_name_arr[] = Company::where('id', $val)->value('companyname');
            }
        }

        try {
            $this->ResumeService->resumeEntrustByAdmin($company_id_arr,$data['ids'],Admin::user()->username);
            admin_toastr('推送成功', 'success');
        } catch (\Exception $e) {
            admin_toastr('职位不匹配,推送失败!', 'error');
        }
        return redirect(admin_base_path("personalTalents/personaltalents"));
    }
}