package com.eitc.patient.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.eitc.common.core.domain.entity.SysUser;
import com.eitc.common.utils.bean.BeanUtils;
import com.eitc.patient.domain.PatientAppointment;
import com.eitc.patient.service.IDoctorService;
import com.eitc.patient.service.IPatientAppointmentService;
import com.eitc.patient.utils.PatientUtil;
import com.eitc.patient.vo.DoctorVO;
import com.eitc.system.mapper.SysUserMapper;
import com.eitc.system.utils.UserCacheUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * DoctorServiceImpl
 *
 * @author mtx
 * @date: 2024/06/13 14:58
 */
@Service
public class DoctorServiceImpl implements IDoctorService {

    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private IPatientAppointmentService patientAppointmentService;


    /**
     * 医生列表
     *
     * @return 返回结果
     * @author mtx
     * @date: 2024/6/13 15:01
     */
    @Override
    public List<DoctorVO> list(String selectDateStr) throws ParseException {
        Date date = new Date();
        // 获取医生列表
        List<SysUser> sysUsers = sysUserMapper.selectUserList(new SysUser());
        List<DoctorVO> list = new ArrayList<>();
        if (CollectionUtils.isEmpty(sysUsers)) {
            return list;
        }

        Date selectDate = null;
        if(StringUtils.isNotEmpty(selectDateStr)){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            selectDate = sdf.parse(selectDateStr);
        }

        for (SysUser sysUser : sysUsers) {
            // 医生是否在排班
            if (!PatientUtil.checkDoctorWorkStatus(String.valueOf(sysUser.getUserId()), selectDate)) {
                continue;
            }
            DoctorVO vo = new DoctorVO();
            BeanUtils.copyProperties(sysUser, vo);
            long count = patientAppointmentService.count(Wrappers.<PatientAppointment>lambdaQuery()
                    .lt(PatientAppointment::getAppointmentStartTime, date)
                    .gt(PatientAppointment::getAppointmentEndTime, date)
                    .eq(PatientAppointment::getAttendingDoctorId, sysUser.getUserId()));

            vo.setIsFree(count > 0 ? 1 : 0);
            vo.setDeptName(UserCacheUtil.getSysDeptById(sysUser.getDeptId()).getDeptName());
            list.add(vo);
        }
        return list;
    }
}
