<?php

namespace App\Admin\Actions\backstage;

use App\Models\Docter;
use App\Models\DocterOrganization;
use App\Models\Organization;
use App\Models\Serviceapplys;
use Encore\Admin\Actions\RowAction;
use Illuminate\Database\Eloquent\Model;

class Pass extends RowAction
{
    public $name = '通过';

    public function handle(Model $model)
    {
//         $model ...
//        dd($model);
        //判定通过认证的数量
        $is_pass_num = 0;
        //查询认证表里有多少条记录
        $docter_approve_num = DocterOrganization::where('docter_id',$model->docter_id)->get();
        //转成数组格式方便遍历
        $docter_approve_num_array = $docter_approve_num->toarray();

        foreach ($docter_approve_num_array as $value)
        {
            if ($value['state'] == 1)
            {
                $is_pass_num=$is_pass_num+1;
            }
        }
        //如果是第一次认证，就将机构的经纬度覆盖进去
        if ($is_pass_num == 0 )
        {
            //organization_id
            //经度
            $longitude = Organization::where('id',$this->row->organization_id)->value('longitude');
            //纬度
            $latitude = Organization::where('id',$this->row->organization_id)->value('latitude');
            Docter::where('id',$this->row->docter_id)->update(['latitude'=>$latitude,'longitude'=>$longitude]);
        }
        $end_time = strtotime('+1year');
        $authentication_end_time = date('Y-m-d H:i:s',$end_time);
        DocterOrganization::where('id',$model->id)->update(['state'=>1,
                                                            'authentication_time'=>date('Y-m-d H:i:s'),
                                                            'authentication_end_time'=>$authentication_end_time]
                                                            );
        Docter::where('id',$model->docter_id)->update(['is_then'=>1,'office_id'=>$model->offices_id,'qualification_id'=>$model->qualifications_id]);
        //生成默认的图文、电话、门诊的记录
        //判断数据表里是否有存在的记录了，如果有存在的记录就不会在继续创建
        $service = Serviceapplys::where('docter_id',$model->docter_id)->get();
        $service = $service->toArray();
        if (empty($service))
        {
            $service_type_arr = [1,2,3];
            foreach ($service_type_arr as $value)
            {
                $total_arr = [
                    'docter_id' => $model->docter_id,
                    'service_type' => $value,
                    'status' => 3,
                    'created_at' =>date('Y-m-d H;i;s'),
                    'updated_at' =>date('Y-m-d H;i;s'),
                ];
                Serviceapplys::insert($total_arr);
            }
        }
        return $this->response()->success('审核通过')->refresh();
    }

}