package cn.hnthyy.thmz.controller.mz;

import cn.hnthyy.thmz.Utils.DateUtil;
import cn.hnthyy.thmz.Utils.TokenUtil;
import cn.hnthyy.thmz.comment.UserLoginToken;
import cn.hnthyy.thmz.entity.MzException;
import cn.hnthyy.thmz.entity.his.YpZdDict;
import cn.hnthyy.thmz.entity.his.mz.*;
import cn.hnthyy.thmz.entity.his.zd.ZdUnitCode;
import cn.hnthyy.thmz.entity.thmz.DispensingWindows;
import cn.hnthyy.thmz.entity.thmz.RadSendRecord;
import cn.hnthyy.thmz.entity.thmz.User;
import cn.hnthyy.thmz.enums.ConfirmFlagEnum;
import cn.hnthyy.thmz.service.his.YpZdDictService;
import cn.hnthyy.thmz.service.his.YpZdManufactoryService;
import cn.hnthyy.thmz.service.his.mz.*;
import cn.hnthyy.thmz.service.his.zd.ZdUnitCodeService;
import cn.hnthyy.thmz.service.thmz.DispensingSocketService;
import cn.hnthyy.thmz.service.thmz.DispensingWindowsService;
import cn.hnthyy.thmz.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Stream;

@Slf4j
@RestController
public class MzPharmacyController {

