course/app/common/service/TeacherScheduleTimeService.php
2024-07-15 00:09:59 +08:00

98 lines
3.1 KiB
PHP

<?php
namespace app\common\service;
use app\common\model\Teacher;
use app\common\model\TeacherScheduleTime;
use app\constant\ResponseCode;
use DateTime;
use think\Exception;
class TeacherScheduleTimeService
{
/**
* @desc 添加空闲时间
* @param $request
* @return array|void
*/
public function addFreeTime($request)
{
try {
if (empty($request->teacher)) {
throw new Exception('请教师登陆后再设置');
}
$teacher = Teacher::where(['id' => $request->teacher->id])->findOrEmpty();
if ($teacher->isEmpty()) {
throw new Exception('未找到教师信息,设置失败');
}
// $free_time = [
// '2024-7-14'=>[
// '9:00-10:00',
// '10:00-11:00',
// '11:00-12:00',
// ],
// '2024-7-15'=>[
// '14:00-15:00',
// '15:00-16:00',
// '16:00-17:00',
// ],
// '2024-7-16'=>[
// '9:00-10:00',
// '10:00-11:00',
// '11:00-12:00',
// ],
// '2024-7-17'=>[
// '9:00-10:00',
// '10:00-11:00',
// '11:00-12:00',
// ]
// ];
$data = $request->post();
$free_time = json_decode($data['schedule_time'], true);
if (empty($free_time)) {
throw new Exception('请选择时间段之后再提交');
}
foreach ($free_time as $free_date => $times) {
if ($times) {
foreach ($times as $time) {
$time_period = explode('-', $time);
$firstDate = new DateTime($free_date . ' ' . $time_period[0]);
$secondDate = new DateTime($free_date . ' ' . $time_period[1]);
$diff = $secondDate->diff($firstDate);
$h = $diff->h;
$m = round($diff->i / 60, 2);
$hour = round($h + $m, 2);
$free_data = [
'teacher_id' => $request->teacher->id,
'date' => $free_date,
'time' => $time,
'hour' => $hour,
'month' => date('Y-m', strtotime($free_date)),
];
//@todo:判断是否已经存在
$res = TeacherScheduleTime::create($free_data);
if(!$res){
throw new Exception('保存失败');
}
}
}
}
return [
'code' => ResponseCode::SUCCESS,
'msg' => '保存成功'
];
} catch (Exception $e) {
return [
'code' => ResponseCode::FAIL,
'msg' => $e->getMessage()
];
}
}
}