package new_mobile_api_controllers

import (
	"Xcx_New/enums"
	"Xcx_New/models"
	"Xcx_New/service"
	"Xcx_New/utils"
	"encoding/json"
	"fmt"
	"math/rand"
	"reflect"
	"strconv"
	"time"
)

type MobileHisApiController struct {
	NewMobileBaseAPIAuthController
}

func (c *MobileHisApiController) GetHisPrescriptionConfig() {
	adminInfo := c.GetMobileAdminUserInfo()

	//获取医嘱模版
	advices, _ := service.FindAllHisAdviceTemplate(adminInfo.Org.Id)
	//获取所有基础药
	drugs, _ := service.GetAllDrugLibList(adminInfo.Org.Id)
	drugways, _, _ := service.GetDrugWayDics(adminInfo.Org.Id)
	efs, _, _ := service.GetExecutionFrequencyDics(adminInfo.Org.Id)
	doctors, _ := service.GetHisAdminUserDoctors(adminInfo.Org.Id)
	team, _ := service.GetAllProjectTeamList(adminInfo.Org.Id)
	projects, _ := service.GetHisProject(adminInfo.Org.Id)
	good_info, _ := service.GetGoodInfoMation(adminInfo.Org.Id)
	//获取所有科室信息
	department, _ := service.GetAllDepartMent(adminInfo.Org.Id)
	c.ServeSuccessJSON(map[string]interface{}{
		"drugs":            drugs,
		"advices_template": advices,
		"drugways":         drugways,
		"efs":              efs,
		"doctors":          doctors,
		"department":       department,
		"projects":         projects,
		"team":             team,
		"good_info":        good_info,
	})
}
func (c *MobileHisApiController) GetHisPatientInfo() {
	patient_id, _ := c.GetInt64("patient_id")
	record_date := c.GetString("record_date")
	number := c.GetString("number")
	start_time := c.GetString("start_time")
	end_time := c.GetString("end_time")
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", record_date+" 00:00:00", loc)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	recordDateTime := theTime.Unix()

	startTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
	if err != nil {

	}
	startRecordDateTime := startTime.Unix()

	endTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
	if err != nil {

	}
	endRecordDateTime := endTime.Unix()

	var last_prescriptions []*models.HisPrescription
	var sch_prescriptions []*models.HisPrescriptionInfoTemplate

	admin := c.GetMobileAdminUserInfo()
	his_patient_info, _ := service.GetHisPatientInfo(admin.Org.Id, patient_id, recordDateTime)
	xt_patient_info, _ := service.GetXTPatientInfo(admin.Org.Id, patient_id)
	prescriptions, _ := service.GetHisPrescription(admin.Org.Id, patient_id, recordDateTime, 2)
	monthPrescriptions, _ := service.GetMonthHisPrescriptionTwo(admin.Org.Id, patient_id, startRecordDateTime, endRecordDateTime, 2)
	case_history, _ := service.GetHisPatientCaseHistoryInfo(admin.Org.Id, patient_id, recordDateTime)
	patientPrescriptionInfo, _ := service.FindPatientPrescriptionInfo(admin.Org.Id, patient_id, recordDateTime, 2)
	order, _ := service.GetHisOrder(admin.Org.Id, number, patient_id)
	all_prescriptions, _ := service.GetCallHisPrescriptions(startRecordDateTime, endRecordDateTime, admin.Org.Id, patient_id, 2)
	adminUserInfo, _ := service.GetAdminUserInfoByID(admin.Org.Id, admin.AdminUser.Id)
	doctors, _ := service.GetHisAdminUserDoctors(admin.Org.Id)
	//获取所有科室信息
	department, _ := service.GetAllDepartMent(admin.Org.Id)
	last_p_info, _ := service.FindLastPatientPrescriptionInfo(admin.Org.Id, patient_id, recordDateTime)
	last_prescriptions, _ = service.GetHisPrescription(admin.Org.Id, patient_id, last_p_info.RecordDate, 2)
	sch, _ := service.GetPatientSch(patient_id, recordDateTime, admin.Org.Id)
	if sch.ID > 0 {
		mode_template, _ := service.GetHisPrescriptionBySchMode(sch.ModeId, patient_id, admin.Org.Id)
		sch_prescriptions, _ = service.GetHisPrescriptionTemplate(mode_template.ID, admin.Org.Id)
	}
	count, _ := service.GetHisPatientCount(admin.Org.Id, patient_id, recordDateTime)
	c.ServeSuccessJSON(map[string]interface{}{
		"his_info":            his_patient_info,
		"xt_info":             xt_patient_info,
		"prescription":        prescriptions,
		"case_history":        case_history,
		"info":                patientPrescriptionInfo,
		"month_prescriptions": monthPrescriptions,
		"order":               order,
		"doctors":             doctors,
		"department":          department,
		"admin_user_info":     adminUserInfo,
		"all_prescriptions":   all_prescriptions,
		"sch_prescriptions":   sch_prescriptions,
		"last_prescriptions":  last_prescriptions,
		"schedule":            sch,
		"count":               count,
	})
	return

}
func (this *MobileHisApiController) GetCallHisPrescription() {
	patient_id, _ := this.GetInt64("patient_id", 0)
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	start_time := this.GetString("start_time")
	startime, _ := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
	end_time := this.GetString("end_time")
	endtime, _ := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
	adminUserInfo := this.GetMobileAdminUserInfo()
	prescriptions, err := service.GetCallHisPrescriptions(startime.Unix(), endtime.Unix(), adminUserInfo.Org.Id, patient_id, 2)
	if err == nil {
		this.ServeSuccessJSON(map[string]interface{}{
			"prescriptions": prescriptions,
		})
		return
	} else {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
}
func (c *MobileHisApiController) DeletePrescription() {
	prescription_id, _ := c.GetInt64("id")
	projects, _ := service.GetHisPrescriptionProjectsByID(prescription_id)
	advices, _ := service.GetHisPrescriptionAdviceByID(prescription_id)
	_, drugStockConfig := service.FindDrugStockAutomaticReduceRecordByOrgId(c.GetMobileAdminUserInfo().Org.Id)
	_, stockConfig := service.FindAutomaticReduceRecordByOrgId(c.GetAdminUserInfo().CurrentOrgId)

	err := service.DelelteHisPrescription(prescription_id, c.GetMobileAdminUserInfo().Org.Id)
	if err == nil {
		if len(projects) > 0 {
			for _, item := range projects {
				if item.Type == 3 { //处理透前准备耗材数量数据
					consumables, _ := service.FindHisConsumablesByID(item.UserOrgId, item.PatientId, item.RecordDate, item.ProjectId)
					if consumables.ID > 0 {
						consumables.Count = 0
						service.UpdateConsumables(&consumables)
					}
				}

				if stockConfig.IsOpen == 1 {
					if item.Type == 3 {
						good, _ := service.FindGoodInfoByIdTwo(item.ProjectId)
						f_count, _ := strconv.ParseFloat(strconv.FormatInt(item.Count, 10), 64)
						good.Total = good.Total + f_count
						service.UpdateGoodInfo(&good)
					}
				}
			}
		}
		if drugStockConfig.IsOpen == 1 {
			if len(advices) > 0 {
				for _, item := range advices {
					drug, _ := service.FindBaseDrugLibRecord(c.GetMobileAdminUserInfo().Org.Id, item.DrugId)
					if item.PrescribingNumberUnit == drug.MinUnit {
						drug.Total = drug.Total + item.PrescribingNumber
						service.UpdateBaseDrugLib(&drug)
					} else {
						if item.PrescribingNumberUnit == drug.MaxUnit {
							item.PrescribingNumber = item.PrescribingNumber * float64(drug.MinNumber)
							drug.Total = drug.Total + item.PrescribingNumber
							service.UpdateBaseDrugLib(&drug)
						}
					}
				}
			}
		}
		c.ServeSuccessJSON(map[string]interface{}{
			"msg": "删除成功",
		})
		return
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
}
func (c *MobileHisApiController) DeleteDoctorAdvice() {
	id, _ := c.GetInt64("id")
	advice, _ := service.GetHisDoctorAdvicesById(id)
	err := service.DelelteDoctorAdvice(id, c.GetMobileAdminUserInfo().Org.Id)
	_, drugStockConfig := service.FindDrugStockAutomaticReduceRecordByOrgId(c.GetMobileAdminUserInfo().Org.Id)

	if err == nil {
		if drugStockConfig.IsOpen == 1 {
			drug, _ := service.FindBaseDrugLibRecord(c.GetMobileAdminUserInfo().Org.Id, advice.DrugId)
			if advice.PrescribingNumberUnit == drug.MinUnit {
				drug.Total = drug.Total + advice.PrescribingNumber
				service.UpdateBaseDrugLib(&drug)
			} else {
				if advice.PrescribingNumberUnit == drug.MaxUnit {
					advice.PrescribingNumber = advice.PrescribingNumber * float64(drug.MinNumber)
					drug.Total = drug.Total + advice.PrescribingNumber
					service.UpdateBaseDrugLib(&drug)
				}
			}
		}
		c.ServeSuccessJSON(map[string]interface{}{
			"msg": "删除成功",
		})
		return
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
}
func (c *MobileHisApiController) DeleteProject() {
	id, _ := c.GetInt64("id")
	project, _ := service.GetHisProjectByID(id)
	adminInfo := c.GetMobileAdminUserInfo()
	var consumable models.DialysisBeforePrepare
	if project.ID > 0 && project.Type == 3 {
		consumable, _ = service.FindHisConsumablesByID(adminInfo.Org.Id, project.PatientId, project.RecordDate, project.ProjectId)
	}
	_, stockConfig := service.FindAutomaticReduceRecordByOrgId(c.GetMobileAdminUserInfo().Org.Id)

	err := service.DelelteProject(id, c.GetMobileAdminUserInfo().Org.Id)
	if err == nil {
		if stockConfig.IsOpen == 1 {
			if project.Type == 3 {
				good, _ := service.FindGoodInfoByIdTwo(project.ProjectId)
				f_count, _ := strconv.ParseFloat(strconv.FormatInt(project.Count, 10), 64)
				good.Total = good.Total + f_count
				service.UpdateGoodInfo(&good)
			}
		}

		if consumable.ID > 0 {
			consumable.Count = 0
			service.UpdateConsumables(&consumable)
		}
		c.ServeSuccessJSON(map[string]interface{}{
			"msg": "删除成功",
		})
		return
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
}
func (c *MobileHisApiController) CreateHisPrescription() {
	record_date := c.GetString("record_date")
	patient_id, _ := c.GetInt64("patient_id")
	reg_type, _ := c.GetInt64("reg_type")
	//diagnose := c.GetString("diagnose")
	sick_type, _ := c.GetInt64("sick_type")
	sick_history := c.GetString("sick_history")
	doctor_id, _ := c.GetInt64("doctor", 0)
	department, _ := c.GetInt64("department", 0)
	his_patient_id, _ := c.GetInt64("his_patient_id")
	dataBody := make(map[string]interface{}, 0)
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
	if err != nil {
		utils.ErrorLog(err.Error())
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", record_date+" 00:00:00", loc)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	adminInfo := c.GetMobileAdminUserInfo()
	recordDateTime := theTime.Unix()

	role, _ := service.GetAdminUserInfoByID(adminInfo.Org.Id, doctor_id)

	//校验库存总量

	_, drugStockConfig := service.FindDrugStockAutomaticReduceRecordByOrgId(c.GetMobileAdminUserInfo().Org.Id)
	_, stockConfig := service.FindAutomaticReduceRecordByOrgId(c.GetMobileAdminUserInfo().Org.Id)

	if drugStockConfig.IsOpen == 1 {
		if dataBody["prescriptions"] != nil && reflect.TypeOf(dataBody["prescriptions"]).String() == "[]interface {}" {
			prescriptions, _ := dataBody["prescriptions"].([]interface{})
			if len(prescriptions) > 0 {
				for _, item := range prescriptions {
					items := item.(map[string]interface{})
					if items["advices"] != nil && reflect.TypeOf(items["advices"]).String() == "[]interface {}" {
						advices := items["advices"].([]interface{})
						if len(advices) > 0 {
							for _, advice := range advices {
								var drug_id int64
								var prescribing_number float64
								var prescribingNumberUnit string

								if advice.(map[string]interface{})["id"] != nil || reflect.TypeOf(advice.(map[string]interface{})["id"]).String() == "float64" {
									drug_id = int64(advice.(map[string]interface{})["id"].(float64))
								}
								if advice.(map[string]interface{})["prescribing_number"] != nil || reflect.TypeOf(advice.(map[string]interface{})["prescribing_number"]).String() == "float64" {
									//presc ribing_number = advice.(map[string]interface{})["prescribing_number"].(float64)
									prescribing_number_str := advice.(map[string]interface{})["prescribing_number"].(string)
									prescribing_number, _ = strconv.ParseFloat(prescribing_number_str, 64)

								}

								if advice.(map[string]interface{})["prescribing_number_unit"] != nil && reflect.TypeOf(advice.(map[string]interface{})["prescribing_number_unit"]).String() == "string" {
									prescribingNumberUnit, _ = advice.(map[string]interface{})["prescribing_number_unit"].(string)
								}

								drug, _ := service.FindBaseDrugLibRecord(adminInfo.Org.Id, drug_id)
								if drug.ID == 0 {
									c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
									return
								}

								if prescribingNumberUnit == drug.MinUnit {
									if prescribing_number > drug.Total {
										c.ServeDynamicFailJsonSend(drug.DrugName + "库存不足")
										//c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeOutOfStockParamWrong)
										return
									}
								} else {
									if prescribingNumberUnit == drug.MaxUnit {
										num := prescribing_number * float64(drug.MinNumber)
										if num > drug.Total {
											c.ServeDynamicFailJsonSend(drug.DrugName + "库存不足")

											//c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeOutOfStockParamWrong)
											return
										}
									}
								}
							}
						}
					}
				}
			}
		}
	}
	if stockConfig.IsOpen == 1 {
		if dataBody["prescriptions"] != nil && reflect.TypeOf(dataBody["prescriptions"]).String() == "[]interface {}" {
			prescriptions, _ := dataBody["prescriptions"].([]interface{})
			if len(prescriptions) > 0 {
				for _, item := range prescriptions {
					items := item.(map[string]interface{})
					if items["project"] != nil && reflect.TypeOf(items["project"]).String() == "[]interface {}" {
						projects := items["project"].([]interface{})
						if len(projects) > 0 {
							for _, project := range projects {
								var project_id int64
								var project_type int64
								var totals float64
								if project.(map[string]interface{})["project_id"] != nil || reflect.TypeOf(project.(map[string]interface{})["project_id"]).String() == "float64" {
									project_id = int64(project.(map[string]interface{})["project_id"].(float64))
								}
								if project.(map[string]interface{})["type"] != nil || reflect.TypeOf(project.(map[string]interface{})["type"]).String() == "float64" {
									project_type = int64(project.(map[string]interface{})["type"].(float64))
								}
								if project.(map[string]interface{})["total"] != nil || reflect.TypeOf(project.(map[string]interface{})["total"]).String() == "string" {
									total, _ := project.(map[string]interface{})["total"].(string)

									totals, _ = strconv.ParseFloat(total, 64)
								}
								if project_type == 3 {
									good, _ := service.FindGoodInfoByIdTwo(project_id)
									if good.ID == 0 {
										c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
										return
									}
									if totals > good.Total {
										c.ServeDynamicFailJsonSend(good.GoodName + "库存不足")
										//
										//c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeOutOfStockParamWrong)
										return
									}

								}

							}
						}
					}
				}
			}
		}

	}

	info, _ := service.FindPatientPrescriptionInfo(adminInfo.Org.Id, patient_id, recordDateTime, 2)
	var hpInfo models.HisPrescriptionInfo
	if info.ID == 0 {
		var randNum int
		randNum = rand.Intn(10000) + 1000
		timestamp := time.Now().Unix()
		tempTime := time.Unix(timestamp, 0)
		timeFormat := tempTime.Format("20060102150405")
		p_number := timeFormat + strconv.FormatInt(int64(randNum), 10) + strconv.FormatInt(int64(adminInfo.Org.Id), 10) + strconv.FormatInt(int64(patient_id), 10)

		hpInfo = models.HisPrescriptionInfo{
			UserOrgId:  adminInfo.Org.Id,
			RecordDate: theTime.Unix(),
			PatientId:  patient_id,
			Status:     1,
			Ctime:      time.Now().Unix(),
			Mtime:      time.Now().Unix(),
			Creator:    adminInfo.AdminUser.Id,
			Modifier:   adminInfo.AdminUser.Id,
			//Diagnosis:          diagnose,
			SickHistory:        sick_history,
			Departments:        department,
			RegisterType:       reg_type,
			PrescriptionNumber: p_number,
			PrescriptionStatus: 1,
			Doctor:             role.UserName,
			DoctorId:           doctor_id,
			SickType:           sick_type,
			PType:              2,
		}
		service.SavePatientPrescriptionInfo(hpInfo)

	} else {
		hpInfo = models.HisPrescriptionInfo{
			ID:                 info.ID,
			UserOrgId:          adminInfo.Org.Id,
			RecordDate:         info.RecordDate,
			PatientId:          info.PatientId,
			Status:             1,
			Ctime:              info.Ctime,
			Mtime:              time.Now().Unix(),
			Creator:            info.Creator,
			Modifier:           adminInfo.AdminUser.Id,
			Diagnosis:          info.Diagnosis,
			SickHistory:        sick_history,
			Departments:        department,
			RegisterType:       reg_type,
			PrescriptionNumber: info.PrescriptionNumber,
			Doctor:             role.UserName,
			PrescriptionStatus: info.PrescriptionStatus,
			DoctorId:           doctor_id,
			SickType:           sick_type,
			PType:              info.PType,
		}
		service.SavePatientPrescriptionInfo(hpInfo)
	}

	if dataBody["prescriptions"] != nil && reflect.TypeOf(dataBody["prescriptions"]).String() == "[]interface {}" {
		prescriptions, _ := dataBody["prescriptions"].([]interface{})
		var tempPrescription *models.HisPrescription

		if len(prescriptions) > 0 {
			for _, item := range prescriptions {
				items := item.(map[string]interface{})
				if items["id"] == nil || reflect.TypeOf(items["id"]).String() != "float64" {
					utils.ErrorLog("id")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}
				id := int64(items["id"].(float64))

				new_prescription, _ := service.GetPrescriptionById(id, adminInfo.Org.Id)
				tempPrescription = &new_prescription

				if items["type"] == nil || reflect.TypeOf(items["type"]).String() != "float64" {
					utils.ErrorLog("type")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}
				types := int64(items["type"].(float64))

				//if items["med_type"] == nil || reflect.TypeOf(items["med_type"]).String() != "float64" {
				//	utils.ErrorLog("med_type")
				//	c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
				//	return
				//}
				//med_type := int64(items["med_type"].(float64))
				//med_type := strconv.Itoa(int(items["med_type"].(float64)))
				//med_type := strconv.Itoa(int(items["med_type"].(float64)))

				//if med_type == "0" {
				//}
				var med_type string
				if adminInfo.Org.Id == 9504 || adminInfo.Org.Id == 10138 {
					med_type = "13"

				} else {
					med_type = "14"
				}

				if items["order_status"] == nil || reflect.TypeOf(items["order_status"]).String() != "float64" {
					utils.ErrorLog("order_status")
				}
				order_status := int64(items["order_status"].(float64))

				if order_status == 0 {
					order_status = 1
				}

				if items["pre_time"] == nil || reflect.TypeOf(items["pre_time"]).String() != "string" {
					utils.ErrorLog("pre_time")
				}
				preTime, _ := items["pre_time"].(string)
				timeLayout := "2006-01-02"
				loc, _ := time.LoadLocation("Local")
				theTime2, err := time.ParseInLocation(timeLayout+" 15:04", preTime, loc)
				if err != nil {
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}
				fmt.Println(preTime)
				fmt.Println(theTime2)
				pTime := theTime2.Unix()
				fmt.Println(pTime)

				ctime := time.Now().Unix()
				if tempPrescription.ID == 0 {
					prescription := &models.HisPrescription{
						ID:                 id,
						PatientId:          patient_id,
						UserOrgId:          adminInfo.Org.Id,
						RecordDate:         recordDateTime,
						Ctime:              ctime,
						Mtime:              ctime,
						Type:               types,
						Modifier:           adminInfo.AdminUser.Id,
						Creator:            adminInfo.AdminUser.Id,
						Status:             1,
						Doctor:             role.UserName,
						HisPatientId:       his_patient_id,
						OrderStatus:        order_status,
						BatchNumber:        "",
						PrescriptionNumber: hpInfo.PrescriptionNumber,
						PreTime:            pTime,
						PType:              2,
						MedType:            med_type,
					}
					tempPrescription = prescription
				} else {
					tempPrescription.Type = types
					tempPrescription.Modifier = adminInfo.AdminUser.Id
					tempPrescription.Mtime = time.Now().Unix()
					tempPrescription.Doctor = role.UserName
					tempPrescription.OrderStatus = order_status
					tempPrescription.PreTime = pTime
					tempPrescription.PType = 2
					tempPrescription.MedType = med_type

				}
				service.SaveHisPrescription(tempPrescription)

				//更改患者挂号状态
				_, err2 := service.UpdateHisPatientIsReturn(patient_id, recordDateTime, adminInfo.Org.Id)
				fmt.Println("更改失败", err2)
				if items["advices"] != nil && reflect.TypeOf(items["advices"]).String() == "[]interface {}" {
					advices := items["advices"].([]interface{})
					//group := service.GetMaxAdviceGroupID(adminInfo.CurrentOrgId)
					groupNo := int64(0)
					ctime := time.Now().Unix()
					mtime := ctime
					if len(advices) > 0 {
						for _, advice := range advices {
							var s models.HisDoctorAdviceInfo
							s.PrescriptionId = tempPrescription.ID
							s.AdviceType = 2
							s.AdviceDoctor = doctor_id
							s.StopState = 2
							s.ExecutionState = 2
							s.AdviceDate = recordDateTime
							s.Status = 1
							s.UserOrgId = adminInfo.Org.Id
							s.RecordDate = recordDateTime
							s.StartTime = pTime
							s.Groupno = groupNo
							s.CreatedTime = ctime
							s.UpdatedTime = mtime
							s.PatientId = patient_id
							s.HisPatientId = his_patient_id
							errcode := c.setAdviceWithJSON(&s, advice.(map[string]interface{}))
							if errcode > 0 {
								c.ServeFailJSONWithSGJErrorCode(errcode)
								return
							}
							service.CreateHisDoctorAdvice(&s)
							var randNum int
							randNum = rand.Intn(10000) + 1000
							timestamp := time.Now().Unix()
							tempTime := time.Unix(timestamp, 0)
							timeFormat := tempTime.Format("20060102150405")
							s.FeedetlSn = timeFormat + strconv.FormatInt(int64(randNum), 10) + "-" + "1" + "-" + strconv.FormatInt(s.ID, 10)
							service.CreateHisDoctorAdvice(&s)

						}
					}
				}
				if items["project"] != nil && reflect.TypeOf(items["project"]).String() == "[]interface {}" {
					projects := items["project"].([]interface{})
					if len(projects) > 0 {
						for _, project := range projects {
							var p models.HisPrescriptionProject
							p.PrescriptionId = tempPrescription.ID
							p.Ctime = time.Now().Unix()
							p.Mtime = time.Now().Unix()
							p.PatientId = patient_id
							p.RecordDate = recordDateTime
							p.UserOrgId = adminInfo.Org.Id
							p.HisPatientId = his_patient_id
							p.Status = 1
							p.Doctor = doctor_id
							p.StartTime = pTime
							errcode := c.setProjectWithJSON(&p, project.(map[string]interface{}))
							if errcode > 0 {
								c.ServeFailJSONWithSGJErrorCode(errcode)
								return
							}
							service.CreateHisProjectTwo(&p)

							var randNum int
							randNum = rand.Intn(10000) + 1000
							timestamp := time.Now().Unix()
							tempTime := time.Unix(timestamp, 0)
							timeFormat := tempTime.Format("20060102150405")
							p.FeedetlSn = timeFormat + strconv.FormatInt(int64(randNum), 10) + "-" + "2" + "-" + strconv.FormatInt(p.ID, 10)
							service.SaveHisProjectTwo(&p)

							if p.Type == 3 { //处理透前准备耗材数量数据
								consumables, _ := service.FindHisConsumablesByID(adminInfo.Org.Id, patient_id, recordDateTime, p.ProjectId)
								if consumables.ID > 0 {
									consumables.Count = p.Count
									service.UpdateConsumables(&consumables)
								}
							}

						}
					}
				}

			}
		}
	}
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"msg": "保存成功",
		})
		return

	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
}
func (this *MobileHisApiController) GetLastOrNextHisPrescription() {
	change_type, _ := this.GetInt64("type", 0)
	record_date := this.GetString("record_time")
	patient_id, _ := this.GetInt64("patient_id", 0)

	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	theAdviceRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
	record_time := theAdviceRecordTime.Unix()
	adminUserInfo := this.GetMobileAdminUserInfo()
	prescriptions, err := service.GetHisPrescriptionByType(change_type, record_time, adminUserInfo.Org.Id, patient_id, 2)
	if err == nil {
		if len(prescriptions) == 0 {
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDoctorAdviceEmpty)
			return
		} else {
			this.ServeSuccessJSON(map[string]interface{}{
				"prescriptions": prescriptions,
			})
			return
		}
	} else {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
}
func (c *MobileHisApiController) setAdviceWithJSON(advice *models.HisDoctorAdviceInfo, json map[string]interface{}) int {

	if json["drug_name"] == nil || reflect.TypeOf(json["drug_name"]).String() != "string" {
		utils.ErrorLog("drug_name")
		return enums.ErrorCodeParamWrong
	}
	adviceName, _ := json["drug_name"].(string)
	if len(adviceName) == 0 {
		utils.ErrorLog("len(advice_name) == 0")
		return enums.ErrorCodeParamWrong
	}
	advice.AdviceName = adviceName
	adviceDesc, _ := json["advice_desc"].(string)
	advice.AdviceDesc = adviceDesc
	if json["drug_spec"] != nil && reflect.TypeOf(json["drug_spec"]).String() == "string" {
		drugSpec, _ := strconv.ParseFloat(json["drug_spec"].(string), 64)
		advice.DrugSpec = drugSpec
	}
	if json["remark"] != nil && reflect.TypeOf(json["remark"]).String() == "string" {
		remark, _ := json["remark"].(string)
		advice.Remark = remark
	}
	if json["id"] == nil {
		advice.DrugId = 0
	} else {
		if json["id"] != nil || reflect.TypeOf(json["id"]).String() == "float64" {
			drug_id := int64(json["id"].(float64))
			advice.DrugId = drug_id
		}
	}
	if json["groupno"] != nil || reflect.TypeOf(json["groupno"]).String() == "float64" {
		groupno := int64(json["groupno"].(float64))
		advice.Groupno = groupno
	}

	if json["advice_id"] != nil && reflect.TypeOf(json["advice_id"]).String() == "float64" {
		advice_id := int64(json["advice_id"].(float64))
		advice.ID = advice_id
		if advice.ID > 0 {
			hisAdvice, err := service.GetHisDoctorAdvicesById(advice.ID)
			if err == nil {
				if hisAdvice.ID > 0 {
					advice.ExecutionTime = hisAdvice.ExecutionTime
					advice.ExecutionStaff = hisAdvice.ExecutionStaff
					advice.ExecutionState = hisAdvice.ExecutionState
					advice.CheckTime = hisAdvice.CheckTime
					advice.Checker = hisAdvice.Checker
					advice.CheckState = hisAdvice.CheckState
					//advice.Groupno = hisAdvice.Groupno
					//advice.StartTime = hisAdvice.StartTime

				}
			}
		}
	}

	if json["prescribing_number"] != nil && reflect.TypeOf(json["prescribing_number"]).String() == "string" {
		prescribingNumber, _ := strconv.ParseFloat(json["prescribing_number"].(string), 64)
		advice.PrescribingNumber = prescribingNumber
	}

	if json["prescribing_number_unit"] != nil && reflect.TypeOf(json["prescribing_number_unit"]).String() == "string" {
		prescribingNumberUnit, _ := json["prescribing_number_unit"].(string)
		advice.PrescribingNumberUnit = prescribingNumberUnit
	}

	_, drugStockConfig := service.FindDrugStockAutomaticReduceRecordByOrgId(c.GetMobileAdminUserInfo().Org.Id)

	if drugStockConfig.IsOpen == 1 {
		drug, _ := service.FindBaseDrugLibRecord(advice.UserOrgId, advice.DrugId)
		if advice.ID == 0 { //医嘱不存在
			if advice.PrescribingNumberUnit == drug.MinUnit { //当前数据单位与基础库一致为最小单位，直接计算
				drug.Total = drug.Total - advice.PrescribingNumber
				service.UpdateBaseDrugLib(&drug)

			} else if advice.PrescribingNumberUnit == drug.MaxUnit { //当前数据单位为最大单位，需要将最大单位转为最小单位
				num := advice.PrescribingNumber * float64(drug.MinNumber)
				drug.Total = drug.Total - num
				service.UpdateBaseDrugLib(&drug)
			}

		} else if advice.ID > 0 { //医嘱存在
			hisAdvice, _ := service.GetHisDoctorAdvicesById(advice.ID)
			var num float64

			if advice.PrescribingNumberUnit == drug.MinUnit { //当前数据为最小单位
				if advice.PrescribingNumberUnit == hisAdvice.PrescribingNumberUnit { //原数据为最小单位，三个单位一致为最小单位直接计算
					if hisAdvice.PrescribingNumber > advice.PrescribingNumber {
						num = hisAdvice.PrescribingNumber - advice.PrescribingNumber
						drug.Total = drug.Total + num
						service.UpdateBaseDrugLib(&drug)
					} else if hisAdvice.PrescribingNumber < advice.PrescribingNumber {
						num = advice.PrescribingNumber - hisAdvice.PrescribingNumber
						drug.Total = drug.Total - num
						service.UpdateBaseDrugLib(&drug)
					}
				} else { //原数据为最大单位，需要将最大单位数量转为最小单位数量
					num2 := hisAdvice.PrescribingNumber * float64(drug.MinNumber)
					if num2 > advice.PrescribingNumber {
						num = num2 - advice.PrescribingNumber
						drug.Total = drug.Total + num
						service.UpdateBaseDrugLib(&drug)
					} else if num2 < advice.PrescribingNumber {
						num = advice.PrescribingNumber - num2
						drug.Total = drug.Total - num
						service.UpdateBaseDrugLib(&drug)
					}

				}

			} else if advice.PrescribingNumberUnit == drug.MaxUnit { //当前数据为最大单位
				if advice.PrescribingNumberUnit == hisAdvice.PrescribingNumberUnit { //原数据为最大单位， 当前数据单位和原数据单位都为最大单位，需要将两个数据转成最小单位
					num1 := hisAdvice.PrescribingNumber * float64(drug.MinNumber)
					num2 := advice.PrescribingNumber * float64(drug.MinNumber)
					if num1 > num2 {
						num = num1 - num2
						drug.Total = drug.Total + num
						service.UpdateBaseDrugLib(&drug)
					} else if num1 < num2 {
						num = num2 - num1
						drug.Total = drug.Total - num
						service.UpdateBaseDrugLib(&drug)
					}

				} else { //原数据为最小单位，当前数据为最大单位，需要将当前数据数量转为最小单位数量
					num2 := advice.PrescribingNumber * float64(drug.MinNumber)
					//num2 := hisAdvice.PrescribingNumber * (drug.Dose / float64(drug.MinNumber))
					if hisAdvice.PrescribingNumber > num2 {
						num = hisAdvice.PrescribingNumber - num2
						drug.Total = drug.Total + num
						service.UpdateBaseDrugLib(&drug)
					} else if num2 < advice.PrescribingNumber {
						num = num2 - hisAdvice.PrescribingNumber
						drug.Total = drug.Total - num
						service.UpdateBaseDrugLib(&drug)
					}

				}
			}
		}
	}

	//
	//if json["execution_time"] != nil && reflect.TypeOf(json["execution_time"]).String() == "string" {
	//	execution_time, _ := strconv.ParseInt(json["execution_time"].(string), 10,64)
	//	advice.ExecutionTime = execution_time
	//}
	//
	//
	//
	//if json["execution_staff"] != nil && reflect.TypeOf(json["execution_staff"]).String() == "string" {
	//	execution_staff, _ := strconv.ParseInt(json["execution_staff"].(string), 10,64)
	//	advice.ExecutionStaff = execution_staff
	//}
	//
	//
	//
	//if json["execution_state"] != nil && reflect.TypeOf(json["execution_state"]).String() == "string" {
	//	execution_state, _ := strconv.ParseInt(json["execution_state"].(string), 10,64)
	//	advice.ExecutionState = execution_state
	//}
	//
	//
	//if json["check_time"] != nil && reflect.TypeOf(json["check_time"]).String() == "string" {
	//	check_time, _ := strconv.ParseInt(json["check_time"].(string), 10,64)
	//	advice.CheckTime = check_time
	//}
	//
	//
	//if json["check_state"] != nil && reflect.TypeOf(json["check_state"]).String() == "string" {
	//	check_state, _ := strconv.ParseInt(json["check_state"].(string), 10,64)
	//	advice.CheckState = check_state
	//}
	//
	//
	//if json["checker"] != nil && reflect.TypeOf(json["checker"]).String() == "string" {
	//	checker, _ := strconv.ParseInt(json["checker"].(string), 10,64)
	//	advice.Checker = checker
	//}
	//
	//if json["start_time"] != nil && reflect.TypeOf(json["start_time"]).String() == "string" {
	//	start_time, _ := strconv.ParseInt(json["start_time"].(string), 10,64)
	//	advice.StartTime = start_time
	//}

	if json["min_unit"] != nil && reflect.TypeOf(json["min_unit"]).String() == "string" {
		drugSpecUnit, _ := json["min_unit"].(string)
		advice.DrugSpecUnit = drugSpecUnit
	}
	if json["single_dose"] != nil && reflect.TypeOf(json["single_dose"]).String() == "string" {
		singleDose, _ := strconv.ParseFloat(json["single_dose"].(string), 64)
		advice.SingleDose = singleDose
	}
	if json["single_dose_unit"] != nil && reflect.TypeOf(json["single_dose_unit"]).String() == "string" {
		singleDoseUnit, _ := json["single_dose_unit"].(string)
		advice.SingleDoseUnit = singleDoseUnit
	}

	if json["delivery_way"] != nil && reflect.TypeOf(json["delivery_way"]).String() == "string" {
		deliveryWay, _ := json["delivery_way"].(string)
		advice.DeliveryWay = deliveryWay
	}
	if json["execution_frequency"] != nil && reflect.TypeOf(json["execution_frequency"]).String() == "string" {
		executionFrequency, _ := json["execution_frequency"].(string)
		advice.ExecutionFrequency = executionFrequency
	}

	if json["retail_price"] != nil || reflect.TypeOf(json["retail_price"]).String() == "string" {
		price, _ := strconv.ParseFloat(json["retail_price"].(string), 64)
		advice.Price = price
	}
	if json["medical_insurance_number"] != nil || reflect.TypeOf(json["medical_insurance_number"]).String() == "string" {
		med_list_codg, _ := json["medical_insurance_number"].(string)
		advice.MedListCodg = med_list_codg
	}
	if json["day"] != nil || reflect.TypeOf(json["day"]).String() == "float64" {
		day := int64(json["day"].(float64))
		advice.Day = day
	}
	return 0
}
func (c *MobileHisApiController) setProjectWithJSON(project *models.HisPrescriptionProject, json map[string]interface{}) int {
	project.ExecutionStaff = 0
	project.ExecutionState = 2
	project.ExecutionTime = 0
	project.Checker = 0
	project.CheckState = 2
	project.CheckTime = 0
	if json["id"] != nil || reflect.TypeOf(json["id"]).String() == "float64" {
		id := int64(json["id"].(float64))
		project.ID = id
		temp_project, _ := service.GetHisPrescriptionProjectByID(id)
		project.ExecutionStaff = temp_project.ExecutionStaff
		project.ExecutionState = temp_project.ExecutionState
		project.ExecutionTime = temp_project.ExecutionTime
		project.Checker = temp_project.Checker
		project.CheckState = temp_project.CheckState
		project.CheckTime = temp_project.CheckTime
	}
	if json["type"] != nil || reflect.TypeOf(json["type"]).String() == "float64" {
		types := int64(json["type"].(float64))
		project.Type = types
	}

	if json["project_id"] != nil || reflect.TypeOf(json["project_id"]).String() == "float64" {
		project_id := int64(json["project_id"].(float64))
		project.ProjectId = project_id
		fmt.Println(project_id)
		fmt.Println(project.ProjectId)
	}
	// if json["price"] != nil || reflect.TypeOf(json["price"]).String() == "float64" {
	// 	price := int64(json["price"].(float64))
	// 	formatInt_price := strconv.FormatInt(price, 10)
	// 	float_price, _ := strconv.ParseFloat(formatInt_price, 64)
	// 	project.Price = float_price
	// }
	if json["price"] != nil || reflect.TypeOf(json["price"]).String() == "string" {
		price, _ := strconv.ParseFloat(json["price"].(string), 64)
		project.Price = price
	}

	if json["total"] != nil && reflect.TypeOf(json["total"]).String() == "string" {
		total, _ := json["total"].(string)
		totals, _ := strconv.ParseInt(total, 10, 64)
		project.Count = totals
	}

	if json["medical_code"] != nil && reflect.TypeOf(json["medical_code"]).String() == "string" {
		medical_code, _ := json["medical_code"].(string)
		project.MedListCodg = medical_code
	}
	if json["single_dose"] != nil && reflect.TypeOf(json["single_dose"]).String() == "string" {
		single_dose, _ := json["single_dose"].(string)
		project.SingleDose = single_dose
	}

	if json["delivery_way"] != nil && reflect.TypeOf(json["delivery_way"]).String() == "string" {
		delivery_way, _ := json["delivery_way"].(string)
		project.DeliveryWay = delivery_way
	}
	if json["execution_frequency"] != nil && reflect.TypeOf(json["execution_frequency"]).String() == "string" {
		execution_frequency, _ := json["execution_frequency"].(string)
		project.ExecutionFrequency = execution_frequency
	}
	if json["remark"] != nil && reflect.TypeOf(json["remark"]).String() == "string" {
		remark, _ := json["remark"].(string)
		project.Remark = remark
	}
	if json["number_days"] != nil && reflect.TypeOf(json["number_days"]).String() == "string" {
		day, _ := json["number_days"].(string)
		project.Day = day
	}

	if json["unit"] != nil && reflect.TypeOf(json["unit"]).String() == "string" {
		unit, _ := json["unit"].(string)
		project.Unit = unit
	}

	_, stockConfig := service.FindAutomaticReduceRecordByOrgId(project.UserOrgId)

	if project.ID == 0 {
		if stockConfig.IsOpen == 1 {
			if project.Type == 3 {
				good, _ := service.FindGoodInfoByIdTwo(project.ProjectId)
				f_count, _ := strconv.ParseFloat(strconv.FormatInt(project.Count, 10), 64)
				good.Total = good.Total - f_count
				service.UpdateGoodInfo(&good)
			}
		}

	} else {
		temp_project, _ := service.GetHisPrescriptionProjectByID(project.ID)

		if stockConfig.IsOpen == 1 {
			if project.Type == 3 {
				good, _ := service.FindGoodInfoByIdTwo(project.ProjectId)
				if project.Count < temp_project.Count {
					other_count := temp_project.Count - project.Count
					other_count_two, _ := strconv.ParseFloat(strconv.FormatInt(other_count, 10), 64)
					good.Total = good.Total + other_count_two
					service.UpdateGoodInfo(&good)
				} else if project.Count > temp_project.Count {
					other_count := project.Count - temp_project.Count
					other_count_two, _ := strconv.ParseFloat(strconv.FormatInt(other_count, 10), 64)
					good.Total = good.Total - other_count_two
					service.UpdateGoodInfo(&good)
				}

			}
		}

	}

	return 0
}
func (c *MobileHisApiController) GetHisPatientList() {
	record_date := c.GetString("record_date")
	sch_type, _ := c.GetInt64("sch_type")
	visit_type, _ := c.GetInt64("visit_type")

	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")

	theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", record_date+" 00:00:00", loc)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	recordDateTime := theTime.Unix()
	adminInfo := c.GetMobileAdminUserInfo()
	patients, _ := service.GetScheduleHisPatientList(adminInfo.Org.Id, "", recordDateTime, sch_type)
	patients_two, _ := service.GetHisPatientList(adminInfo.Org.Id, "", recordDateTime)
	patients = append(patients, patients_two...)
	patients = RemoveRepeatedPatient(patients)
	if visit_type == 0 {
		c.ServeSuccessJSON(map[string]interface{}{
			"list": patients,
		})

	} else if visit_type == 1 { //未就诊
		var patientsOne []*service.Patients
		for _, item := range patients {
			if item.HisPrescription == nil || len(item.HisPrescription) <= 0 {
				patientsOne = append(patientsOne, item)
			}
		}
		c.ServeSuccessJSON(map[string]interface{}{
			"list": patientsOne,
		})

	} else if visit_type == 2 { //已就诊
		var patientsTwo []*service.Patients
		for _, item := range patients {

			if item.HisPrescription != nil && len(item.HisPrescription) > 0 {
				patientsTwo = append(patientsTwo, item)
			}
		}
		c.ServeSuccessJSON(map[string]interface{}{
			"list": patientsTwo,
		})
	}

}

func RemoveRepeatedPatient(patient []*service.Patients) (newArr []*service.Patients) {
	newArr = make([]*service.Patients, 0)
	for i := 0; i < len(patient); i++ {
		repeat := false
		for j := i + 1; j < len(patient); j++ {
			if patient[i].ID == patient[j].ID {
				repeat = true
				break
			}
		}
		if !repeat {
			newArr = append(newArr, patient[i])
		}
	}
	return
}
