package mobile_api_controllers

import (
	"XT_New/enums"
	"XT_New/models"
	"XT_New/service"
	"XT_New/utils"
	"strconv"
	"time"
)

type DoctorAdviceAPIController struct {
	MobileBaseAPIAuthController
}

// /m/api/schedule/advices [get]
// @param date:string (yyyy-mm-dd)
// @param advice_type:int 1长期医嘱 3临时医嘱 其他:全部
func (this *DoctorAdviceAPIController) ScheduleAdvices() {

	schedualDate := this.GetString("date")
	adviceType, _ := this.GetInt("advice_type")
	patientType, _ := this.GetInt("patient_type")
	delivery_way := this.GetString("delivery_way")
	if adviceType != 1 && adviceType != 3 && adviceType != 2 {
		adviceType = 0
	}

	if patientType != 1 && patientType != 2 {

		patientType = 0
	}

	date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", schedualDate)
	if parseDateErr != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	adminInfo := this.GetMobileAdminUserInfo()
	orgID := adminInfo.Org.Id
	redis := service.RedisClient()
	key := strconv.FormatInt(orgID, 10) + ":" + ":patient_list_all"
	redis.Set(key, "", time.Second)
	scheduals, err := service.MobileGetScheduleDoctorAdvicesTwo(orgID, date.Unix(), adviceType, patientType, adminInfo.AdminUser.Id, delivery_way)
	//获取所有的患者
	blood_patients, _ := service.GetAllPatientListByListSeven(orgID)
	//获取透析处方
	blood_prescriptions, _ := service.GetAllPrescriptionByListOne(orgID, date.Unix())
	//获取上机
	blood_dialysisOrders, _ := service.GetAllDialysisOrdersByListTwo(orgID, date.Unix())

	for key, schedule := range scheduals {
		for _, patient := range blood_patients {
			if schedule.PatientId == patient.ID {
				scheduals[key].SchedualPatient = patient
				break
			}
		}

		for _, prescription := range blood_prescriptions {
			if schedule.PatientId == prescription.PatientId {
				scheduals[key].Prescription = prescription
				break
			}
		}

		//获取上机
		for _, dialysisorder := range blood_dialysisOrders {
			if schedule.PatientId == dialysisorder.PatientId {
				scheduals[key].DialysisOrder = dialysisorder
				break
			}
		}

	}

	config, _ := service.GetHisDoctorConfig(orgID)
	project_config, _ := service.GetHisProjectConfig(orgID)

	if project_config.IsOpen == 1 || project_config.IsOpen == 2 {
		//获取his医嘱数据
		project, _ := service.GetMobileHisPrescriptionProject(orgID, date.Unix(), delivery_way, patientType, adminInfo.AdminUser.Id)
		//team_project, _ := service.GetMobileHisPrescriptionTeamProject(orgID, date.Unix(), delivery_way, patientType, adminInfo.AdminUser.Id)
		for _, item := range project {
			index := 0
			for _, subItem := range item.HisPrescriptionTeamProject {

				if subItem.HisProject.CostClassify != 3 {
					subItem.IsCheckTeam = 2
					item.HisPrescriptionProject = append(item.HisPrescriptionProject, subItem)
				}

				if subItem.HisProject.CostClassify == 3 {
					subItem.IsCheckTeam = 1
					index = index + 1
					if index == 1 {
						item.HisPrescriptionProject = append(item.HisPrescriptionProject, subItem)
					}
				}
			}
		}

		//获取所有的患者
		patients, _ := service.GetAllPatientListByListTwo(orgID)

		//获取所有床位
		numberList, _ := service.GetAllDeviceNumberByListOne(orgID)

		//获取透析处方
		prescriptions, _ := service.GetAllPrescriptionByListOne(orgID, date.Unix())

		//获取上机
		dialysisOrders, _ := service.GetAllDialysisOrdersByListTwo(orgID, date.Unix())

		for key, item := range project {
			for _, patient := range patients {
				if item.PatientId == patient.ID {
					project[key].SchedualPatient = patient
					break
				}
			}
			// 获取床位信息
			for _, it := range numberList {
				if item.BedId == it.ID {
					project[key].DeviceNumber = it
					break
				}
			}

			// 获取处方
			for _, it := range prescriptions {
				if item.PatientId == it.PatientId {
					project[key].Prescription = it
					break
				}
			}

			//获取上机
			for _, it := range dialysisOrders {
				if item.PatientId == it.PatientId {
					project[key].DialysisOrder = it
					break
				}
			}
		}

		hisAdvices, _ := service.GetHisDoctorAdvicesTwo(orgID, date.Unix(), delivery_way, patientType, adminInfo.AdminUser.Id)
		adminUser, _ := service.GetAllAdminUsers(orgID, adminInfo.App.Id)
		if err != nil {
			this.ErrorLog("获取排班信息失败:%v", err)
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		} else {
			filtedScheduals := []*service.MScheduleDoctorAdviceVMOne{}
			for _, schedual := range scheduals {
				if len(schedual.DoctorAdvices) > 0 {
					filtedScheduals = append(filtedScheduals, schedual)
				}
			}
			this.ServeSuccessJSON(map[string]interface{}{
				"scheduals":      filtedScheduals,
				"adminUser":      adminUser,
				"config":         config,
				"project":        project,
				"project_config": project_config,
				"hisAdvices":     hisAdvices,
			})
		}
	} else {
		adminUser, _ := service.GetAllAdminUsers(orgID, adminInfo.App.Id)
		if err != nil {
			this.ErrorLog("获取排班信息失败:%v", err)
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		} else {
			filtedScheduals := []*service.MScheduleDoctorAdviceVMOne{}
			for _, schedual := range scheduals {
				if len(schedual.DoctorAdvices) > 0 {
					filtedScheduals = append(filtedScheduals, schedual)
				}
			}
			this.ServeSuccessJSON(map[string]interface{}{
				"scheduals":      filtedScheduals,
				"adminUser":      adminUser,
				"config":         config,
				"project_config": project_config,
			})
		}
	}
}

func (c *DoctorAdviceAPIController) GetAdviceConfigs() {
	advice_type, _ := c.GetInt64("type", 0)
	adminUserInfo := c.GetMobileAdminUserInfo()
	var drugs []models.DrugDic
	drugways, _, _ := service.GetDrugWayDics(adminUserInfo.Org.Id)
	efs, _, _ := service.GetExecutionFrequencyDics(adminUserInfo.Org.Id)
	adviceTemplates, _ := service.FindAllAdviceTemplate(adminUserInfo.Org.Id, advice_type)
	c.ServeSuccessJSON(map[string]interface{}{
		"drugs":            drugs,
		"drugways":         drugways,
		"efs":              efs,
		"advice_templates": adviceTemplates,
	})
}
