<?php

namespace App\Community\Actions\Vaccine;

use App\Models\Order;
use App\Models\OrderPatient;
use App\Models\OrderVaccine;
use App\Models\OrganizationVaccine;
use App\Models\Patient;
use App\Models\TimePeriod;
use App\Models\Vaccine;
use Encore\Admin\Actions\Action;
use Encore\Admin\Actions\RowAction;
use Encore\Admin\Grid\Tools\AbstractTool;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Request;
use Encore\Admin\Facades\Admin;

class FasteOrder extends Action
{
    protected $selector = '.import-tenant';

    public function handle()
    {
        $data = request()->all();

        $org_id = Admin::user()->org_id;
        $timeInfo = TimePeriod::where(['id'=>$data['timer']])->first()->toArray();
        $patientInfo = Patient::where(['id'=>$data['user']])->first()->toArray();
        $vaccineInfo = Vaccine::where(['id'=>$data['vaccine']])->first()->toArray();


        DB::beginTransaction();
        try {
            $orderInfo = [
                'user_id'=>$patientInfo['user_id'],
                'organization_id'=>$org_id,
                'order_sn'=>$patientInfo['user_id'],
                'product_type'=>4,
                'total_amount'=>$vaccineInfo['price'],
                'is_faster'=>1,
                'order_status'=>7,
                'payment_status'=>2,
            ];

            if($data['date'] == date('Y-m-d',time())){
                $orderInfo['order_status'] = 3;
//                $orderInfo['order_notes'] = '快速预约';
                $orderInfo['receiving_time'] = time();
            }
            $order = Order::create($orderInfo);
            $order_sn = build_sn($order['id']);
            Order::where('id', $order['id'])->update(['order_sn' => $order_sn]);

            //保存订单患者信息
            $addPatient = Patient::select(['name', 'sex', 'avatar', 'birthday', 'relationship_type', 'info', 'card_type', 'card_number', 'card_img_url', 'card_back_img_url', 'email', 'phone as patient_phone', 'social_card_number', 'born_hospital', 'guardian_name', 'address'])->where('id', $data['user'])->first()->getOriginal();
            $addPatient['order_id'] = $order['id'];
            $addPatient['patient_id'] = $data['user'];
            $addPatient['organization_id'] = $org_id;
            $addPatient['time_period_id'] = $data['timer'];
            $addPatient['appoint_start_time'] = strtotime($data['date'].' '.$timeInfo['start_time_period'].':00');
            $addPatient['appoint_end_time'] = strtotime($data['date'].' '.$timeInfo['end_time_period'].':00');

            $patienter = OrderPatient::create($addPatient);
            // todo 需要完善疫苗订单
            $vaccine = [
                'order_id'=>$order['id'],
                'order_patient_id'=>$patienter['id'],
                'vaccine_id'=>$vaccineInfo['id'],
                'vaccine_type'=>$vaccineInfo['type'],
                'vaccine_price'=>$vaccineInfo['price'],
                'vaccine_name'=>$vaccineInfo['name'],
                'vaccine_remark'=>$vaccineInfo['remark'],
                'vaccine_supplier'=>$vaccineInfo['supplier'],
            ];
            OrderVaccine::create($vaccine);
            Vaccine::where(['id'=>$vaccineInfo['id'],'org_id'=>$org_id])->decrement('stock');
            DB::commit();
        } catch ( Exception $e){
            DB::rollBack();
            return $this->response()->error('添加订单失败');
        }

        return $this->response()->success('导入完成！')->refresh();
    }

    public function form()
    {
        Admin::script($this->script());
        Admin::js('select2.js');
        $patient = Patient::pluck('name','id');
        $org_id = Admin::user()->org_id;
        $vaccine = Vaccine::where(['org_id'=>$org_id])->pluck('name','id');
        // todo 需要搜索
        $this->select('user', '接种人')->options($patient)->rules('required',['required'=>'请选择接种患者']);
        $this->select('vaccine', '疫苗')->options($vaccine)->rules('required',['required'=>'请选择疫苗']);
        $this->date('date','时间')->rules('required',['required'=>'请选择时间']);
        $this->select('timer','时间段')->rules('required',['required'=>'请选择时间段']);
    }

    public function html()
    {
        return <<<HTML
        <a class="btn btn-sm btn-default import-tenant"><i class="fa fa-calendar-check-o"></i>  快速预约</a>
HTML;
    }

    protected function script()
    {

        return <<<EOT
        $("select[name='user']").select2({"allowClear":true,"placeholder":{"id":"","text":"\u75ab\u82d7"}});
        $('#date').blur(function () {
            var url = '';
            var date = $('#date').val();
            console.log(date);
            $.get("/cdms/api/getDateVaccine",{date: this.value}, function (data) {
                var html = '<option value="">请选择时间段</option>';
                for(let key  in data){
                console.log(key + '---' + data[key])
                 html += '<option value="'+key+'">'+data[key]+'</option>';
                }
                $('select[name="timer"]').empty();
                $('select[name="timer"]').append(html);
            });
        });
EOT;
    }
}
