<?php
/**
 * Created by PhpStorm.
 * User: zilongs
 * Date: 20-9-29
 * Time: 上午11:09
 */

namespace App\Http\Controllers\Api\V1;

use App\Models\Collection;
use App\Models\Docter;
use App\Models\DocterServiceTime;
use App\Models\DocterSetting;
use App\Models\Organization;
use App\Models\Schedule;
use App\Models\SchedulePeriod;
use App\Models\ServicePack;
use App\Models\Team;
use DB;

class DocterController extends AuthController
{
    public function docterList()
    {
        $req = request()->post();
        $this->validate(request(), [
            'list_type' => 'in:0,1,2,3',
            'city_id' => 'integer',
            'name' => 'max:255',
            'latitude' => 'numeric',
            'longitude' => 'numeric',
            'sort_type' => 'in:0,1,2,3',
            'is_pack_docter' => 'in:0,1',
        ]);
        $user = $this->user;

        $distance_field = get_user_distance_field($user);

        $builder = Docter::with('office', 'qualification')->select(['id', 'type', 'name', 'phone', 'sex', 'birthday', 'avatar', 'status', 'label', 'sign', 'intro', 'office_id', 'qualification_id', 'score', 'service_persons', 'eva_num', 'service_days', 'phone_minutes', 'chat_price', 'phone_price', 'appoint_price', 'is_chat', 'is_phone', 'is_appoint', 'latitude', 'longitude', DB::raw($distance_field)])->where('status', 1)->where('is_then', 1)->where('phone', '<>', '');
        $list_type = !empty($req['list_type']) ? $req['list_type'] : 0;
        $now_line = (int)date('Hi');
        if ($list_type == 1) {
            $docter_ids5 = DocterServiceTime::where('type', 1)->where('start_time_line', '<=', $now_line)->where('end_time_line', '>', $now_line)->pluck('docter_id')->toArray();
            $builder->where('is_phone', 1)->whereIn('id', $docter_ids5);
        }
        if ($list_type == 2) {
            $docter_ids6 = DocterServiceTime::where('type', 2)->where('start_time_line', '<=', $now_line)->where('end_time_line', '>', $now_line)->pluck('docter_id')->toArray();
            $builder->where('is_chat', 1)->whereIn('id', $docter_ids6);
        }
        if ($list_type == 3) {
            $builder->where('is_appoint', 1);
        }
        if (!empty($req['name'])) {
            $name = $req['name'];
            $organizations = Organization::with('docter')->select(['id'])->where('name', 'like', '%'.$name.'%')->get()->toArray();
            $docterIds = [];
            foreach ($organizations as $k => $v) {
                $tmpDocterIds = array_column($v['docter'], 'id');
                $docterIds = array_merge($docterIds, $tmpDocterIds);
            }
            $orgDocterIds = array_values(array_unique($docterIds));
            $builder->where(function ($query) use($name, $orgDocterIds) {
                $query->where('name', 'like', '%'.$name.'%')->orWhereIn('id', $orgDocterIds);
            });
        }
        if (!empty($req['city_id'])) {
            $organizations = Organization::with('docter')->select(['id'])->where('city_id', $req['city_id'])->get()->toArray();
            $docterIds = [];
            foreach ($organizations as $k => $v) {
                $tmpDocterIds = array_column($v['docter'], 'id');
                $docterIds = array_merge($docterIds, $tmpDocterIds);
            }
            $cityDocterIds = array_values(array_unique($docterIds));
            $builder->whereIn('id', $cityDocterIds);
        }

        if ($list_type == 3) {
            //查询我关注的医生
            $docterIds3 = Collection::where('user_id', $user['id'])->where('docter_id', '>', 0)->pluck('docter_id')->toArray();
            $builder->whereNotIn('id', $docterIds3);
        }

        if (!empty($req['is_pack_docter'])) {
            $team_ids = ServicePack::pluck('team_id')->toArray();
            $team_id_arr = [];
            foreach ($team_ids as $k => $v) {
                if (!empty($v) && is_array($v)) {
                    $team_id_arr = array_merge($team_id_arr, $v);
                }
            }
            $team_id_arr = array_values(array_unique($team_id_arr));
            $teams = Team::with(['docter'])->whereIn('id', $team_id_arr)->get()->toArray();
            $docterIds4 = [];
            foreach ($teams as $k => $v) {
                foreach ($v['docter'] as $k1 => $v1) {
                    if (!in_array($v1['id'], $docterIds4)) {
                        $docterIds4[] = $v1['id'];
                    }
                }
            }
            $builder->whereIn('id', $docterIds4);
        }

        if (!empty($req['sort_type'])) {
            if ($req['sort_type'] == 1) {
                $builder->orderBy('distance', 'asc');
            }
            elseif ($req['sort_type'] == 2) {
                $builder->orderBy('eva_num', 'desc');
            }
            elseif ($req['sort_type'] == 3) {
                $builder->orderBy('service_persons', 'desc');
            }
        }
        $data = $builder->paginate()->toArray();

        //组合我关注的医生，放在最前面
        $page = empty($req['page']) ? 1 : $req['page'];
        if ($list_type == 3 && $page == 1) {
            $builder2 = Docter::with('office', 'qualification')->select(['id', 'type', 'name', 'phone', 'sex', 'birthday', 'avatar', 'status', 'label', 'sign', 'intro', 'office_id', 'qualification_id', 'score', 'service_persons', 'eva_num', 'service_days', 'phone_minutes', 'chat_price', 'phone_price', 'appoint_price', 'is_chat', 'is_phone', 'is_appoint', 'latitude', 'longitude', DB::raw($distance_field)])->whereIn('id', $docterIds3)->where('status', 1)->where('is_then', 1)->where('phone', '<>', '')->where('is_appoint', 1);
            if (!empty($req['name'])) {
                $builder2->where(function ($query) use($name, $orgDocterIds) {
                    $query->where('name', 'like', '%'.$name.'%')->orWhereIn('id', $orgDocterIds);
                });
            }
            if (!empty($req['city_id'])) {
                $builder2->whereIn('id', $cityDocterIds);
            }
            if (!empty($req['is_pack_docter'])) {
                $builder->whereIn('id', $docterIds4);
            }
            if (!empty($req['sort_type'])) {
                if ($req['sort_type'] == 1) {
                    $builder2->orderBy('distance', 'asc');
                }
                elseif ($req['sort_type'] == 2) {
                    $builder2->orderBy('eva_num', 'desc');
                }
                elseif ($req['sort_type'] == 3) {
                    $builder2->orderBy('service_persons', 'desc');
                }
            }

            $collectDocters = $builder2->get()->toArray();
            if (!empty($collectDocters)) {
                $data['data'] = array_merge($collectDocters, $data['data'] );
            }
        }

        return out($data);
    }

