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

import cn.hnthyy.thmz.Utils.DateUtil;
import cn.hnthyy.thmz.entity.MzException;
import cn.hnthyy.thmz.entity.his.mz.Employee;
import cn.hnthyy.thmz.entity.his.mz.MzyRequest;
import cn.hnthyy.thmz.entity.his.mz.MzyZdChargeType;
import cn.hnthyy.thmz.enums.YesNoEnum;
import cn.hnthyy.thmz.mapper.his.mz.EmployeeMapper;
import cn.hnthyy.thmz.mapper.his.mz.MzyRequestMapper;
import cn.hnthyy.thmz.mapper.his.mz.MzyZdChargeTypeMapper;
import cn.hnthyy.thmz.service.his.mz.MzyRequestService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
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.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class MzyRequestServiceImpl implements MzyRequestService {
    @SuppressWarnings("all")
    @Autowired
    private MzyRequestMapper mzyRequestMapper;
    @SuppressWarnings("all")
    @Autowired
    private EmployeeMapper employeeMapper;
    @SuppressWarnings("all")
    @Autowired
    private MzyZdChargeTypeMapper mzyZdChargeTypeMapper;

    @Override
    public List<MzyRequest> queryMzyRequestByRequestDay(String requestDay) {
        return mzyRequestMapper.selectMzyRequestByRequestDay(requestDay);
    }

    @Override
    public List<String> queryUnitCodeByRequestDay(String requestDay, String ampm) {
        return mzyRequestMapper.selectUnitCodeByRequestDay(requestDay, ampm);
    }

    @Override
    public List<MzyRequest> queryDoctorCodeByRequestDay(String requestDay, String unitCode, String ampm, String chargeType) {
        List<MzyRequest> mzyRequests = mzyRequestMapper.selectDoctorCodeByRequestDay(requestDay, unitCode, ampm, chargeType);
        mzyRequests.forEach(mzyRequest -> {
            if (mzyRequest != null && StringUtils.isNotBlank(mzyRequest.getDoctorCode()) && mzyRequest.getDoctorCode().matches("[\u4E00-\u9FA5]+")) {
                Employee employee = employeeMapper.selectByUserName(mzyRequest.getDoctorCode());
                if (employee == null) {
                    mzyRequest.setDoctorCode(null);
                } else {
                    mzyRequest.setDoctorCode(employee.getEmployeeCode());
                }
            }
        });
        return mzyRequests;
    }

    @Override
    public List<MzyZdChargeType> queryChargeTypeByRequestDay(String requestDay, String unitCode, String ampm) {
        List<String> chargeTypes = mzyRequestMapper.selectChargeTypeByRequestDay(requestDay, unitCode, ampm);
        if (chargeTypes == null || chargeTypes.size() == 0) {
            return null;
        }
        List<MzyZdChargeType> list = new ArrayList<>();
        chargeTypes.forEach(ct -> {
            if (StringUtils.isNotBlank(ct)) {
                List<MzyRequest> mzyRequests = mzyRequestMapper.selectRequestByRequestDay(requestDay, unitCode, ampm, ct, null);
                if (mzyRequests != null && mzyRequests.size() > 0) {
                    MzyZdChargeType mzct = mzyZdChargeTypeMapper.selectByCode(ct);
                    if (mzct != null) {
                        list.add(mzct);
                    }
                }

            }
        });
        return list;
    }

    @Override
    public Integer getReqOrder(MzyRequest mzyRequest) throws MzException {
        if (mzyRequest == null) {
            throw new MzException("没有查询到匹配的可挂号表，请先创建！");
        }

        List<MzyRequest> mzyRequests = mzyRequestMapper.selectRequestByRequestDay(DateFormatUtils.format(mzyRequest.getRequestDay(), "yyyy-MM-dd"), mzyRequest.getUnitCode(), mzyRequest.getAmpm(), mzyRequest.getChargeType(), mzyRequest.getDoctorCode());
        if (mzyRequests == null || mzyRequests.size() == 0) {
            throw new MzException("没有查询到匹配的可挂号表，请先创建！");
        }
        MzyRequest oldMzyRequest = mzyRequests.get(0);
        Integer oldBespeakNo = oldMzyRequest.getBespeakNo();
        Integer bespeakNo = mzyRequest.getBespeakNo();
        Integer leftNum = mzyRequest.getLeftNum();
        if (oldBespeakNo > bespeakNo) {
            bespeakNo = oldBespeakNo;
            leftNum = oldMzyRequest.getLeftNum();
        }
        mzyRequest.setOrgiBespeakNo(bespeakNo);
        mzyRequest.setOrgiLeftNum(leftNum);
        Integer newBespeakNo = bespeakNo + 1;
        Integer newLeftNum = leftNum - 1;
        mzyRequest.setBespeakNo(newBespeakNo);
        mzyRequest.setLeftNum(newLeftNum);
        int num = mzyRequestMapper.updateMzyRequest(mzyRequest);
        mzyRequestMapper.updateOriMzyRequest(mzyRequest);
        if (num == 0) {
            throw new MzException("更新挂号表信息出错，请重试或者联系管理员！");
        }
        return mzyRequest.getOrgiBespeakNo();
    }

    @Override
    public int synchronizationRequest() {
        return mzyRequestMapper.synchronizationRequest();
    }

    @Override
    public List<MzyRequest> queryRequestForToday(Date today) {
        return mzyRequestMapper.selectRequestForToday(today);
    }

    @Override
    public MzyRequest queryMzyRequestByAllParams(MzyRequest mzyRequest) {
        return mzyRequestMapper.selectMzyRequestByAllParams(mzyRequest);
    }

    @Override
    public int saveRequest(MzyRequest mzyRequest) {
        return mzyRequestMapper.insertRequest(mzyRequest);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    public int saveRequest(List<MzyRequest> mzyRequests, String opId) throws MzException {
        Date now = new Date();
        int index = 1;
        for (MzyRequest m : mzyRequests) {
            if (m != null) {
                if (m.getChargeType() == null) {
                    m.setChargeType("");
                }
                if (m.getCheckFee() == null) {
                    m.setCheckFee(BigDecimal.ZERO);
                }
                if(m.getDoctorCode()==null){
                    m.setDoctorCode("");
                }
                if(m.getGroupCode()==null){
                    m.setGroupCode("");
                }
                m.setOpId(opId);
                m.setSysDate(now);
                if (m.getId() != null) {
                    MzyRequest dbMzyRequest = mzyRequestMapper.selectMzyRequestById(m.getId());
                    m.setRequestDayOld(dbMzyRequest.getRequestDay());
                    m.setAmpmOld(dbMzyRequest.getAmpm());
                    m.setUnitCodeOld(dbMzyRequest.getUnitCode());
                    m.setDoctorCodeOld(dbMzyRequest.getDoctorCode());
                    m.setChargeTypeOld(dbMzyRequest.getChargeType());
                    int num= mzyRequestMapper.updateMzyRequestNew(m);
                    if(num<=0){
                        throw new MzException("第【"+index+"】条数据重复，请确认!");
                    }
                } else {
                    m.setGroupCode("");
                    m.setDelFlag(YesNoEnum.NO.code);
                   int num=mzyRequestMapper.insertRequest(m);
                   if(num<=0){
                        throw new MzException("第【"+index+"】条数据重复，请确认!");
                    }
                }
                index++;
            }
        }
        return mzyRequests.size();
    }

    @Override
    public List<MzyRequest> queryByTimes(Date beginDate, Date endDate, String unitCode, String ampm) {
        return mzyRequestMapper.selectByTimes(beginDate, endDate, unitCode, ampm);
    }

    @Override
    public MzyRequest queryById(Long id) {
        return mzyRequestMapper.selectMzyRequestById(id);
    }

    @Override
    public List<Map<String, Object>> queryNumByDateAndDept(Date beginDate, Date endDate, String unitCode) {
        return mzyRequestMapper.selectNumByDateAndDept(beginDate,endDate,unitCode);
    }

    @Override
    public List<Map<String, Object>> queryDoctorByDateAndDept(Date requestDay, List<String> ampms, String unitCode) {
        return mzyRequestMapper.selectDoctorByDateAndDept(requestDay,ampms,unitCode);
    }

    @Override
    public List<Map<String,Object>> queryRequestByDateAndDeptAndDoctor(Date requestDay, List<String> ampms, String unitCode, String doctorCode) {
        return mzyRequestMapper.selectRequestByDateAndDeptAndDoctor(requestDay,ampms,unitCode,doctorCode);
    }

    @Override
    public int removeMzyRequestById(Long id) {
        return mzyRequestMapper.deleteMzyRequestById(id);
    }

    @Override
    public MzyZdChargeType calculateAddition(Long mzyRequestId, Date birthDay) throws MzException {
        if (mzyRequestId==null) {
            throw new MzException("排班主键不能为空");
        }
        MzyRequest mzyRequest=mzyRequestMapper.selectMzyRequestById(mzyRequestId);
        if(mzyRequest==null){
            throw new MzException("排班信息不存在");
        }
        MzyZdChargeType mzyZdChargeType=mzyZdChargeTypeMapper.selectByCode(mzyRequest.getChargeType());
        if(mzyZdChargeType==null){
            throw new MzException("根据号别编号查询号别失败,没有对应的号别信息");
        }
        BigDecimal checkFee=mzyRequest.getCheckFee();
        checkFee=checkFee==null?BigDecimal.ZERO:checkFee;
        //检查费挂号表没有字段保存，故借用其他费用存放
        if(mzyZdChargeType.getOthFee()!=null){
            checkFee=checkFee.add(mzyZdChargeType.getOthFee());
        }
        mzyZdChargeType.setOthFee(checkFee);
        if (birthDay!=null) {
            int age=DateUtil.getAge(birthDay);
            //6岁以内的小朋友挂号费上调50%
            if(age<=6){
                if(mzyZdChargeType.getReqFee()!=null){
                    checkFee=checkFee.add(mzyZdChargeType.getReqFee());
                }
                if(mzyZdChargeType.getClinicFee()!=null){
                    checkFee=checkFee.add(mzyZdChargeType.getClinicFee());
                }
                BigDecimal tempFee = checkFee.multiply(BigDecimal.valueOf(0.5));
                mzyZdChargeType.setOthFee(mzyZdChargeType.getOthFee().add(tempFee));
                mzyZdChargeType.setMessage("根据【湘医保发〔2020〕51 号】价格通知，6岁以内的小朋友挂号费上调50%!");
            }
        }
        return mzyZdChargeType;
    }
}
