<?php

namespace App\Http\Controllers\API\Admin\YeWu;

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

class AppointmentTypeController extends Controller
{
    //各种预约方式数量统计
    public function countAppointmentType(){
        $searchInfo = request('searchInfo');
        $today = date('Y-m-d'); // 获取今天日期

        // 按预约类型统计
        $list = DB::table('s_list');
        if(isset($searchInfo['dateRange'])){
            $list = $list->whereBetween('s_list.reservation_date', $searchInfo['dateRange']);
        }
        $list = $list
            ->whereIn('s_list.list_status',[1,2,3])
            ->where(['s_list.is_del' => 0, 's_list.is_nullify' => 0])
            ->select(
                'appointment_type_id',
                's_appointment_type.name',
                DB::raw('count(*) as count'),
                // 统计爽约数量：list_status=1 且 reservation_date < 今天
                DB::raw('SUM(CASE WHEN s_list.list_status = 1 AND s_list.reservation_date < "'.$today.'" THEN 1 ELSE 0 END) as break_appointment'),
                // 计算爽约率（爽约数/总数，保留两位小数）
                DB::raw('ROUND(SUM(CASE WHEN s_list.list_status = 1 AND s_list.reservation_date < "'.$today.'" THEN 1 ELSE 0 END) / COUNT(*) * 100, 2) as break_appointment_rate')
            )
            ->leftJoin('s_appointment_type', 's_list.appointment_type_id', '=', 's_appointment_type.id')
            ->groupBy('appointment_type_id', 's_appointment_type.name')
            ->get();

        // 按月统计（保持原有逻辑不变）
        $monthList = DB::table('s_list');
        if(isset($searchInfo['dateRange'])){
            $monthList = $monthList->whereBetween('s_list.reservation_date', $searchInfo['dateRange']);
        }
        $monthList = $monthList
            ->whereIn('s_list.list_status',[1,2,3])
            ->where(['s_list.is_del' => 0,'s_list.is_nullify' => 0])
            ->select(
                DB::raw('DATE_FORMAT(s_list.reservation_date, "%Y-%m") as month'),
                DB::raw('count(*) as count')
            )
            ->groupBy('month')
            ->get();
     

        return \Yz::Return(true, '操作成功', ['list'=>$list,'monthList'=>$monthList]);
    }
}