    public function docterDetail()
    {
        $req = request()->post();
        $this->validate(request(), [
            'docter_id' => 'required|integer',
            'list_type' => 'in:0,1,2,3',
            'latitude' => 'numeric',
            'longitude' => 'numeric',
        ]);
        $user = $this->user;

        $distance_field = get_user_distance_field($user);

        $data = Docter::with('office', 'qualification', 'evaluate.user')->select(['id', 'type', 'name', 'phone', 'sex', 'birthday', 'avatar', 'status', 'label', 'sign', 'intro', 'office_id', 'qualification_id', 'score', 'service_persons', 'eva_num', 'service_days', 'phone_minutes', 'chat_price', 'phone_price', 'appoint_price', 'is_chat', 'is_phone', 'is_appoint', 'latitude', 'longitude', DB::raw($distance_field)])->where('id', $req['docter_id'])->where('status', 1)->first()->toArray();

        $data['organization'] = null;
        if (!empty($req['list_type']) && $req['list_type'] == 3) {
            $schedulePeriod = SchedulePeriod::with('organization')->select(['organization_id'])->where('docter_id', $req['docter_id'])->where('schedule_date', date('Y-m-d'))->first()->toArray();
            $data['organization'] = $schedulePeriod['organization'];
        }

        return ($data);
    }

