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

import cn.hnthyy.thmz.entity.MzException;
import cn.hnthyy.thmz.entity.his.mz.MzSerialNo;
import cn.hnthyy.thmz.mapper.his.mz.MzSerialNoMapper;
import cn.hnthyy.thmz.service.his.mz.MzSerialNoService;
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.Date;

@Service
public class MzSerialNoServiceImpl implements MzSerialNoService {
    @SuppressWarnings("all")
    @Autowired
    private MzSerialNoMapper mzSerialNoMapper;

    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    @Override
    public int getMzSerialNo() throws MzException {
        mzSerialNoMapper.updateForBlock(new Date());
        MzSerialNo mzSerialNo = mzSerialNoMapper.selectMzSerialNo();
        if (mzSerialNo == null) {
            throw new MzException("序列号生成器不存在，请先设置！");
        }
        mzSerialNo.setNewSerialOut(mzSerialNo.getSerialOut() + 1);
        int num = mzSerialNoMapper.updateMzSerialNo(mzSerialNo);
        if (num == 0) {
            throw new MzException("获取挂号流水号失败，请重试!");
        }
        return mzSerialNo.getNewSerialOut();
    }

    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    @Override
    public String getMzPatientNo() throws MzException {
        mzSerialNoMapper.updateForBlock(new Date());
        MzSerialNo mzSerialNo = mzSerialNoMapper.selectMzSerialNo();
        if (mzSerialNo == null) {
            throw new MzException("序列号生成器不存在，请先设置！");
        }
        Integer newOutpatientNo=Integer.valueOf(mzSerialNo.getOutpatientNo()) + 1;
        mzSerialNo.setNewOutpatientNo(newOutpatientNo.toString());
        int num = mzSerialNoMapper.updateMzSerialNo(mzSerialNo);
        if (num == 0) {
            throw new MzException("获取挂号流水号失败，请重试!");
        }
        return mzSerialNo.getNewOutpatientNo()+"-4";
    }

    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    @Override
    public int getSerialNo() throws MzException {
        mzSerialNoMapper.updateForBlock(new Date());
        MzSerialNo mzSerialNo = mzSerialNoMapper.selectMzSerialNo();
        if (mzSerialNo == null) {
            throw new MzException("序列号生成器不存在，请先设置！");
        }
        mzSerialNo.setNewSerialNew(mzSerialNo.getSerialNew() + 1);
        int num = mzSerialNoMapper.updateMzSerialNo(mzSerialNo);
        if (num == 0) {
            throw new MzException("获取缴费流水号失败，请重试!");
        }
        return mzSerialNo.getNewSerialNew();
    }
}
