package thyyxxk.webserver.service.medicaladvice.patientinfo;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import thyyxxk.webserver.dao.his.medicaladvice.patientinfo.BaByInfoDao;
import thyyxxk.webserver.entity.medicaladvice.medicamanage.patientinfo.BabyInfoVo;
import thyyxxk.webserver.utils.AssertUtil;
import thyyxxk.webserver.utils.CommonUtil;

import java.util.List;

/**
 * @Description:
 * @Author:lihong
 * @Date: 2023/12/19
 */
@Slf4j
@Service
public class BaByInfoService {
    @Autowired
    private BaByInfoDao dao;
    /**
     * @description: 查询婴儿信息
     * @author: lihong
     * @date: 2023/12/19 10:37
     * @param: query
     * @return: thyyxxk.webserver.entity.medicaladvice.medicamanage.patientinfo.BabyInfoVo
     **/
    public List<BabyInfoVo> queryInfo(BabyInfoVo query) {
        AssertUtil.isnotBlank(query.getInpatientNo(), "住院号不能为空");
        query.setInpatientNo(query.getInpatientNo()+"$%");
        List<BabyInfoVo> list = dao.selectInfo(query.getInpatientNo());
        CommonUtil.BeanTrim(list);
        return list;
    }
    @Transactional(rollbackFor = Exception.class)
    public void deleteBaby(BabyInfoVo query) {
        dao.deleteAPatientMi(query.getInpatientNo());
        dao.deletezyActpatient(query.getInpatientNo(), query.getAdmissTimes());
    }

    @Transactional(rollbackFor = Exception.class)
    public void saveBabyInfo(BabyInfoVo query) {
        AssertUtil.isnotBlank(query.getInpatientNo(), "住院号不能为空");
        AssertUtil.isnotBlank(query.getBirthDate(), "出生日期不能为空");
        AssertUtil.isnotBlank(query.getSex(), "性别不能为空");
        String inpatientNo = query.getInpatientNo();
        List<BabyInfoVo> list = dao.selectInfo(inpatientNo+"$%");
        if(CollUtil.isNotEmpty(list)){
            Integer num = list.stream().map(item -> Convert.toInt(item.getInpatientNo().trim().split("\\$")[1])).max(Integer::compareTo).get();
            query.setInpatientNo(StrUtil.format("{}${}",inpatientNo,(num+1)));
            query.setName(StrUtil.format("(婴{}){}",(num+1),query.getName()));
        }else {
            query.setInpatientNo(query.getInpatientNo()+"$1");
            query.setName(StrUtil.format("(婴1){}",query.getName()));
        }
        dao.insertAPatientMi(query);
        dao.insertZyActpatient(query,inpatientNo);
    }
}
