package cn.hnthyy.thmz.service.impl.his.mz;

import cn.hnthyy.thmz.entity.MzException;
import cn.hnthyy.thmz.entity.his.mz.MzDrugWin;
import cn.hnthyy.thmz.mapper.his.mz.MzDrugWinMapper;
import cn.hnthyy.thmz.pageDto.MzDrugWinPageDto;
import cn.hnthyy.thmz.service.his.mz.MzDrugWinService;
import cn.hnthyy.thmz.vo.MzDrugWinVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class MzDrugWinServiceImpl implements MzDrugWinService {
    @SuppressWarnings("all")
    @Autowired
    private MzDrugWinMapper mzDrugWinMapper;

    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    @Override
    public MzDrugWin queryMinMzDrugWin(String groupNo) throws MzException {
        mzDrugWinMapper.updateForBlock(groupNo);
        MzDrugWin mzDrugWin=mzDrugWinMapper.selectMinMzDrugWin(groupNo);
        if (mzDrugWin == null) {
            throw new MzException("当前药房"+groupNo+"没有在使用中的发药窗口，请先设置！");
        }
        if(mzDrugWin.getPatientNum()==null){
            mzDrugWin.setPatientNum(1);
        }else {
            mzDrugWin.setPatientNum(mzDrugWin.getPatientNum()+1);
        }
        mzDrugWinMapper.updateMzDrugWin(mzDrugWin);
        return mzDrugWin;
    }

    @Override
    public MzDrugWin queryMzDrugWinByGroupNoAndWinNo(String groupNo, String winNo) {
        return mzDrugWinMapper.selectMzDrugWinByGroupNoAndWinNo(groupNo,winNo);
    }

    @Override
    public List<MzDrugWinVo> queryMzDrugWinPage(MzDrugWinPageDto mzDrugWinPageDto) {
        return mzDrugWinMapper.selectMzDrugWinPage(mzDrugWinPageDto);
    }

    @Override
    public int countMzDrugWin(MzDrugWin mzDrugWin) {
        return mzDrugWinMapper.countMzDrugWin(mzDrugWin);
    }

    @Override
    public int saveMzDrugWin(MzDrugWinVo mzDrugWinVo) {
        if (mzDrugWinVo.getIsEdit() == 1){//修改
            mzDrugWinMapper.updateMzDrugWinVo(mzDrugWinVo);
        }else{
            mzDrugWinMapper.insertMzDrugWin(mzDrugWinVo);
        }
        return 0;
    }

    @Override
    public int removeByGroupNoWinNo(String groupNo,String winNo) {
        return mzDrugWinMapper.deleteByGroupNoWinNo(groupNo,winNo);
    }
}