    @Autowired
    private MzPharmacyService mzPharmacyService;
    @Autowired
    private ZdUnitCodeService zdUnitCodeService;
    @Autowired
    private MzVisitTableService mzVisitTableService;
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private MzZdSupplyTypeService mzZdSupplyTypeService;
    @Autowired
    private MzChargeDetailService mzChargeDetailService;
    @Autowired
    private YpZdDictService ypZdDictService;
    @Autowired
    private YpZdManufactoryService ypZdManufactoryService;
    @Autowired
    private MzPatientMiService mzPatientMiService;
    @Autowired
    private MzOrderFrequencyService mzOrderFrequencyService;
    @Autowired
    private DispensingSocketService dispensingSocketService;
    @Autowired
    private DispensingWindowsService dispensingWindowsService;
    /**
     * 查询处方信息
     *
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/listMzChargeOrder", method = {RequestMethod.POST})
    public Map<String, Object> listMzChargeOrder(@RequestBody ChargeDetailPharmacyVo chargeDetailPharmacyVo) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            if (chargeDetailPharmacyVo == null || chargeDetailPharmacyVo.getMzChargeDetail() == null) {
                resultMap.put("code", -1);
                resultMap.put("message", "收费处方列表查询参数不能为空");
                return resultMap;
            }
            MzChargeDetail mzChargeDetail = chargeDetailPharmacyVo.getMzChargeDetail();
            if (StringUtils.isBlank(mzChargeDetail.getName())) {
                mzChargeDetail.setName(null);
            } else {
                mzChargeDetail.setName("%" + mzChargeDetail.getName() + "%");
            }
            if (StringUtils.isBlank(mzChargeDetail.getPatientId())) {
                mzChargeDetail.setPatientId(null);
            }
            List<MzChargeDetail> mzChargeDetails = mzPharmacyService.getMzChargeOrder(chargeDetailPharmacyVo);
            mzChargeDetails.forEach(chargeDetail -> {
                int radSend = mzPharmacyService.isRadSend(chargeDetail.getChargeItemCode());
                chargeDetail.setIsRadSend(radSend);
            });
            resultMap.put("code", 0);
            resultMap.put("message", "查询收费处方列表信息成功");
            resultMap.put("data", mzChargeDetails);
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("code", -1);
            resultMap.put("message", "查询收费处方列表失败，系统出错，请联系管理员");
            log.error("查询费用列表失败，系统异常，错误信息{}", e.getMessage());
            return resultMap;
        }
    }

    /**
     * 药房查询退药记录
     *
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/getYfRefundMedicine", method = {RequestMethod.POST})
    public Map<String, Object> getYfRefundMedicine(@RequestBody ChargeFeeParamsVo chargeFeeParamsVo) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            if (chargeFeeParamsVo == null) {
                resultMap.put("code", -1);
                resultMap.put("message", "查询门诊医生退药记录单失败,参数为空");
                return resultMap;
            }
            resultMap.put("code", 0);
            resultMap.put("message", "查询门诊医生退药记录单成功");
            if (StringUtils.isBlank(chargeFeeParamsVo.getName())) {
                chargeFeeParamsVo.setName(null);
            } else {
                chargeFeeParamsVo.setName("%" + chargeFeeParamsVo.getName() + "%");
            }
            if (StringUtils.isBlank(chargeFeeParamsVo.getSerialNo())) {
                chargeFeeParamsVo.setSerialNo(null);
            }
            if (StringUtils.isBlank(chargeFeeParamsVo.getPatientId())) {
                chargeFeeParamsVo.setPatientId(null);
            }
            if (StringUtils.isBlank(chargeFeeParamsVo.getGroupNoOut())) {
                chargeFeeParamsVo.setGroupNoOut(null);
            }
            int count = 0;
            List<YpMzFytjVo> ypMzFytjList = new ArrayList<>();
            if (chargeFeeParamsVo.getConfirmFlag().equals(2)) {
                ypMzFytjList = mzPharmacyService.getYpMzRefundFytjPage(chargeFeeParamsVo);
                count = mzPharmacyService.getYpMzRefundFytjCount(chargeFeeParamsVo);
            } else if (chargeFeeParamsVo.getConfirmFlag().equals(3)) {
                ypMzFytjList = mzPharmacyService.getYpMzRefundSucceedFytjPage(chargeFeeParamsVo);
                count = mzPharmacyService.getYpMzRefundSucceedFytjCount(chargeFeeParamsVo);
            }
            for (YpMzFytjVo ypMzFytj : ypMzFytjList) {
                if (StringUtils.isNotBlank(ypMzFytj.getWarnDept())) {
                    ZdUnitCode zdUnitCode = zdUnitCodeService.queryByCode(ypMzFytj.getWarnDept());
                    ypMzFytj.setWarnDeptName(zdUnitCode.getName());
                }
            }
            resultMap.put("data", ypMzFytjList);
            resultMap.put("total", count);
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询门诊医生退药记录单失败，错误信息{}", e.getMessage());
            resultMap.put("code", -1);
            resultMap.put("message", "查询门诊医生退药记录单失败");
            return resultMap;
        }
    }

    /**
     * 查询退药记录明细
     *
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/getRefundYpMx", method = {RequestMethod.POST})
    public Map<String, Object> getRefundYpMx(@RequestBody ChargeFeeParamsVo chargeFeeParamsVo) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            if (chargeFeeParamsVo == null) {
                resultMap.put("code", -1);
                resultMap.put("message", "查询已经确认的药品记录明细失败,参数为空");
                return resultMap;
            }
            if (StringUtils.isBlank(chargeFeeParamsVo.getPatientId())) {
                resultMap.put("code", -1);
                resultMap.put("message", "病人ID不能为空");
                return resultMap;
            }
            if (chargeFeeParamsVo.getTimes() == null) {
                resultMap.put("code", -1);
                resultMap.put("message", "门诊就诊次数不能为空");
                return resultMap;
            }
            if (StringUtils.isBlank(chargeFeeParamsVo.getOrderNo())) {
                resultMap.put("code", -1);
                resultMap.put("message", "处方号不能为空");
                return resultMap;
            }
            if (StringUtils.isBlank(chargeFeeParamsVo.getReceiptNo())) {
                resultMap.put("code", -1);
                resultMap.put("message", "门诊缴费次数不能为空");
                return resultMap;
            }
            if (StringUtils.isBlank(chargeFeeParamsVo.getGroupNoOut())) {
                resultMap.put("code", -1);
                resultMap.put("message", "药房编码不能为空");
                return resultMap;
            }
            resultMap.put("code", 0);
            resultMap.put("message", "查询退药的药品记录明细成功");
            //查询退药申请后的药品统计数据
            List<Map<String, Object>> ypMzFytjListRefund = mzPharmacyService.getPrescriptionYpMx(chargeFeeParamsVo);
            //查询退药申请前的药品统计数据
            chargeFeeParamsVo.setReceiptNo(chargeFeeParamsVo.getReceiptNo().substring(1));//去掉负号
            chargeFeeParamsVo.setConfirmFlag(ConfirmFlagEnum.CONFIRM.code);
            List<Map<String, Object>> ypMzFytjList = mzPharmacyService.getPrescriptionYpMx(chargeFeeParamsVo);
            for (Map<String, Object> stringObjectMap : ypMzFytjListRefund) {
                for (Map<String, Object> objectMap : ypMzFytjList) {
                    if (stringObjectMap.get("charge_item_code").equals(objectMap.get("charge_item_code"))) {
                        objectMap.put("dec_amount", stringObjectMap.get("quantity"));
                    }
                }
            }
            resultMap.put("data", ypMzFytjList);
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询退药的药品记录明细失败，错误信息{}", e.getMessage());
            resultMap.put("code", -1);
            resultMap.put("message", "查询退药的药品记录明细失败");
            return resultMap;
        }
    }

    /**
     * 退药处理
     *
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/refundMedicineProcessing", method = {RequestMethod.POST})
    public Map<String, Object> refundMedicineProcessing(@RequestBody List<MzRefundMedicineVo> mzRefundMedicineVos, HttpServletRequest httpServletRequest) throws MzException {
        User tokenUser = TokenUtil.getUser(httpServletRequest);
        Map<String, Object> resultMap = new HashMap<>();
        try {
            if (mzRefundMedicineVos == null && mzRefundMedicineVos.size() < 1) {
                resultMap.put("code", -1);
                resultMap.put("message", "退药处理失败,参数为空");
                return resultMap;
            }
            resultMap = mzPharmacyService.refundMedicineProcessing(mzRefundMedicineVos, tokenUser.getUserIdCode());
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("退药处理失败，错误信息{}", e.getMessage());
            resultMap.put("code", -1);
            resultMap.put("message", "退药处理失败");
            return resultMap;
        }
    }

    /**
     * 发药处理查询发药处方信息
     *
     * @param chargeFeeParamsVo
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/getSendMedicinePrescription", method = {RequestMethod.POST})
    public Map<String, Object> getSendMedicinePrescription(@RequestBody ChargeFeeParamsVo chargeFeeParamsVo) {
        Map<String, Object> resultMap = new HashMap<>();
        int count = 0;
        try {
            if (chargeFeeParamsVo == null) {
                resultMap.put("code", -1);
                resultMap.put("message", "发药处理查询处方记录失败,参数为空");
                return resultMap;
            }
            if (StringUtils.isBlank(chargeFeeParamsVo.getGroupNoOut())) {
                resultMap.put("code", -1);
                resultMap.put("message", "发药药房编码不能为空");
                return resultMap;
            }
            List<ChargeDetailInfoVo> fyclPrescription = new ArrayList<>();
            if (chargeFeeParamsVo.getConfirmFlag() == 0) {
                fyclPrescription = mzPharmacyService.getFyclWfyPrescriptionPage(chargeFeeParamsVo);
                count = mzPharmacyService.getFyclWfyPrescriptionCount(chargeFeeParamsVo);
                Iterator<ChargeDetailInfoVo> iterator = fyclPrescription.iterator();
                while (iterator.hasNext()) {
                    ChargeDetailInfoVo mzChargeDetail = iterator.next();
                    int number = mzPharmacyService.selectMzReceiptSerialCount(mzChargeDetail);
                    if (number > 0) {
                        count--;
                        iterator.remove();
                    } else {
                        if (StringUtils.isNotBlank(mzChargeDetail.getWarnDept())) {
                            ZdUnitCode zdUnitCode = zdUnitCodeService.queryByCode(mzChargeDetail.getWarnDept());
                            mzChargeDetail.setWarnDeptName(zdUnitCode.getName());
                        }
                        if (StringUtils.isNotBlank(mzChargeDetail.getDoctorCode())) {
                            Employee employee = employeeService.queryByUserCode(mzChargeDetail.getDoctorCode());
                            mzChargeDetail.setEmployeeName(employee.getEmployeeName());
                        }
                    }
                }
            } else {
                fyclPrescription = mzPharmacyService.getFyclYfyPrescriptionPage(chargeFeeParamsVo);
                count = mzPharmacyService.getFyclYfyPrescriptionCount(chargeFeeParamsVo);
                for (ChargeDetailInfoVo chargeDetailInfoVo : fyclPrescription) {
                    if (StringUtils.isNotBlank(chargeDetailInfoVo.getWarnDept())) {
                        ZdUnitCode zdUnitCode = zdUnitCodeService.queryByCode(chargeDetailInfoVo.getWarnDept());
                        chargeDetailInfoVo.setWarnDeptName(zdUnitCode.getName());
                    }
                    if (StringUtils.isNotBlank(chargeDetailInfoVo.getDoctorCode())) {
                        Employee employee = employeeService.queryByUserCode(chargeDetailInfoVo.getDoctorCode());
                        if (employee != null) {
                            chargeDetailInfoVo.setEmployeeName(employee.getEmployeeName());
                        }
                    }
                }
            }
            resultMap.put("code", 0);
            resultMap.put("message", "查询发药处理的处方信息成功");
            resultMap.put("data", fyclPrescription);
            resultMap.put("total", count);
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询发药处理的处方信息失败，错误信息{}", e.getMessage());
            resultMap.put("code", -1);
            resultMap.put("message", "查询发药处理的处方信息失败");
            return resultMap;
        }
    }

    /**
     * 发药处理查询处方详细信息
     *
     * @param mzChargeDetail
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/getFyclPrescriptionDetail", method = {RequestMethod.POST})
    public Map<String, Object> getFyclPrescriptionDetail(@RequestBody MzChargeDetail mzChargeDetail) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            if (mzChargeDetail == null) {
                resultMap.put("code", -1);
                resultMap.put("message", "发药处理查询处方记录失败,参数为空");
                return resultMap;
            }
            if (StringUtils.isBlank(mzChargeDetail.getGroupNo())) {
                resultMap.put("code", -1);
                resultMap.put("message", "发药药房编码不能为空");
                return resultMap;
            }
            if (StringUtils.isBlank(mzChargeDetail.getPatientId())) {
                resultMap.put("code", -1);
                resultMap.put("message", "病人编码不能为空");
                return resultMap;
            }
            if (mzChargeDetail.getOrderNo() == null) {
                resultMap.put("code", -1);
                resultMap.put("message", "处方号不能为空");
                return resultMap;
            }
            if (mzChargeDetail.getRealNo() == null) {
                resultMap.put("code", -1);
                resultMap.put("message", "发票流水号不能为空");
                return resultMap;
            }
            if (mzChargeDetail.getReceiptNo() == null) {
                resultMap.put("code", -1);
                resultMap.put("message", "发票分票号不能为空");
                return resultMap;
            }
            if (mzChargeDetail.getTimes() == null) {
                resultMap.put("code", -1);
                resultMap.put("message", "次数不能为空");
                return resultMap;
            }
            List<MzSendMedicineVo> cfxxList = mzPharmacyService.getFyclPrescriptionDetail(mzChargeDetail);
            if (cfxxList.size() > 0) {
                MzVisitTable visit = mzVisitTableService.queryByPatientIdAndTimes(mzChargeDetail.getPatientId(), mzChargeDetail.getTimes());
                cfxxList.get(0).setIcdText(visit.getIcdText());
                String warnDeptName = zdUnitCodeService.queryDeptNameByIdInCache(cfxxList.get(0).getWarnDept());
                cfxxList.get(0).setWarnDeptName(warnDeptName);
                Employee employee = employeeService.queryByUserCode(cfxxList.get(0).getDoctorCode());
                cfxxList.get(0).setEmployeeName(employee.getEmployeeName());
            }
            for (MzSendMedicineVo mzSendMedicineVo : cfxxList) {
                String drugUnitName = mzPharmacyService.getYpUnitName(mzSendMedicineVo.getDrugUnit());
                String ypUnitName = mzPharmacyService.getYpUnitName(mzSendMedicineVo.getYpUnit());
                mzSendMedicineVo.setDrugUnitName(drugUnitName);
                mzSendMedicineVo.setYpUnitName(ypUnitName);
                if(mzSendMedicineVo.getSupplyCode() != null){
                    MzZdSupplyType mzZdSupplyType = mzZdSupplyTypeService.selectMzZdSupplyTypeByCode(mzSendMedicineVo.getSupplyCode());
                    mzSendMedicineVo.setPrintName(mzZdSupplyType.getPrintName());
                }
            }
            resultMap.put("code", 0);
            resultMap.put("message", "查询发药处理的处方详细信息成功");
            resultMap.put("data", cfxxList);
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询发药处理的处方详细信息失败，错误信息{}", e.getMessage());
            resultMap.put("code", -1);
            resultMap.put("message", "查询发药处理的处方详细信息失败");
            return resultMap;
        }
    }

    /**
     * 发药处理
     *
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/sendMedicineProcessing", method = {RequestMethod.POST})
    public Map<String, Object> sendMedicineProcessing(@RequestBody MzChargeDetail mzChargeDetail, HttpServletRequest httpServletRequest) throws MzException {
        User tokenUser = TokenUtil.getUser(httpServletRequest);
        Map<String, Object> resultMap = new HashMap<>();
        try {
            if (mzChargeDetail == null) {
                resultMap.put("code", -1);
                resultMap.put("message", "发药处理失败,参数为空");
                return resultMap;
            }
            if (mzChargeDetail == null) {
                resultMap.put("code", -1);
                resultMap.put("message", "发药处理查询处方记录失败,参数为空");
                return resultMap;
            }
            if (StringUtils.isBlank(mzChargeDetail.getGroupNo())) {
                resultMap.put("code", -1);
                resultMap.put("message", "发药药房编码不能为空");
                return resultMap;
            }
            if (StringUtils.isBlank(mzChargeDetail.getPatientId())) {
                resultMap.put("code", -1);
                resultMap.put("message", "病人编码不能为空");
                return resultMap;
            }
            if (mzChargeDetail.getOrderNo() == null) {
                resultMap.put("code", -1);
                resultMap.put("message", "处方号不能为空");
                return resultMap;
            }
            if (mzChargeDetail.getRealNo() == null) {
                resultMap.put("code", -1);
                resultMap.put("message", "流水号不能为空");
                return resultMap;
            }
            if (mzChargeDetail.getReceiptNo() == null) {
                resultMap.put("code", -1);
                resultMap.put("message", "发票分票号不能为空");
                return resultMap;
            }
            if (mzChargeDetail.getTimes() == null) {
                resultMap.put("code", -1);
                resultMap.put("message", "次数不能为空");
                return resultMap;
            }
            resultMap = mzPharmacyService.sendMedicineProcessing(mzChargeDetail, tokenUser);
            dispensingSocketService.sendToMedicine(mzChargeDetail.getPatientId());
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("发药处理失败，错误信息{}", e.getMessage());
            resultMap.put("code", -1);
            resultMap.put("message", "发药处理失败");
            return resultMap;
        }
    }

    /**
     * 配药处理
     *
     * @param mzChargeDetail
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/dispensingMedicineProcessing", method = {RequestMethod.POST})
    public Map<String, Object> dispensingMedicineProcessing(@RequestBody MzChargeDetail mzChargeDetail) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            if (mzChargeDetail == null) {
                resultMap.put("code", -1);
                resultMap.put("message", "配药处理失败,参数为空");
                return resultMap;
            }
            if (StringUtils.isBlank(mzChargeDetail.getPatientId())) {
                resultMap.put("code", -1);
                resultMap.put("message", "配药处理失败,病人ID为空");
                return resultMap;
            }
            if (mzChargeDetail.getOrderNo() == null) {
                resultMap.put("code", -1);
                resultMap.put("message", "配药处理失败,处方号为空");
                return resultMap;
            }
            if (mzChargeDetail.getTimes() == null) {
                resultMap.put("code", -1);
                resultMap.put("message", "配药处理失败,次数为空");
                return resultMap;
            }
            int num = mzPharmacyService.dispensingMedicineProcessing(mzChargeDetail);
            if (num > 0) {
                resultMap.put("code", 0);
                resultMap.put("message", "配药处理成功");
                dispensingSocketService.sendToMedicineAndSendMedicine(mzChargeDetail.getPatientId());
                return resultMap;
            }
            resultMap.put("code", -1);
            resultMap.put("message", "配药处理失败");
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("配药处理失败，错误信息{}", e.getMessage());
            resultMap.put("code", -1);
            resultMap.put("message", "配药处理失败");
            return resultMap;
        }
    }

    /**
     * 获取处方打印数据
     *
     * @param mzChargeDetail
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/getPrintPrescriptionData", method = {RequestMethod.POST})
    public Map<String, Object> getPrintPrescriptionData(@RequestBody MzChargeDetail mzChargeDetail, HttpServletRequest httpServletRequest) throws MzException {
        Map<String, Object> resultMap = new HashMap<>();
        User tokenUser = TokenUtil.getUser(httpServletRequest);
        try {
            if (mzChargeDetail == null) {
                resultMap.put("code", -1);
                resultMap.put("message", "打印失败,参数为空");
                return resultMap;
            }
            if (StringUtils.isBlank(mzChargeDetail.getPatientId())) {
                resultMap.put("code", -1);
                resultMap.put("message", "打印失败,病人ID为空");
                return resultMap;
            }
            if (mzChargeDetail.getTimes() == null) {
                resultMap.put("code", -1);
                resultMap.put("message", "打印失败,次数为空");
                return resultMap;
            }
            DispensingWindows windows = dispensingWindowsService.queryLastDispensingWindowsByUserIdCode(tokenUser.getUserIdCode(),null);
            if (windows == null) {
                resultMap.put("code", -1);
                resultMap.put("message", "当前操作人未设置发药基础参数，请先设置！");
                return resultMap;
            }
            Map<String, Object> printMap = new HashMap<>();
            MzPatientMi mzPatientMi = mzPatientMiService.queryByPatientId(mzChargeDetail.getPatientId());
            MzVisitTable visit = mzVisitTableService.queryByPatientIdAndTimes(mzChargeDetail.getPatientId(), mzChargeDetail.getTimes());
            printMap.put("patientId", mzChargeDetail.getPatientId());
            printMap.put("ybCardNo", mzPatientMi.getYbCardNo());
            printMap.put("icCardNo", mzPatientMi.getIcCardNo());
            printMap.put("name", mzPatientMi.getName());
            printMap.put("sex", mzPatientMi.getSex());
            printMap.put("age", mzPatientMi.getAge());
            printMap.put("birthDay", mzPatientMi.getBirthDay());
            printMap.put("socialNo", mzPatientMi.getSocialNo());
            printMap.put("phoneNo", mzPatientMi.getPhoneNo());
            printMap.put("address", mzPatientMi.getAddress());
            printMap.put("icdText", visit.getIcdText());//诊断
            mzChargeDetail.setBillItemCode("TC");
            List<MzChargeDetail> mzChargeDetails = mzChargeDetailService.getMzChargeDetailList(mzChargeDetail);
            if (mzChargeDetails.size() > 0) {
                printMap.put("realNo", mzChargeDetails.get(0).getRealNo());//交费流水号
            }
            Employee employee = new Employee();
            BigDecimal totalPrice = new BigDecimal("0");//总价
            List<Map<String, Object>> list = new ArrayList<>();
            for (int i = 0; i < mzChargeDetails.size(); i++) {
                MzChargeDetail chargeDetail =  mzChargeDetails.get(i);
                if(i == 0){
                    String warnDeptName = zdUnitCodeService.queryDeptNameByIdInCache(chargeDetail.getWarnDept());
                    printMap.put("warnDeptName", warnDeptName);//科室
                }
                Map<String, Object> map = new HashMap<>();
                totalPrice = totalPrice.add(chargeDetail.getUnitPrice().multiply(BigDecimal.valueOf(chargeDetail.getQuantity())));
                map.put("quantity", chargeDetail.getQuantity());//数量
                map.put("drugQuan", chargeDetail.getDrugQuan());//一次剂量
                map.put("priceTime", chargeDetail.getPriceTime());//划价日期 开处方日期
                map.put("frequency", chargeDetail.getFrequency());//频率
                map.put("jzFlag", chargeDetail.getJzFlag());//急诊标记
                map.put("instructionText", chargeDetail.getInstructionText());//嘱托说明
                map.put("tryResult", chargeDetail.getTryResult());//皮试结果
                map.put("tryFlag", chargeDetail.getTryFlag());//是否需要皮试
                YpZdDict ypZdDict = ypZdDictService.queryYpZdDictByCodeAndSerial(chargeDetail.getChargeItemCode(), chargeDetail.getSerial());
                map.put("drugName", ypZdDict.getName());//药品名称
                map.put("specification", ypZdDict.getSpecification());//规格
                map.put("drugFlag", ypZdDict.getDrugFlag());//毒麻标志
                map.put("psFlag", ypZdDict.getPsFlag());//是否需要皮试
                String manufactoryName = ypZdManufactoryService.queryYpZdManufactoryByCode(ypZdDict.getManuCode());
                map.put("manufactoryName", manufactoryName);//生产厂家
                String packUnitName = mzPharmacyService.getYpUnitName(ypZdDict.getPackUnit());
                if (chargeDetail.getGroupNo().equals("81")) {
                    map.put("ypUnitName", packUnitName);//单位
                    map.put("drugUnitName", packUnitName);//一次剂量单位
                } else if (chargeDetail.getGroupNo().equals("71")) {
                    String drugUnitName = mzPharmacyService.getYpUnitName(chargeDetail.getDrugUnit());
                    map.put("ypUnitName", packUnitName);//单位
                    map.put("drugUnitName", drugUnitName);//一次剂量单位
                }
                if(chargeDetail.getSupplyCode() != null){
                    MzZdSupplyType mzZdSupplyType = mzZdSupplyTypeService.selectMzZdSupplyTypeByCode(chargeDetail.getSupplyCode());
                    map.put("printName", mzZdSupplyType.getPrintName());//给药方式
                }
                employee = employeeService.queryByUserCode(chargeDetail.getDoctorCode());
                list.add(map);
            }
            if (employee.getEmployeeName() != null) {
                printMap.put("employeeName", employee.getEmployeeName());//医师
                printMap.put("employeeCode", employee.getEmployeeCode());//医师编码
            }
            printMap.put("totalPrice", totalPrice);
            printMap.put("list", list);
            resultMap.put("code", 0);
            resultMap.put("message", "打印成功");
            resultMap.put("data", printMap);
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("打印失败，错误信息{}", e.getMessage());
            resultMap.put("code", -1);
            resultMap.put("message", "打印失败");
            return resultMap;
        }
    }

    /**
     * 获取注射单药品标签打印数据
     *
     * @param mzChargeDetail
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/getPrintInjectionData", method = {RequestMethod.POST})
    public Map<String, Object> getPrintInjectionData(@RequestBody MzChargeDetail mzChargeDetail, HttpServletRequest httpServletRequest) throws MzException {
        Map<String, Object> resultMap = new HashMap<>();
        User tokenUser = TokenUtil.getUser(httpServletRequest);
        try {
            if (mzChargeDetail == null) {
                resultMap.put("code", -1);
                resultMap.put("message", "打印失败,参数为空");
                return resultMap;
            }
            if (StringUtils.isBlank(mzChargeDetail.getGroupNo())) {
                resultMap.put("code", -1);
                resultMap.put("message", "发药药房编码不能为空");
                return resultMap;
            }
            if (StringUtils.isBlank(mzChargeDetail.getPatientId())) {
                resultMap.put("code", -1);
                resultMap.put("message", "病人编码不能为空");
                return resultMap;
            }
            if (mzChargeDetail.getOrderNo() == null) {
                resultMap.put("code", -1);
                resultMap.put("message", "处方号不能为空");
                return resultMap;
            }
            if (mzChargeDetail.getRealNo() == null) {
                resultMap.put("code", -1);
                resultMap.put("message", "发票流水号不能为空");
                return resultMap;
            }
            if (mzChargeDetail.getReceiptNo() == null) {
                resultMap.put("code", -1);
                resultMap.put("message", "发票分票号不能为空");
                return resultMap;
            }
            if (mzChargeDetail.getTimes() == null) {
                resultMap.put("code", -1);
                resultMap.put("message", "次数不能为空");
                return resultMap;
            }
            DispensingWindows windows = dispensingWindowsService.queryLastDispensingWindowsByUserIdCode(tokenUser.getUserIdCode(),null);
            if (windows == null) {
                resultMap.put("code", -1);
                resultMap.put("message", "当前操作人未设置发药基础参数，请先设置！");
                return resultMap;
            }
            List<MzSendMedicineVo> cfxxList = mzPharmacyService.getFyclPrescriptionDetail(mzChargeDetail);
            if (cfxxList.size() > 0) {
                MzVisitTable visit = mzVisitTableService.queryByPatientIdAndTimes(mzChargeDetail.getPatientId(), mzChargeDetail.getTimes());
                cfxxList.get(0).setIcdText(visit.getIcdText());
                String warnDeptName = zdUnitCodeService.queryDeptNameByIdInCache(cfxxList.get(0).getWarnDept());
                cfxxList.get(0).setWarnDeptName(warnDeptName);
                Employee employee = employeeService.queryByUserCode(cfxxList.get(0).getDoctorCode());
                cfxxList.get(0).setEmployeeName(employee.getEmployeeName());
            }
            MzPatientMi mzPatientMi = mzPatientMiService.queryByPatientId(mzChargeDetail.getPatientId());
            for (MzSendMedicineVo mzSendMedicineVo : cfxxList) {
                mzSendMedicineVo.setName(mzPatientMi.getName());
                mzSendMedicineVo.setSex(mzPatientMi.getSex());
                mzSendMedicineVo.setAge(mzPatientMi.getAge());
                mzSendMedicineVo.setBirthDay(mzPatientMi.getBirthDay());
                String drugUnitName = mzPharmacyService.getYpUnitName(mzSendMedicineVo.getDrugUnit());
                String ypUnitName = mzPharmacyService.getYpUnitName(mzSendMedicineVo.getYpUnit());
                String miniUnitName = mzPharmacyService.getYpUnitName(mzSendMedicineVo.getMiniUnit());
                mzSendMedicineVo.setDrugUnitName(drugUnitName);
                mzSendMedicineVo.setYpUnitName(ypUnitName);
                mzSendMedicineVo.setMiniUnitName(miniUnitName);
                YpZdDict ypZdDict = ypZdDictService.queryYpZdDictByCodeAndSerial(mzSendMedicineVo.getChargeItemCode(), mzSendMedicineVo.getSerial());
                mzSendMedicineVo.setWeight(ypZdDict.getWeight());
                mzSendMedicineVo.setVolum(ypZdDict.getVolum());
                MzZdSupplyType mzZdSupplyType = mzZdSupplyTypeService.selectMzZdSupplyTypeByCode(mzSendMedicineVo.getSupplyCode());
                mzSendMedicineVo.setPrintName(mzZdSupplyType.getPrintName());
                mzSendMedicineVo.setClassCode(mzZdSupplyType.getClassCode());
                MzOrderFrequency mzOrderFrequencyByCode = mzOrderFrequencyService.getMzOrderFrequencyByCode(mzSendMedicineVo.getFrequency());
                mzSendMedicineVo.setComm(mzOrderFrequencyByCode.getComm());
            }
            resultMap.put("code", 0);
            resultMap.put("message", "打印成功");
            resultMap.put("data", cfxxList);
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("打印失败，错误信息{}", e.getMessage());
            resultMap.put("code", -1);
            resultMap.put("message", "打印失败");
            return resultMap;
        }
    }

    /**
     * 叫号
     *
     * @param patientId
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/callNumber", method = {RequestMethod.GET})
    public Map<String, Object> callNumber(@RequestParam("patientId") String patientId) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            if (patientId == null) {
                resultMap.put("code", -1);
                resultMap.put("message", "叫号失败,病人ID参数为空");
                return resultMap;
            }
            dispensingSocketService.callNumberSendToMedicine(patientId);
            resultMap.put("code", 0);
            resultMap.put("message", "叫号成功");
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("叫号失败，错误信息{}", e.getMessage());
            resultMap.put("code", -1);
            resultMap.put("message", "叫号失败");
            return resultMap;
        }
    }

    @UserLoginToken
    @RequestMapping(value = "/getRadSendRecord", method = {RequestMethod.POST})
    public Map<String, Object> getRadSendRecord(@RequestBody RadSendRecord radSendRecord) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            if (radSendRecord == null) {
                resultMap.put("code", -1);
                resultMap.put("message", "放射科发药记录查询失败,参数为空");
                return resultMap;
            }
            List<RadSendRecord> radSendRecordPage = mzPharmacyService.getRadSendRecordPage(radSendRecord);
            Stream.iterate(0,i -> i+1).limit(radSendRecordPage.size()).forEach(i -> {
                RadSendRecord rsr = radSendRecordPage.get(i);
                Date date = rsr.getSendDate();
                if(radSendRecordPage.size() == i+1){//分页查询的最后一条数据,需取当前时间的上一次发药时间
                    Date lastRadSendDate = mzPharmacyService.getLastRadSendDate(date);
                    rsr.setStartDate(lastRadSendDate);
                }else{
                    rsr.setStartDate(radSendRecordPage.get(i+1).getSendDate());
                }
                rsr.setEndDate(DateUtil.getPrevDayFirstSecond(date));
                Employee employee = employeeService.queryByUserCode(rsr.getConfirmId());
                rsr.setName(employee.getEmployeeName());
                rsr.setPageIndex(radSendRecord.getPageIndex());
                rsr.setPageSize(radSendRecord.getPageSize());
            });
            List<RadSendRecord> reRadSendRecord = new ArrayList<>();
            if(radSendRecord.getPageIndex() == 0){
                //添加一条上次发药后到当天未发药记录
                RadSendRecord wfy = new RadSendRecord();
                wfy.setStartDate(radSendRecordPage.get(0).getSendDate());
                if(DateUtils.isSameDay(radSendRecordPage.get(0).getSendDate(),new Date())){//当天刚发完药，将截止时间设为当天
                    wfy.setEndDate(radSendRecordPage.get(0).getSendDate());
                }else{
                    wfy.setEndDate(DateUtil.getPrevDayFirstSecond(new Date()));
                }
                reRadSendRecord.add(wfy);
            }
            reRadSendRecord.addAll(radSendRecordPage);
            Integer count = mzPharmacyService.getRadSendRecordCount(radSendRecord);
            resultMap.put("code", 0);
            resultMap.put("message", "查询放射科发药记录成功");
            resultMap.put("data", reRadSendRecord);
            resultMap.put("total", count);
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询放射科发药记录失败，错误信息{}", e.getMessage());
            resultMap.put("code", -1);
            resultMap.put("message", "查询放射科发药记录失败");
            return resultMap;
        }
    }

    /**
     * 获取放射科发药统计
     * @param confirmTime
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/getRadSendStat",method = RequestMethod.GET)
    public Map<String,Object> getRadSendStat(@RequestParam("confirmTime") String confirmTime){
        Map<String, Object> resultMap = new HashMap<>();
        try {
            if (confirmTime == null) {
                resultMap.put("code", -1);
                resultMap.put("message", "放射科发药统计查询失败,发药时间为空");
                return resultMap;
            }
            List<Map<String, Object>> list = mzPharmacyService.getRadSendStat(confirmTime);
            resultMap.put("code", 0);
            resultMap.put("message", "查询放射科发药统计成功");
            resultMap.put("data", list);
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询放射科发药统计失败，错误信息{}", e.getMessage());
            resultMap.put("code", -1);
            resultMap.put("message", "查询放射科发药统计失败");
            return resultMap;
        }
    }

    /**
     * 放射科发药处理
     *
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/sendMedicineProcessingRad", method = {RequestMethod.GET})
    public Map<String, Object> sendMedicineProcessingRad(HttpServletRequest httpServletRequest) throws MzException {
        User tokenUser = TokenUtil.getUser(httpServletRequest);
        Map<String, Object> resultMap = new HashMap<>();
        try {
            int number = mzPharmacyService.sendMedicineProcessingRad(tokenUser);
            if(number > 0){
                resultMap.put("code", 0);
                resultMap.put("message", "放射科发药处理成功");
                return resultMap;
            }else{
                resultMap.put("code", -1);
                resultMap.put("message", "可发药处方为空，放射科发药处理失败");
                return resultMap;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("放射科发药处理失败，错误信息{}", e.getMessage());
            resultMap.put("code", -1);
            resultMap.put("message", "放射科发药处理失败");
            return resultMap;
        }
    }

    /**
     * 获取放射科发药统计打印数据
     * @param confirmTime
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/getPrintRadSendStat",method = RequestMethod.GET)
    public Map<String,Object> getPrintRadSendStat(@RequestParam("confirmTime") String confirmTime){
        Map<String, Object> resultMap = new HashMap<>();
        try {
            if (confirmTime == null) {
                resultMap.put("code", -1);
                resultMap.put("message", "放射科发药统计打印数据查询失败,发药时间为空");
                return resultMap;
            }
            List<Map<String, Object>> list = mzPharmacyService.getRadSendStat(confirmTime);
            resultMap.put("code", 0);
            resultMap.put("message", "放射科发药统计数据打印成功");
            resultMap.put("data", list);
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询放射科发药统计打印数据失败，错误信息{}", e.getMessage());
            resultMap.put("code", -1);
            resultMap.put("message", "放射科发药统计数据打印失败");
            return resultMap;
        }
    }
}
