public async Task <IActionResult> GetPrescription(string appointmentGuid, string actionType = null)
        {
            if (string.IsNullOrEmpty(appointmentGuid))
            {
                return(Failed(ErrorCode.Empty, "参数不正确,请检查"));
            }

            var prescriptionBiz = new PrescriptionBiz();

            var result = await prescriptionBiz.GetPrescription(appointmentGuid, actionType);

            return(Success(result));
        }
        public async Task <IActionResult> CreatePrescription([FromBody] ProcessPrescriptionRequestDto request)
        {
            Logger.Info($"{nameof(CreatePrescription)}: {JsonConvert.SerializeObject(request)}");

            var context = new PrescriptionContext(request);

            var appointmentBiz = new DoctorAppointmentBiz();
            var appointment    = await appointmentBiz.GetAsync(request.AppointmentGuid);

            if (appointment is null)
            {
                return(Failed(ErrorCode.Empty, "预约不存在,请检查"));
            }

            var informationBiz          = new PrescriptionInformationBiz();
            var prescriptionInformation = await informationBiz.ExistInformation(appointment.AppointmentGuid);

            if (prescriptionInformation != null)
            {
                return(Failed(ErrorCode.Empty, "该处方已提交,请勿重复提交"));
            }
            context.AppointmentModel = appointment;

            var validateResult = Validate(context);

            if (validateResult.Code != ErrorCode.Success)
            {
                return(validateResult);
            }
            context.AppointmentModel.Status = AppointmentStatusEnum.Treated.ToString();

            var prescriptionBiz = new PrescriptionBiz();
            var result          = await prescriptionBiz.CreatePrescription(context);

            if (!result)
            {
                return(Failed(ErrorCode.DataBaseError, "创建处方记录失败,请稍后重试"));
            }

            var response = new SubmitPrescriptionSuccessResponseDto
            {
                InformationGuid     = context.InformationModel.InformationGuid,
                PrescriptionSuccess = context.PrescriptionModels.Select(d => new SubmitPrescriptionSuccessItemDto()
                {
                    PrescriptionGuid = d.PrescriptionGuid,
                    PrescriptionName = d.PrescriptionName
                })
            };

            return(Success(response));
        }
        public async Task <IActionResult> ConfirmAppointmentReceivables(string appointmentGuid)
        {
            if (string.IsNullOrEmpty(appointmentGuid))
            {
                return(Failed(ErrorCode.UserData, "用户预约参数未提供"));
            }

            var appointmentBiz = new DoctorAppointmentBiz();

            var appointment = await appointmentBiz.GetAsync(appointmentGuid);

            if (appointment is null)
            {
                return(Failed(ErrorCode.UserData, "预约不存在,请检查参数是否正确"));
            }

            var prescriptionBiz = new PrescriptionBiz();

            var result = await prescriptionBiz.UpdateReceptionStatus(appointmentGuid);

            return(result ? Success() : Failed(ErrorCode.DataBaseError, "更新收款状态失败"));
        }
        /// <summary>
        /// 验证参数
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        ResponseDto Validate(PrescriptionContext context)
        {
            var request         = context.Request;
            var prescriptionBiz = new PrescriptionBiz();

            if (request.PatientAge <= 0)
            {
                return(Failed(ErrorCode.Empty, "年龄必须大于0"));
            }

            if (request.PatientAge > 120)
            {
                return(Failed(ErrorCode.Empty, "年龄超过最大120岁限制"));
            }

            if (!string.IsNullOrEmpty(request.PatientSymptoms) &&
                request.PatientSymptoms.Length > 1000)
            {
                return(Failed(ErrorCode.Empty, "患者症状超过最大长度限制"));
            }

            context.InformationModel.AppointmentGuid   = request.AppointmentGuid;
            context.InformationModel.PatientName       = request.PatientName;
            context.InformationModel.PatientGender     = request.PatientGender.ToString();
            context.InformationModel.PatientAge        = request.PatientAge;
            context.InformationModel.PatientPhone      = request.PatientPhone;
            context.InformationModel.HasAllergy        = request.HasAllergy;
            context.InformationModel.HasChronicDisease = request.HasChronicDisease;
            context.InformationModel.PatientProvince   = request.PatientProvince;
            context.InformationModel.PatientCity       = request.PatientCity;
            context.InformationModel.PatientDistrict   = request.PatientDistrict;
            context.InformationModel.PatientAddress    = request.PatientAddress;
            context.InformationModel.ReceptionType     = request.ReceptionType.ToString();
            context.InformationModel.ClinicalDiagnosis = request.ClinicalDiagnosis;
            context.InformationModel.PatientSymptoms   = request.PatientSymptoms;
            context.InformationModel.DoctorGuid        = context.AppointmentModel.DoctorGuid;
            context.InformationModel.HospitalGuid      = context.AppointmentModel.HospitalGuid;
            context.InformationModel.OfficeGuid        = context.AppointmentModel.OfficeGuid;

            var prescriptions = request.BasePrescriptions;

            if (string.IsNullOrEmpty(context.InformationModel.InformationGuid))
            {
                if (prescriptions.Count <= 0)
                {
                    return(Failed(ErrorCode.Empty, "处方数据为空,请检查"));
                }

                context.InformationModel.InformationGuid = Guid.NewGuid().ToString("N");
                context.InformationModel.PaidStatus      = PrescriptionInformationPaidStatus
                                                           .NotPaid.ToString();
                context.InformationModel.AppointmentTime = DateTime.Now;
                context.InformationModel.CreatedBy       = UserID;
                context.InformationModel.LastUpdatedBy   = UserID;
            }
            else
            {
                context.InformationModel.LastUpdatedDate = DateTime.Now;

                if (prescriptions.Count <= 0)
                {
                    return(Success());
                }
            }

            if (prescriptions.Any(d => d.Receptions.Count <= 0))
            {
                return(Failed(ErrorCode.Empty, "存在药品数据为空的处方,请检查"));
            }

            var duplicatePreNameExists = prescriptions.GroupBy(d => d.PrescriptionName?.Trim())
                                         .Any(g => g.Count() > 1);

            if (duplicatePreNameExists)
            {
                return(Failed(ErrorCode.Empty, "处方名称有重复,请检查"));
            }

            #region 随机生成七位纯数字处方编号

            var uniquePrescriptions = (ConcurrentBag <string>)null;

            lock (locker)
            {
                uniquePrescriptions = prescriptionBiz.GetUniquePrescriptionNos(prescriptions.Count);
            }
            #endregion

            foreach (var prescription in prescriptions)
            {
                var prescriptionModel = new PrescriptionModel();

                lock (locker)
                {
                    var precriptionTotalFee = prescription.Receptions
                                              .Sum(d => d.ItemPrice * d.ItemQuantity);

                    context.InformationModel.TotalCost += precriptionTotalFee;

                    prescriptionModel.TotalCost = precriptionTotalFee;
                }

                var name = prescription.PrescriptionName;
                if (string.IsNullOrEmpty(name?.Trim()))
                {
                    return(Failed(ErrorCode.Empty, "存在名称为空的处方,请检查"));
                }

                if (name.Length > 50)
                {
                    return(Failed(ErrorCode.Empty, $"处方【{name}】名称超过最大长度限制,请检查"));
                }

                if (context.dbPrescriptionModels.Count > 0)
                {
                    if (context.dbPrescriptionModels.Any(d => d.PrescriptionName.Equals(name)))
                    {
                        return(Failed(ErrorCode.Empty, "已提交,请勿重复提交"));
                    }
                }

                var pewscriptionGuid = Guid.NewGuid().ToString("N");

                if (!uniquePrescriptions.TryTake(out var no))
                {
                    return(Failed(ErrorCode.Empty, "服务器操作繁忙,请稍后重试"));
                }

                prescriptionModel.PrescriptionGuid = pewscriptionGuid;
                prescriptionModel.InformationGuid  = context.InformationModel.InformationGuid;
                prescriptionModel.PrescriptionName = name;
                prescriptionModel.PrescriptionNo   = no;
                prescriptionModel.Status           = PrescriptionStatusEnum.Obligation.ToString();
                prescriptionModel.CreatedBy        = UserID;
                prescriptionModel.LastUpdatedBy    = UserID;

                context.PrescriptionModels.Add(prescriptionModel);

                foreach (var reception in prescription.Receptions)
                {
                    if (string.IsNullOrEmpty(reception.ItemName?.Trim()))
                    {
                        return(Failed(ErrorCode.Empty, $"处方【{name}】下存在名称为空的药品,请检查"));
                    }

                    if (reception.ItemName.Length > 50)
                    {
                        return(Failed(ErrorCode.Empty, $"药品【{reception.ItemName}】名称超过最大长度限制,请检查"));
                    }

                    if (!string.IsNullOrEmpty(reception.ItemSpecification?.Trim()))
                    {
                        if (reception.ItemSpecification.Length > 50)
                        {
                            return(Failed(ErrorCode.Empty, $"药品【{reception.ItemName}】名称超过最大长度限制,请检查"));
                        }
                    }

                    if (reception.ItemPrice < 0)
                    {
                        return(Failed(ErrorCode.Empty, $"处方【{name}】下存在单价小于0的药品,请检查"));
                    }

                    if (reception.ItemQuantity < 1)
                    {
                        return(Failed(ErrorCode.Empty, $"处方【{name}】下存在数量小于1的药品,请检查"));
                    }

                    if (reception.ItemType == ReceptionRecipeTypeEnum.Drug)
                    {
                        if (!reception.DrugFrequencyQuantity.HasValue)
                        {
                            return(Failed(ErrorCode.Empty, $"处方【{name}】下存在用药频度数量需提供,请检查"));
                        }

                        if (reception.DrugFrequencyQuantity.Value <= 0)
                        {
                            return(Failed(ErrorCode.Empty, $"处方【{name}】下存在用药频度数量小于0的药品,请检查"));
                        }

                        if (!reception.DrugFrequencyQuantity.HasValue)
                        {
                            return(Failed(ErrorCode.Empty, $"处方【{name}】下存在用药频度数量需提供,请检查"));
                        }

                        if (reception.DrugFrequencyTimes.Value <= 0)
                        {
                            return(Failed(ErrorCode.Empty, $"处方【{name}】下存在用药频度小于0的药品,请检查"));
                        }

                        if (string.IsNullOrEmpty(reception.DrugFrequencyUnit?.Trim()))
                        {
                            return(Failed(ErrorCode.Empty, $"处方【{name}】下存在用药频度单位为空的药品,请检查"));
                        }

                        if (reception.DrugFrequencyUnit.Length > 50)
                        {
                            return(Failed(ErrorCode.Empty, $"处方【{name}】下存在用药频度单位超过最大长度限制,请检查"));
                        }
                    }

                    context.RecipeModels.Add(new PrescriptionRecipeModel()
                    {
                        RecipeGuid            = Guid.NewGuid().ToString("N"),
                        PrescriptionGuid      = pewscriptionGuid,
                        ItemType              = reception.ItemType.ToString(),
                        ItemName              = reception.ItemName,
                        ItemSpecification     = reception.ItemSpecification,
                        ItemPrice             = reception.ItemPrice,
                        ItemQuantity          = reception.ItemQuantity,
                        DrugDosage            = reception.DrugDosage,
                        DrugFrequencyQuantity = reception.DrugFrequencyQuantity,
                        DrugFrequencyTimes    = reception.DrugFrequencyTimes,
                        DrugFrequencyUnit     = reception.DrugFrequencyUnit,
                        DrugUsage             = reception.DrugUsage,
                        LastUpdatedBy         = UserID,
                        CreatedBy             = UserID
                    });
                }
            }
            return(Success());
        }
        public async Task <IActionResult> CancellPrescription([FromBody] CancellPrescriptionRequestDto request)
        {
            var prescriptionBiz = new PrescriptionBiz();

            var prescription = await prescriptionBiz.GetAsync(request.PrescriptionGuid);

            if (prescription is null)
            {
                return(Failed(ErrorCode.Empty, "处方记录不存在,请检查"));
            }

            var name = prescription.PrescriptionName;

            if (prescription.Status == PrescriptionStatusEnum.Paied.ToString())
            {
                return(Failed(ErrorCode.Empty, $"处方【{name}】已完成付款不可作废"));
            }

            if (prescription.Status == PrescriptionStatusEnum.Cancellation.ToString())
            {
                return(Failed(ErrorCode.Empty, $"处方【{name}】已作废,请勿重复提交"));
            }

            prescription.Status          = PrescriptionStatusEnum.Cancellation.ToString();
            prescription.LastUpdatedBy   = UserID;
            prescription.LastUpdatedDate = DateTime.Now;
            prescription.Reason          = request.Reason;

            var informationBiz = new PrescriptionInformationBiz();
            var information    = await informationBiz.GetAsync(prescription.InformationGuid);

            if (information is null)
            {
                return(Failed(ErrorCode.Empty, "处方记录不存在"));
            }

            lock (locker)
            {
                information.TotalCost -= prescription.TotalCost;
            }

            var context = new PrescriptionContext(null)
            {
                InformationModel = information
            };

            var prescriptionModels = await prescriptionBiz.GetAllPrescriptionsAsync(information.InformationGuid, prescription.PrescriptionGuid);

            context.dbPrescriptionModels = prescriptionModels;

            UpdatePrescriptionInformationPaidStatus(context);

            var result = await prescriptionBiz.CancellPrescription(context.InformationModel, prescription);

            if (!result)
            {
                return(Failed(ErrorCode.DataBaseError, $"作废处方【{prescription.PrescriptionName}】失败"));
            }

            return(Success());
        }
        public async Task <IActionResult> UpdatePrescription([FromBody]
                                                             ProcessPrescriptionRequestDto request)
        {
            if (string.IsNullOrEmpty(request.InformationGuid))
            {
                return(Failed(ErrorCode.Empty, "预约不存在,请检查"));
            }

            Logger.Info($"{nameof(UpdatePrescription)}: {JsonConvert.SerializeObject(request)}");

            var context = new PrescriptionContext(request);

            var appointmentBiz = new DoctorAppointmentBiz();
            var appointment    = await appointmentBiz.GetAsync(request.AppointmentGuid);

            if (appointment is null)
            {
                return(Failed(ErrorCode.Empty, "预约不存在,请检查"));
            }
            context.AppointmentModel = appointment;

            var informationBiz = new PrescriptionInformationBiz();
            var information    = await informationBiz.GetAsync(request.InformationGuid);

            if (information is null)
            {
                return(Failed(ErrorCode.Empty, "用户信息不存在,请检查"));
            }

            if (!information.AppointmentGuid.Equals(request.AppointmentGuid))
            {
                return(Failed(ErrorCode.Empty, "预约记录和用户信息不一致,无法操作"));
            }

            context.InformationModel = information;

            var prescriptionBiz = new PrescriptionBiz();

            var prescriptionModels = await prescriptionBiz.GetAllPrescriptionsAsync(information.InformationGuid);

            prescriptionModels = prescriptionModels.Where(d =>
                                                          d.Status != PrescriptionStatusEnum.Cancellation.ToString()).ToList();

            context.dbPrescriptionModels = prescriptionModels;

            var validateResult = Validate(context);

            if (validateResult.Code != ErrorCode.Success)
            {
                return(validateResult);
            }

            context.dbPrescriptionModels = prescriptionModels
                                           .Concat(context.PrescriptionModels).ToList();

            UpdatePrescriptionInformationPaidStatus(context);

            var result = await prescriptionBiz.UpdatePrescription(context);

            if (!result)
            {
                return(Failed(ErrorCode.DataBaseError, "更新处方记录失败"));
            }

            var prescriptions = prescriptionModels.Where(d => d.Status != PrescriptionStatusEnum.Cancellation.ToString())
                                .OrderBy(d => d.CreationDate)
                                .Concat(context.PrescriptionModels)
                                .Select(d => new SubmitPrescriptionSuccessItemDto()
            {
                PrescriptionGuid = d.PrescriptionGuid,
                PrescriptionName = d.PrescriptionName
            });

            var response = new SubmitPrescriptionSuccessResponseDto()
            {
                InformationGuid     = information.InformationGuid,
                PrescriptionSuccess = prescriptions
            };

            return(Success(response));
        }