package com.org.web.hospital.service;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.org.system.enums.YesOrNoState;
import com.org.utils.SecurityUtil;
import com.org.utils.exception.CustomException;
import com.org.web.hospital.domain.BcHospitalRecord;
import com.org.web.hospital.mapper.BcHospitalRecordMapper;
import com.org.web.person.domain.BcPersonSupport;
import com.org.web.person.service.BcPersonSupportService;
import com.org.web.room.domain.BcRoom;
import com.org.web.room.domain.BcRoomBed;
import com.org.web.room.service.BcRoomBedService;
import com.org.web.room.service.BcRoomService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class BcHospitalRecordService extends ServiceImpl<BcHospitalRecordMapper, BcHospitalRecord> {

    @Autowired
    BcPersonSupportService personSupportService;

    @Autowired
    BcRoomService bcRoomService;

    @Autowired
    BcRoomBedService bcRoomBedService;

    @Transactional(rollbackFor = Exception.class)
    public boolean executeSaveOrUpdate(BcHospitalRecord record) {
        log.info("BcHospitalRecordService - executeSaveOrUpdate record:{}", record);


        if (ObjectUtil.isEmpty(record.getId())) {
            checkParams(record, false);

            record.setCreateBy(SecurityUtil.getUserId());
            record.setCreateTime(new Date());
            record.setIsDelete(YesOrNoState.NO.getState());

            if (null == record.getCheckInTime()) {
                record.setCheckInTime(new Date()); // 入住时间
            }

        } else {
            if (record.getType() == 1) checkParams(record, true);

            record.setUpdateBy(SecurityUtil.getUserId());
            record.setUpdateTime(new Date());

            if (record.getType() == 2) {
                // 退房 查询是否存在入住信息
//                BcHospitalRecord lastRecordByPersonId = baseMapper.getLastRecordByPersonId(record.getPersonId());
                if (null == record.getCheckOutTime()) {
                    record.setCheckOutTime(new Date()); // 退房时间
                }

            }
        }
        saveOrUpdate(record);

        return true;
    }

    public void checkParams(BcHospitalRecord record, boolean isExcludeSelf) {
        BcPersonSupport oldPerson = personSupportService.getById(record.getPersonId());
        if (ObjectUtil.isNull(oldPerson)) {
            throw new CustomException("人员不存在");
        }

        BcRoomBed roomBed = bcRoomBedService.getById(record.getBedId());
        if (ObjectUtil.isNull(roomBed)) {
            throw new CustomException("房间床位不存在");
        }

        // 入住  查询该人员是否存在其他入住信息
        BcHospitalRecord lastRecord = baseMapper.getLastRecordByPersonId(record.getPersonId(), null);
        boolean personFlag = true;
        if (null != lastRecord ) { // 存在入住信息且退房时间为空
            if (isExcludeSelf && lastRecord.getId() != record.getId()) personFlag = false;

            if (!isExcludeSelf || !personFlag) {  // 新增时 或 编辑不一样了
                BcRoom bcRoom = bcRoomService.getById(lastRecord.getRoomId());
                BcRoomBed bcRoomBed = bcRoomBedService.getById(lastRecord.getBedId());
                throw new CustomException("人员已存在入住记录，房间床位为：" + bcRoom.getName() + bcRoomBed.getName());
            }
        }

        // 入住  查询该床位是否存在其他入住信息
        BcHospitalRecord lastRecordBed = baseMapper.getLastRecordByPersonId(null, record.getBedId());
        boolean bedFlag = true;
        if (null != lastRecordBed ) { // 存在入住信息且退房时间为空
            if (isExcludeSelf && lastRecordBed.getId() != record.getId()) bedFlag = false;

            if (!isExcludeSelf || !bedFlag) { // 新增时 或 编辑不一样了
                throw new CustomException("床位已使用，请选择其他房间床位");
            }
        }
    }

    public BcHospitalRecord getDetail(Long id) {
        BcHospitalRecord record = this.getById(id);
        if (null != record) {
            // 查询人员名称
            BcPersonSupport oldPerson = personSupportService.getById(record.getPersonId());
            record.setPersonName(oldPerson.getName());
        }
        return record;
    }

    /**
     * 列表查询
     */
    public List<BcHospitalRecord> queryList(BcHospitalRecord record) {
        log.info("BcHospitalRecordService - queryList record:{}", record);

        return baseMapper.queryList(record);
    }

    public List<BcHospitalRecord> checkinList(BcHospitalRecord record) {
        log.info("BcHospitalRecordService - checkinList record:{}", record);

        record.setType(1);
        return baseMapper.checkList(record);
    }

    public List<BcHospitalRecord> checkoutList(BcHospitalRecord record) {
        log.info("BcHospitalRecordService - checkoutList record:{}", record);

        record.setType(2);
        return baseMapper.checkList(record);
    }

    /**
     * 根据人员查询入院记录
     * @param personId
     * @return
     */
    public BcHospitalRecord getRecordByPersonId(Long personId) {
        BcHospitalRecord record = new BcHospitalRecord();
        record.setPersonId(personId);

        List<BcHospitalRecord> bcHospitalRecords = baseMapper.checkList(record);
        if (null != bcHospitalRecords && !bcHospitalRecords.isEmpty()) return bcHospitalRecords.get(0);

        return null;
    }


    /**
     * 根据床位查询入院记录
     */
    public BcHospitalRecord getRecordByBedId(Long bedId) {
        BcHospitalRecord record = new BcHospitalRecord();
        record.setBedId(bedId);
        record.setType(1);

        List<BcHospitalRecord> bcHospitalRecords = baseMapper.checkList(record);
        if (null != bcHospitalRecords && !bcHospitalRecords.isEmpty()) {
            BcHospitalRecord hospitalRecord = bcHospitalRecords.get(0);
            BcPersonSupport person = personSupportService.getById(hospitalRecord.getPersonId());
            if (ObjectUtil.isNotNull(person)) {
                hospitalRecord.setPersonName(person.getName());
            }
            return hospitalRecord;
        }

        return null;
    }

    /**
     * 删除
     */
    public boolean del(Long id) {
        log.info("BcHospitalRecordService - del id:{}", id);

        BcHospitalRecord hospitalRecord = getById(id);
        if (ObjectUtil.isEmpty(hospitalRecord)) {
            throw new CustomException("删除记录不存在");
        }
        hospitalRecord.setIsDelete(YesOrNoState.YES.getState());
        hospitalRecord.setDeleteBy(SecurityUtil.getUserId());
        hospitalRecord.setDeleteTime(new Date());
        return updateById(hospitalRecord);
    }

    /**
     * 删除
     */
    public void delByPersonId(Long personId) {
        log.info("BcHospitalRecordService - delByPersonId personId:{}", personId);
        baseMapper.deleteByPersonId(personId, SecurityUtil.getUserId());
    }

}
