<?php

namespace App\Admin\Controllers\Jobfairout;

use App\Http\Controllers\Controller;
use App\Models\Company;
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\Layout\Content;
use Encore\Admin\Show;
use App\Models\Jobfairout\JobfairoutCompany;
use App\Models\Jobfairout\Jobfairout;
use App\Models\Jobfairout\JobfairoutReserve;
use App\Models\Jobfairout\JobfairoutPutJob;
use App\Admin\Extensions\Form\ValidateForm;
use Illuminate\Http\Request;
use App\Services\Common\SmsService;
use Aix\Sms\Contracts\Smser;
use App\Services\Common\EmailService;
use App\Models\MembersHandsel;
use App\Models\MembersPoint;
use App\Models\MembersSetmeal;
use App\Models\Pms;
class JobfairoutCompanyController extends Controller
{
    use HasResourceActions;
    protected $smsService;
    protected $emailService;

    public function __construct(SmsService $smsService,EmailService $emailService)
    {
        $this->smsService = $smsService;
        $this->emailService = $emailService;
    }

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        $grid=$this->grid()->render();
        return $content
            ->header('参会企业')
            ->description('')
            ->body(view('admin.jobfairout.jobfair_company')->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->form()->edit($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 JobfairoutCompany);
        $grid->model()->when(get_subsite_id()>0, function ($query) {
            $query->whereHas('jobfairout', function ($query) {
                $query->where('subsite_id', get_subsite_id());
            });
        })->orderByRaw("FIELD(audit, 2,1,3)")->orderBy('updated_at', 'desc');

        $grid->column('companys.companyname', '参会企业')->display(function ($companyname) {
            return '<a href="'.route('jobs.company',['id'=>$this->company_id]).'" target="_blank">'.$companyname.'</a>';
        })->width(200);

        $grid->person('参展人员信息')->display(function () {
            if($this->persons->isEmpty()){
                return '暂时没有';
            }else{
                return '<a href="'.route('jobfairout.company.person',['id'=>$this->id]).'" target="_blank">点击查看</a>';
            }
        });

        $grid->jobs_name('企业职位')->display(function () {
            if($this->jobfairPutJob->isEmpty()){
                return '暂无职位';
            }else{
                return '<a href="'.route('jobfairoutPutJobs.index',['jobfair_id'=>$this->jobfair_id,'company_id'=>$this->company_id]).'">点击查看</a>';
            }
        });
        $grid->column('jobfairout.title', '招聘会标题')->display(function ($jobfair_title) {
            return '<a href="'.route('jobfairout.show.com',$this->jobfair_id).'" target="_blank">'.$jobfair_title.'</a>';
        })->width(200);

        $grid->column('info.is_speech', '是否演讲')->display(function ($is_speech) {
            if($is_speech ==1)
            {
                return ' <span style="color: #009900">是</span>';
            }else{
                return ' <span style="color: #FF3300">否</span>';
            }
        });


        $grid->audit('预订状态')->display(function ($audit) {
            if ($audit==1) {
                return ' <span style="color: #009900">预定成功</span>';
            } elseif ($audit==2) {
                return'<span style="color:#FF6600">等待确认</span>';
            } else {
                return '<span style="color: #FF3300">审核未通过</span>';
            }
        });

        $grid->pay_type('支付方式')->display(function ($pay_type) {
            if ($pay_type==1) {
                return '<span style="color: #009900">场次</span>';
            } elseif ($pay_type==2) {
                return '<span style="color: #009900">积分</span>';
            } else {
                return '<span style="color: #009900">公益</span>';
            }
        });

        $grid->etype('预订方式')->display(function ($etype) {
            if ($etype==1) {
                return '<span style="color: #009900">在线预订</span>';
            } elseif ($etype==2) {
                return '<span style="color: #009900">电话预定</span>';
            } else {
                return '<span style="color: #009900">现场预定</span>';
            }
        });
        if(get_subsite_open()){
            $grid->column('jobfairout.subsite_id', '所属分站')->display(function ($subsite_id) {
                if ($subsite_id) {
                    $Subsite = Subsite::find($subsite_id);
                    return isset($Subsite->sitename) ? $Subsite->sitename : '未知';
                }
                return '总站';
            });
        }

        $grid->created_at('创建时间');
        /* $grid->disableCreateButton();*/
        $grid->actions(function ($actions) use ($grid) {
            if (Admin::user()->can('company_manager_bussiness')) {
                $actions->append("<button class='btn btn-primary btn-xs business' id=".$actions->row['company_id'].">业务</button>");
            }
            if (Admin::user()->can('jobfairout_company_audit')) {
                $actions->append("<button class='btn btn-primary btn-xs jobaudit' data-code=".$actions->row['id'].">审核</button>");
            }
            if (Admin::user()->can('jobfairout_companys_edit')) {
                $actions->disableEdit(false);
            }
            if (Admin::user()->can('jobfairout_companys_delete')) {
                $actions->disableDelete(false);
            }
            if (Admin::user()->can('jobfairout_company_poster')) {
                $actions->append('<button class="btn btn-primary btn-xs poster" title="企业海报" onclick="window.open(\''.route('jobfairout.company.poster',['id'=>$actions->row['id']]).'\')" >企业海报</button>');
            }
        });

        if (Admin::user()->can('jobfairout_company_delete')) {
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    $batch->disableDelete(false);
                });
            });
            $grid->disableRowSelector(false);
        }

        if (Admin::user()->can('jobfairout_companys_create')) {
            $grid->disableCreateButton(false);
        }
        $grid->tools(function ($tools) {
            if (Admin::user()->can('jobfairout_company_audit')) {
                $but = <<<EOT
<div class="btn-group" data-toggle="buttons">
    <label class="btn btn-google btn-sm" id="Audit_Companys" title="参会状态">
        <i class="fa fa-audio-description"></i>
        <input type="radio" class="user-gender">审核企业
    </label>
</div>
EOT;
                $tools->append($but);
            }
        });
        $grid->filter(function ($filter) {
            // 去掉默认的id过滤器
            $filter->disableIdFilter();
            $filter->column(1/2, function ($filter) {
                $filter->like('companys.companyname', '参会企业');
                $filter->equal('jobfair_companys.jobfair_id', '招聘会标题')->select(Jobfairout::select('title', 'id')->when(get_subsite_id()>0,function ($query){
                    $query->whereHas('subsites', function ($query) {
                        $query->where('subsite_jobfairouts.subsite_id', get_subsite_id())->where('subsites.effective', 1);
                    });
                })->pluck('title', 'id')->all());
                $filter->equal('jobfair_companys.audit', '预订状态')->select([
                    1=>'预定成功',
                    2=>'等待确认',
                    3=>'审核未通过',
                ]);
                if( get_subsite_id() == 0 && get_subsite_open()){
                    $filter->equal('jobfairout.subsite_id', '所属分站')->select(array_column(get_all_subsite(), 'sitename', 'id'));
                }
            });
            $filter->column(1/2, function ($filter) {
                $filter->equal('jobfair_companys.pay_type', '支付方式')->select([
                    1=>'场次',
                    2=>'积分',
                    3=>'公益',
                ]);
                $filter->equal('jobfair_companys.etype', '预订方式')->select([
                    1=>'在线预订',
                    2=>'电话预定',
                    3=>'现场预定'
                ]);
                $filter->where(function ($query) {
                    switch ($this->input) {
                        case 3:
                            $query->whereRaw("jobfair_companys.updated_at>='".date('Y-m-d H:i:s', strtotime('-3 day'))."'");
                            break;
                        case 7:
                            $query->whereRaw("jobfair_companys.updated_at>='".date('Y-m-d H:i:s', strtotime('-7 day'))."'");
                            break;
                        case 30:
                            $query->whereRaw("jobfair_companys.updated_at>='".date('Y-m-d H:i:s', strtotime('-30 day'))."'");
                            break;
                    }
                }, '更新时间', 'updated_at')->select([
                    3=>'三天内',
                    7=>'一周内',
                    30=>'一月内',
                ]);
            });
        });

        return $grid;
    }

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

        $jobfairCompany = JobfairoutCompany::findOrFail($id);

        $show->id('ID');

        $show->companys()->companyname('参会企业')->as(function ($companys){
            return $companys->companyname;
        });

        $show->jobfairout()->title('招聘会标题')->as(function ($jobfair){
            return $jobfair->title;
        });

        $show->type('签到状态')->as(function ($type) {
            if ($type==0) {
                return '未签到';
            } elseif ($type==1) {
                return '迟到';
            } elseif ($type==2) {
                return '早退';
            } elseif ($type==3) {
                return '迟到/早退';
            } elseif ($type==4) {
                return '已签到';
            }
        });


        $show->audit('预订状态')->as(function ($audit) {
            if ($audit==1) {
                return '预定成功';
            } elseif ($audit==2) {
                return '等待确认';
            } else {
                return '审核未通过';
            }
        });
        $show->pay_type('支付方式')->as(function ($pay_type) {
            if ($pay_type==1) {
                return '场次';
            } elseif ($pay_type==2) {
                return '积分';
            } else {
                return '公益';
            }
        });
        $show->etype('预订方式')->as(function ($etype) {
            if ($etype==1) {
                return '在线预订';
            } elseif ($etype==2) {
                return '电话预定';
            } else {
                return '现场预定';
            }
        });

        $show->subsite_id('所属分站')->as(function () use ($jobfairCompany) {
            $subsite_id = Jobfairout::findOrFail($jobfairCompany->jobfair_id)->subsite_id;
            if ($subsite_id) {
                $Subsite = Subsite::find($subsite_id);
                return isset($Subsite->sitename) ? $Subsite->sitename : '未知';
            }
            return '总站';
        });
        $show->created_at('创建时间');
        $show->updated_at('更新时间');
        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new ValidateForm(new JobfairoutCompany);
        $form->select('company_id', '企业名称')->options(
            Company::pluck('companyname', 'id')->all()
        )->rules([
            'required',
        ])->setMustMark();
        $form->select('jobfair_id', '招聘会名称')->options(
            Jobfairout::where('display', 1)->where('predetermined_status',1)->where('holddate_end', '>', time())->pluck('title', 'id')->all()
        )->rules(['required',])->setMustMark();
        $form->select('etype', '预定方式')->options([3=>'现场预定'])->default(3)->help('现场预定不消耗场次或积分!');
        $form->hidden('pay_type')->default(3);
        $form->saving(function (Form $form){
            $company_id = $form->company_id;
            $count = JobfairoutCompany::where(['company_id'=>$company_id,'jobfair_id'=>$form->jobfair_id])->count();
            if ($count>=1) {
                admin_toastr('该企业已预定过该招聘会!', 'error');
                return back();
            }
        });
        $form->saved(function (Form $form) {
            $model = $form->model();
            $model->audit = 1;
            $model->note = '该企业现场预定展位!';
            $model->save();
        });
        return $form;
    }

    public function person(Request $request)
    {
        $id = $request->id;
        $reserve = JobfairoutReserve::where('exid',$id)->get();
        return view('admin.jobfairout.jobfair_company_person',['reserve'=>$reserve]);
    }

    public function poster(Request $request)
    {
        $id = $request->id;
        $poster = JobfairoutCompany::find($id);
        return view('admin.jobfairout.jobfair_company_poster',['poster'=>$poster]);
    }

    public function auditCompanys(Request $request)
    {
        $id = $request->id;
        $form = new \Encore\Admin\Widgets\Form();
        $form->action(route('jobfairout.company.auditr'));
        $form->disableReset();
        $form->hidden('id', 'ID')->default($id);
        $form->radio('audit', '审核')->options([1=>'预订成功',3=>'审核未通过'])->default(1);
        $form->textarea('note', '备注');
        $form->html('<label style="color: rgb(0, 153, 0)"><input type="checkbox" name="pms_notice" value="1" checked="checked">站内信通知</label>');
        return json_encode(['html'=>$form->render(),'detail'=>'审核企业']);
    }

    public function auditCompanysR(Request $request)
    {
        $id = $request->id;
        $audit = $request->audit;
        $note = $request->note;
        $pms_notice = $request->pms_notice;
        if($audit==3){
            if (empty($note)) {
                admin_toastr('参会企业审核未通过必须填写备注!', 'error');
                return back();
            }
        }
        $arr = array_filter(explode(',', $id));
        if (empty($arr)) {
            admin_toastr('请选择参会企业', 'error');
            return back();
        }
        $arr_id = [];
        $JobfairCompany = JobfairoutCompany::whereHas('jobfairout',function ($query){
            $query->where('holddate_end', '>', time());
        })->whereIn('id', $arr)->get();
        if($JobfairCompany->isEmpty()){
            admin_toastr('招聘会已过期', 'error');
            return back();
        }
        \DB::beginTransaction();
        try {
            foreach ($JobfairCompany as $key => $val) {
                if ($audit==1) { //预订成功
                    if ($val->audit==2) {
                        $arr_id[] = $val->id;
                        if($val->companys->mobile && $val->companys->mobile_audit == 1){
                            $this->smsService->sendSms(
                                $val->companys->mobile,
                                Smser::TEMPLATE_JOBFAIR_APPLY_OK,
                                [
                                    'jobfair_name'=>$val->jobfairout->title,
                                    'jobfair_time'=>date('Y-m-d H:i',$val->jobfairout->holddate_start),
                                    'jobfair_addr'=>$val->jobfairout->address,
                                ]);
                        }
                        if($val->companys->email && $val->companys->email_audit == 1){
                            $this->emailService->sendMail($val->companys->email, EmailService::TEMPLATE_JOBFAIR_APPLY_OK,
                                ['title'=>'赴外招聘会预订成功'],
                                [
                                    'jobfair_name'=>$val->jobfairout->title,
                                    'jobfair_time'=>date('Y-m-d H:i',$val->jobfairout->holddate_start),
                                    'jobfair_addr'=>$val->jobfairout->address,
                                ]
                            );
                        }
                    }
                } else { //审核未通过。
                    if ($val->audit==2 || $val->audit==1) {
                        $arr_id[] = $val->id;
                        if($val->companys->mobile && $val->companys->mobile_audit == 1){
                            $this->smsService->sendSms(
                                $val->companys->mobile,
                                Smser::TEMPLATE_JOBFAIR_APPLY_ERROR,
                                [
                                    'jobfair_name'=>$val->jobfairout->title
                                ]);
                        }
                        if($val->companys->email && $val->companys->email_audit == 1){
                            $this->emailService->sendMail($val->companys->email, EmailService::TEMPLATE_JOBFAIR_APPLY_ERROR, ['title'=>'赴外招聘会预订失败'], ['jobfair_name'=>$val->jobfairout->title]);
                        }
                    }

                    if ($val->jobfairout) {
                        if ($val->pay_type==1) {//场次
                            MembersSetmeal::where('uid', $val->company_id)->where('utype', 1)
                                ->increment('jobfair_num', $val->jobfairout->jobsfair_num);
                        }elseif ($val->pay_type==2) { //积分
                            MembersPoint::where('uid', $val->company_id)->where('utype', 1)
                                ->increment('points', $val->jobfairout->predetermined_point);
                            MembersHandsel::create([
                                'uid'=>$val->company_id,
                                'utype'=>1,
                                'htype_cn'=>'返还预定招聘会的积分',
                                'operate'=>1,
                                'points'=>$val->jobfairout->predetermined_point
                            ]);
                        }
                    }
                }
            }

            if ($arr_id) {
                $newReult = JobfairoutCompany::with(['jobfairout', 'companys'])->whereHas('jobfairout')
                    ->whereHas('companys')->whereIn('id', $arr_id)->get();
                foreach ($newReult as $key => $val) {
                    if ($val->jobfairout && $val->companys) {
                        $newDate[$key]['utype'] = $val->companys->utype;
                        $newDate[$key]['msgtype'] = 2;
                        $newDate[$key]['msgfromuid'] = 0;
                        $newDate[$key]['msgfrom'] = 'admin';
                        $newDate[$key]['msgtoname'] = $val->companys->username;
                        $newDate[$key]['msgtouid'] = $val->companys->id;
                        $title = strstr($val->jobfairout->title, '赴外—招聘会') ? $val->jobfairout->title : $val->jobfairout->title . '赴外—招聘会';
                        if ($audit == 1) {
                            $newDate[$key]['message'] = '您申请的<a href="/content/jobfairout/show/' . $val->jobfairout->id . '">' . $title . '</a>已审核通过,请尽快提交招聘会职位。';
                        } else {
                            $newDate[$key]['message'] = '您申请的<a href="/content/jobfairout/show/' . $val->jobfairout->id . '">' . $title . '</a>已审核失败,请尽快查收。失败原因(' . $note . ')';
                        }
                        $newDate[$key]['created_at'] = date('Y-m-d H:i:s');
                        $newDate[$key]['updated_at'] = date('Y-m-d H:i:s');
                    }
                }
                if ($pms_notice&&$newDate) {
                    Pms::insert($newDate);
                }
                JobfairoutCompany::whereIn('id', $arr_id)->update(['audit' => $audit, 'note' => $note]);
            } else {
                admin_toastr('操作失败', 'error');
                return back();
            }
            \DB::commit();
            admin_toastr('操作成功', 'success');
        } catch (\Exception $e) {
            \DB::rollback();
            admin_toastr('操作失败', $e->getMessage());
        }
        return back();
    }


    public function destroy($id)
    {
        $ids = array();
        if ($id) {
            $ids = explode(',', $id);
        }
        if (!$ids) {
            return admin_toastr('请勾选需要删除的参展职位', 'error');
        }
        \DB::beginTransaction();
        try {
            JobfairoutCompany::whereIn('id', $ids)->delete();
            JobfairoutPutJob::whereIn('exid', $ids)->delete();
            $data = [
                'status'  => true,
                'message' => trans('admin.delete_succeeded'),
            ];
            \DB::commit();
            return response()->json($data);
        } catch (\Exception $e) {
            \DB::rollback();
            $data = [
                'status'  => false,
                'message' => trans('admin.delete_failed'),
            ];
            return response()->json($data);
        }
    }
}