<?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\SystemConfig;
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;

        $is_show = SystemConfig::get('docter_config', 'is_show');
        if ($is_show == 0) {
            return out();
        }

        $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);
        }
        elseif ($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);
        }
        elseif ($list_type == 3) {
            $builder->where('is_appoint', 1);
        }
        else {
            $builder->where(function ($query) {
                $query->where('is_phone', 1)->orWhere('is_chat', 1)->orWhere('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('docterOrganization')->select(['id'])->where('city_id', $req['city_id'])->get()->toArray();
            $docterIds = [];
            foreach ($organizations as $k => $v) {
                $tmpDocterIds = array_column($v['docter_organization'], 'docter_id');
                $docterIds = array_merge($docterIds, $tmpDocterIds);
            }
            $cityDocterIds = array_values(array_unique($docterIds));

            $builder->whereIn('id', $cityDocterIds);
        }

        if ($list_type == 3) {
            if (!empty($user)) {
                //查询我关注的医生
                $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 && !empty($docterIds3)) {
            $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',
            '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();

        $organization_ids = SchedulePeriod::where('docter_id', $req['docter_id'])->groupBy('organization_id')->pluck('organization_id')->toArray();
        $data['organization'] = [];
        if (!empty($organization_ids)) {
            $data['organization'] = Organization::select(['id', 'name', 'address', 'latitude', 'longitude', DB::raw($distance_field)])->whereIn('id', $organization_ids)->get()->toArray();
        }

        return ($data);
    }

    public function schedulePeriodList()
    {
        $req = request()->post();
        $this->validate(request(), [
            'docter_id' => 'required|integer',
            'latitude' => 'numeric',
            'longitude' => 'numeric',
        ]);
        $user = $this->user;

        $show_days = DocterSetting::where('docter_id', $req['docter_id'])->where('type', 1)->value('show_days');
        $per_page = !empty($show_days) ? $show_days : 15;
        $data = Schedule::with(['schedulePeriod.timePeriod', 'schedulePeriod.organization'])->where('docter_id', $req['docter_id'])->where('schedule_type', 1)->where('schedule_day', '>=', date('Ymd'))->orderBy('schedule_day', 'asc')->paginate($per_page)->toArray();
        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;
                    }
                    //预约时间已经过了，就不展示了
                    $schedule_time = strtotime($v1['schedule_date'].' '.$v1['time_period']['end_time_period'].':00');
                    if ($schedule_time < time()) {
                        unset($v['schedule_period'][$k1]);
                    }
                }
                $v['schedule_period'] = array_values($v['schedule_period']);
            }
        }

        return out($data);
    }

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

        $docterSettings = DocterSetting::select(['service_num', 'show_days'])->where('org_id', $req['organization_id'])->where('type', $req['schedule_type'])->first();
        $per_page = !empty($docterSettings['show_days']) ? $docterSettings['show_days'] : 15;
        $data = Schedule::with(['schedulePeriod.timePeriod', 'schedulePeriod.organization'])->where('schedule_day', '>=', date('Ymd'))->where('organization_id', $req['organization_id'])->where('schedule_type', $req['schedule_type'])->orderBy('schedule_day', 'asc')->paginate($per_page)->toArray();

        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;
                    }
                    //预约时间已经过了，就不展示了
                    $schedule_time = strtotime($v1['schedule_date'].' '.$v1['time_period']['end_time_period'].':00');
                    if ($schedule_time < time()) {
                        unset($v['schedule_period'][$k1]);
                    }
                }
                $v['schedule_period'] = array_values($v['schedule_period']);
            }
        }

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

        return out($data);
    }
}
