<?php

namespace App\Http\Controllers\API\H5;

use App\Http\Controllers\Controller;
use DateTime;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PlanController extends Controller
{
    //获取本月每日剩余号源数量
    public function GetMonthPlanCount()
    {
      $hospital_id =request('hospital');
      $openid =request('openid');
      $person_id=request('person_id');
      $month=request('month');
      $use_type=request('use_type');//使用类型 1个检 2团检
      $checkup_type_id=request('checkup_type_id');//体检类型表对应id
      $amount=request('amount');//总金额

      $first_day_timestamp = strtotime($month . '-01');
      $first_day = date('Y-m-d', $first_day_timestamp);  //当月第一天
      $last_day_timestamp = strtotime($month . '-01 +1 month -1 day');
      $last_day = date('Y-m-d', $last_day_timestamp);   //当月最后一天
      $list=DB::table('plans')
        ->whereBetween('date',[$first_day,$last_day])->whereIn('status',[1])
        ->whereRaw('JSON_CONTAINS(checkup_type_id, ?, "$")', [$checkup_type_id])
        ->where(['hospital_id'=>$hospital_id,'type'=>1])
        ->whereIn('use_type',[0,$use_type]);
//      if($use_type==1){
//        $list=$list->where(['amount_limit1'=>0])->orWhere('amount_limit1','>=',$amount);
//      }
//      if($use_type==2){
//        $list=$list->where(['amount_limit2'=>0])->orWhere('amount_limit2','>=',$amount);
//      }
      if ($use_type == 1) {
        $list = $list->where(function ($query) use ($amount) {
          $query->where('amount_limit1', 0)->orWhere('amount_limit1', '>=', $amount);
        });
      }

      if ($use_type == 2) {
        $list = $list->where(function ($query) use ($amount) {
          $query->where('amount_limit2', 0)->orWhere('amount_limit2', '>=', $amount);
        });
      }
      $list=$list->select('date', DB::raw('COUNT(*) as count'));
      $list=$list->groupBy('date')->get();


      //获取整月日期
      // 获取当月的第一天
      $firstDay = date("Y-m-d", strtotime($month . "-01"));
      // 获取当月的最后一天
      $lastDay = date("Y-m-t", strtotime($month));
      $dates = array();
      $k=0;
      for ($i = $firstDay; $i <= $lastDay; $i = date("Y-m-d", strtotime($i . " +1 day"))) {
        $xingqi=\App\Lib\Tools::GetWeekName($i);
        $dates[]=[
          'date'=>$i,
          'xingqi'=>$xingqi,
          'count'=>0
        ];
          foreach ($list as $item) {
            if($item->date == $i){
              $dates[$k]=[
                'date'=>$i,
                'xingqi'=>$xingqi,
                'count'=>$item->count
              ];
              break;
            }
          }
        $k++;
      }

      return \Yz::Return(true,"查询完成",['list'=>$dates]);
    }
    //获取某日号源列表
    public function GetDayPlanList()
    {
      $hospital_id =request('hospital');
      $openid =request('openid');
      $person_id=request('person_id');
      $date=request('date');
      $use_type=request('use_type');//使用类型 1个检 2团检
      $checkup_type_id=(string)request('checkup_type_id');//体检类型表对应id
      $amount=request('amount');//总金额

      $list=DB::table('plans')
        ->where('date',$date)->whereIn('status',[1,2])
        ->whereRaw('JSON_CONTAINS(checkup_type_id, ?, "$")', [$checkup_type_id])
        //->whereRaw('JSON_CONTAINS(CAST(checkup_type_id AS JSON), ?, "$")', ['"'.$checkup_type_id.'"'])
        ->where(['hospital_id'=>$hospital_id,'type'=>1])
        ->whereIn('use_type',[0,$use_type]);
      if ($use_type == 1) {
        $list = $list->where(function ($query) use ($amount) {
          $query->where('amount_limit1', 0)->orWhere('amount_limit1', '>=', $amount);
        });
      }

      if ($use_type == 2) {
        $list = $list->where(function ($query) use ($amount) {
          $query->where('amount_limit2', 0)->orWhere('amount_limit2', '>=', $amount);
        });
      }
      $list=$list->get();


      // 获取前后各三天的日期
      $dateTime = new DateTime($date);
      $days7=[];
      for ($i = -3; $i <= 3; $i++) {
        $dateTimeClone = clone $dateTime; // 克隆对象以避免修改原对象
        $dateTimeClone->modify("$i days"); // 修改日期
        $days7[] = $dateTimeClone->format('Y-m-d'); // 按照需要的格式添加到结果数组
      }

      $weeklist=DB::table('plans')
        ->whereBetween('date',[$days7[0],$days7[6]])->whereIn('status',[1])
        ->whereRaw('JSON_CONTAINS(checkup_type_id, ?, "$")', [$checkup_type_id])
        ->where(['hospital_id'=>$hospital_id,'type'=>1])
        ->whereIn('use_type',[0,$use_type]);
//      if($use_type==1){
//        $weeklist=$weeklist->where(['amount_limit1'=>0])->orWhere('amount_limit1','>=',$amount);
//      }
//      if($use_type==2){
//        $weeklist=$weeklist->where(['amount_limit2'=>0])->orWhere('amount_limit2','>=',$amount);
//      }
      if ($use_type == 1) {
        $weeklist = $weeklist->where(function ($query) use ($amount) {
          $query->where('amount_limit1', 0)->orWhere('amount_limit1', '>=', $amount);
        });
      }

      if ($use_type == 2) {
        $weeklist = $weeklist->where(function ($query) use ($amount) {
          $query->where('amount_limit2', 0)->orWhere('amount_limit2', '>=', $amount);
        });
      }
      $weeklist=$weeklist->select('date', DB::raw('COUNT(*) as count'));
      $weeklist=$weeklist->groupBy('date')->get();
      $week7=[];
      $k=0;
      foreach ($days7 as $date) {
        $xingqi=\App\Lib\Tools::GetWeekName($date);
        $week7[]=[
          'date'=>$date,
          'count'=>0,
          'xingqi'=>$xingqi
        ];
        foreach ($weeklist as $plan) {
          if($plan->date == $date){
            $week7[$k]=[
              'date'=>$date,
              'xingqi'=>$xingqi,
              'count'=>$plan->count
            ];
            break;
          }
        }
        $k++;
      }


      return \Yz::Return(true,"查询完成",['list'=>$list,'weeklist'=>$week7]);
    }
    //检查号源是否可用
  public function CheckPlan($plan_id,$hospital_id,$type,$sex,$price,$checkup_type_id)
  {

    $plan = DB::table('plans')->where(['id' => $plan_id, 'hospital_id' => $hospital_id, 'status' => 1, 'is_del' => 0])->first();
    if (!$plan) return ['status'=>false,'msg'=>"号源不可用"];
    //判断个检/团检类型
    if ($plan->use_type <> 0 and $plan->use_type <> $type) {
      $type_temp = '';
      if ($plan->use_type == 1) $type_temp = '个检';
      if ($plan->use_type == 2) $type_temp = '团检';
      return ['status'=>false,'msg'=>"此号源为" . $type_temp . "号源，不可用"];
    }
    //判断是否是预留号源
    if ($plan->type <> 1) return  ['status'=>false,'msg'=>"此号源为预留号源，不可用"];
    //判断是否是vip
    //判断性别
    if ($plan->sex <> 0 and $plan->sex <> $sex) return ['status'=>false,'msg'=>"此号源性别与体检人性别不符，不可用"];
    //判断体检类型checkup_type
    if(!!$checkup_type_id){
       $checkup_type_array=json_decode($plan->checkup_type_id,true);
       if(!in_array($checkup_type_id,$checkup_type_array)){
         return ['status'=>false,'msg'=>"此号源体检类型与套餐不匹配，不可用"];
       }
    }
    //判断金额
    if ($plan->use_type == 1 and $plan->amount_limit1 <> 0) {
      if ($price < $plan->amount_limit1) return  ['status'=>false,'msg'=>"未达到此号源限制的金额，不可用"];
    }
    if ($plan->use_type == 2 and $plan->amount_limit2 <> 0) {
      if ($price < $plan->amount_limit2) return  ['status'=>false,'msg'=>"未达到此号源限制的金额，不可用"];
    }
    //判断时间是否过期
    $plan_datetime = $plan->date . ' ' . $plan->time;
    if ($plan_datetime < date('Y-m-d H:i:s')) return  ['status'=>false,'msg'=>"号源已过期，不可用"];


    return ['status'=>true,'msg'=>"",'plan'=>$plan];
  }
}