    public function schedulePeriodList()
    {
        $req = request()->post();
        $this->validate(request(), [
            'docter_id' => 'required|integer',
            'organization_id' => 'integer',
            'per_page' => 'integer',
            'latitude' => 'numeric',
            'longitude' => 'numeric',
        ]);
        $user = $this->user;
        $builder = Schedule::with(['schedulePeriod.timePeriod', 'schedulePeriod.organization'])->where('docter_id', $req['docter_id'])->where('schedule_type', 1)->where('schedule_day', '>=', date('Ymd'))->orderBy('schedule_day');
        if (!empty($req['organization_id'])) {
            $builder->where('organization_id', $req['organization_id']);
        }
        $data = $builder->paginate($req['per_page']??15)->toArray();
        \Log::info($data);
        if (!empty($data)) {
            foreach ($data['data'] as $k => &$v) {
                foreach ($v['schedule_period'] as $k1 => &$v1) {
                    if (!empty($v1['organization'])) {
                        $v1['organization']['distance'] = get_user_distance($user, $v1['organization']['latitude'], $v1['organization']['longitude']);
                    }
                    $docterSettings = DocterSetting::select(['service_num'])->where('docter_id', $req['docter_id'])->where('type', 1)->where('org_id', $v1['organization_id'])->first();
                    if (empty($docterSettings)) {
                        $v1['can_appoint_num'] = 0;
                    }
                    else {
                        $can_appoint_num = $docterSettings['service_num'] - $v1['order_num'];
                        $v1['can_appoint_num'] = $can_appoint_num < 0 ? 0 : $can_appoint_num;
                    }
                }
            }
        }

        return out($data);
    }

//    public function schedulePeriodList()
//    {
//        $req = request()->post();
//        $this->validate(request(), [
//            'docter_id' => 'required|integer',
//            'organization_id' => 'integer',
//            'per_page' => 'integer',
//            'latitude' => 'numeric',
//            'longitude' => 'numeric',
//        ]);
//        $user = $this->user;
//        $builder = schedulePeriod::with(['timePeriod', 'organization'])->where('docter_id', $req['docter_id'])->where('schedule_date', '>=', date('Y-m-d'));
//        if (!empty($req['organization_id'])) {
//            $builder->where('organization_id', $req['organization_id']);
//        }
//        $data = $builder->paginate($req['per_page']??15)->toArray();
//        //日期有重复,不同机构排班
//        $newdata = array();
//        if (!empty($data)) {
////            foreach ($data['data'] as $k => &$v) {
//                foreach ($data as $k1 => $v1) {
//                    if (!empty($v1['organization'])) {
//                        $v1['organization']['distance'] = get_user_distance($user, $v1['organization']['latitude'], $v1['organization']['longitude']);
//                    }
//                    $docterSettings = DocterSetting::select(['service_num'])->where('docter_id', $req['docter_id'])->where('type', 1)->where('org_id', $v1['organization_id'])->first();
//                    if (empty($docterSettings)) {
//                        $v1['can_appoint_num'] = 0;
//                    }
//                    else {
//                        $can_appoint_num = $docterSettings['service_num'] - $v1['order_num'];
//                        $v1['can_appoint_num'] = $can_appoint_num < 0 ? 0 : $can_appoint_num;
//                    }
//
//                    if(empty($newdata[$v1['time_period']])){
//                        $newdata[$v1['schedule_date']] = $v1;
//                    }else{
//                        $newd = $newdata[$v1['schedule_date']];
//                        foreach ($newd['time_period'] as $k2 => $v2) {
//                            array_push($v1['time_period'],$v2);
//                        }
//                        $newdata[$v['schedule_date']] = $v1;
//
//                    }
//                }
//
////            }
//        }
//        $res = array();
//        foreach ($newdata as $v) {
//            if (!empty($v['time_period']))$res[] = $v;
//        }
//
//        return out($res);
//    }

    public function timePeriodList()
    {
        $req = request()->post();
        $this->validate(request(), [
            'organization_id' => 'integer',
            'schedule_type' => 'integer',
            'per_page' => 'integer',
            'latitude' => 'numeric',
            'longitude' => 'numeric',
        ]);

        $builder = Schedule::with(['schedulePeriod.timePeriod', 'schedulePeriod.organization'])->where('schedule_day', '>=', date('Ymd'));
        if (!empty($req['organization_id'])) {
            $builder->where('organization_id', $req['organization_id']);
        }
        if (!empty($req['schedule_type'])) {
            $builder->where('schedule_type', $req['schedule_type']);
        }
        $data = $builder->orderBy('schedule_day', 'asc')->paginate($req['per_page']??15)->toArray();

        $docterSettings = DocterSetting::select(['service_num'])->where('org_id', $req['organization_id'])->where('type', $req['schedule_type'])->first();
        if (!empty($data)) {
            foreach ($data['data'] as $k => &$v) {
                if (empty($v['schedule_period'])) {
                    unset($data['data'][$k]);
                }
                foreach ($v['schedule_period'] as $k1 => &$v1) {
                    if (empty($docterSettings)) {
                        $v1['can_appoint_num'] = 0;
                    }
                    else {
                        $can_appoint_num = $docterSettings['service_num'] - $v1['order_num'];
                        $v1['can_appoint_num'] = $can_appoint_num < 0 ? 0 : $can_appoint_num;
                    }
                }
            }
        }

        $data['data'] = array_values($data['data']);

        return out($data);
    }
}
