package new_mobile_api_controllers

import (
	"XT_New/controllers/mobile_api_controllers"
	"XT_New/enums"
	"XT_New/models"
	"XT_New/service"
	"XT_New/utils"
	"encoding/json"
	"fmt"
	"github.com/jinzhu/gorm"
	"reflect"
	"strconv"
	"strings"
	"time"
)

type StaffScheduleApiController struct {
	mobile_api_controllers.MobileBaseAPIAuthController
}

func (this *StaffScheduleApiController) GetMobileDoctorList() {

	orgId := this.GetMobileAdminUserInfo().Org.Id
	appId := this.GetMobileAdminUserInfo().App.Id
	staffList, err := service.GetDoctorList(orgId, appId)
	//获取所有的医生
	doctorList, err := service.GetAllDoctorList(orgId, appId)

	//获取所有的护士
	nurseList, err := service.GetAllNurseList(orgId, appId)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeDataException, "添加设备失败")
		return
	}

	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeDataException, "添加设备失败")
		return
	}

	this.ServeSuccessJSON(map[string]interface{}{
		"staffList":  staffList,
		"doctorList": doctorList,
		"nurseList":  nurseList,
	})
}

func (this *StaffScheduleApiController) GetMobileStaffScheduleList() {

	orgId := this.GetMobileAdminUserInfo().Org.Id
	start_time, _ := this.GetInt64("start_time")
	fmt.Println("staft_time", start_time)
	end_time, _ := this.GetInt64("end_time")
	staffList, err := service.GetStaffScheduleList(orgId, start_time, end_time)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeDataException, "添加设备失败")
		return
	}

	this.ServeSuccessJSON(map[string]interface{}{
		"staffList": staffList,
	})
}

func (this *StaffScheduleApiController) GetMobileNextWeekScheduleLIst() {

	orgId := this.GetMobileAdminUserInfo().Org.Id
	start_time, _ := this.GetInt64("start_time")
	end_time, _ := this.GetInt64("end_time")

	staffList, err := service.GetStaffScheduleList(orgId, start_time, end_time)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeDataException, "添加设备失败")
		return
	}

	this.ServeSuccessJSON(map[string]interface{}{
		"staffList": staffList,
	})
}

func (this *StaffScheduleApiController) GetScheduleByUserType() {
	doctor_id, _ := this.GetInt64("doctor_id")
	start_time, _ := this.GetInt64("start_time")
	end_time, _ := this.GetInt64("end_time")
	orgId := this.GetMobileAdminUserInfo().Org.Id
	staffList, err := service.GetScheduleByDoctorId(doctor_id, start_time, end_time, orgId)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeDataException, "添加设备失败")
		return
	}

	this.ServeSuccessJSON(map[string]interface{}{
		"staffList": staffList,
	})
}

func (this *StaffScheduleApiController) GetSearchPatientByDoctorId() {

	orgId := this.GetMobileAdminUserInfo().Org.Id
	user_name := this.GetString("user_name")
	start_time, _ := this.GetInt64("start_time")
	end_time, _ := this.GetInt64("end_time")
	staffList, err := service.ToSearchSeacheduleList(user_name, start_time, end_time, orgId)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeDataException, "添加设备失败")
		return
	}

	this.ServeSuccessJSON(map[string]interface{}{
		"staffList": staffList,
	})
}

func (this *StaffScheduleApiController) GetMobileSchedulelist() {

	orgId := this.GetMobileAdminUserInfo().Org.Id
	list, err := service.GetScheduleList(orgId)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeDataException, "添加设备失败")
		return
	}

	this.ServeSuccessJSON(map[string]interface{}{
		"list": list,
	})
}

func (this *StaffScheduleApiController) GetMobileScheduleListTotal() {

	start_time, _ := this.GetInt64("start_time")
	end_time, _ := this.GetInt64("end_time")
	orgId := this.GetMobileAdminUserInfo().Org.Id

	//统计班次
	scheudletotal, err := service.GetScheduleListTotal(orgId, start_time, end_time)
	//统计总工时
	list, err := service.GetTotalMinutes(orgId, start_time, end_time)
	//统计出勤天数
	workDay, err := service.GetTotalWorkDay(orgId, start_time, end_time)
	//统计缺勤天数
	noWorkDay, err := service.GetTotalNoWorkDay(orgId, start_time, end_time)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeDataException, "添加设备失败")
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"scheudletotal": scheudletotal,
		"list":          list,
		"workDay":       workDay,
		"noWorkDay":     noWorkDay,
	})
}

func (this *StaffScheduleApiController) GetMySchedule() {
	start_time, _ := this.GetInt64("start_time")
	end_time, _ := this.GetInt64("end_time")
	orgId := this.GetMobileAdminUserInfo().Org.Id
	creator, _ := this.GetInt64("creator")
	schedule, err := service.GetMySchedule(start_time, end_time, orgId, creator)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeDataException, "添加设备失败")
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"schedule": schedule,
	})
}

func (this *StaffScheduleApiController) GetMobileChartList() {

	start_time, _ := this.GetInt64("start_time")
	end_time, _ := this.GetInt64("end_time")
	orgId := this.GetMobileAdminUserInfo().Org.Id
	//统计总工时
	list, err := service.GetTotalMinutesOne(orgId, start_time, end_time)
	//统计出勤的总工时
	workDaylist, err := service.GetTotalMinutesTwo(orgId, start_time, end_time)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeDataException, "添加设备失败")
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"list":        list,
		"workDaylist": workDaylist,
	})
}

func (this *StaffScheduleApiController) ToSearchMobileTotal() {

	start_time, _ := this.GetInt64("start_time")
	end_time, _ := this.GetInt64("end_time")
	orgId := this.GetMobileAdminUserInfo().Org.Id
	keyword := this.GetString("keyword")
	//统计表
	scheduletotal, err := service.GetSearchScheduleListTotal(orgId, start_time, end_time, keyword)
	list, err := service.GeSearchtTotalMinutes(orgId, start_time, end_time, keyword)
	workDay, err := service.GetSearchWorkDay(orgId, start_time, end_time, keyword)
	noWorkDay, err := service.GetSearchWorkNoDay(orgId, start_time, end_time, keyword)

	//统计图
	chartTotalMinute, err := service.GetChartTotalMinutesOne(orgId, start_time, end_time, keyword)
	chartWorkDayMinute, err := service.GetChartTotalMinutesTwo(orgId, start_time, end_time, keyword)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeDataException, "添加设备失败")
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"scheduletotal":      scheduletotal,
		"list":               list,
		"workDay":            workDay,
		"noWorkDay":          noWorkDay,
		"chartTotalMinute":   chartTotalMinute,
		"chartWorkDayMinute": chartWorkDayMinute,
	})
}

func (this *StaffScheduleApiController) ChangeMobileOption() {

	start_time, _ := this.GetInt64("start_time")
	end_time, _ := this.GetInt64("end_time")
	orgId := this.GetMobileAdminUserInfo().Org.Id
	doctor_type, _ := this.GetInt64("doctor_type")
	//统计图
	scheduletotal, err := service.ChagneScheduleListTotal(orgId, start_time, end_time, doctor_type)
	list, err := service.ChangeScheduleMinute(orgId, start_time, end_time, doctor_type)
	workday, err := service.ChangeWorkDay(orgId, start_time, end_time, doctor_type)
	worknoday, err := service.ChangeNoWorkDay(orgId, start_time, end_time, doctor_type)

	//统计表
	chartotalminute, err := service.ChartTotalMinute(orgId, start_time, end_time, doctor_type)
	chartworkdayminute, err := service.ChartWorkDayMinute(orgId, start_time, end_time, doctor_type)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeDataException, "添加设备失败")
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"scheduletotal":      scheduletotal,
		"list":               list,
		"workday":            workday,
		"worknoday":          worknoday,
		"chartotalminute":    chartotalminute,
		"chartworkdayminute": chartworkdayminute,
	})
}

func (this *StaffScheduleApiController) GetAllZone() {

	id := this.GetMobileAdminUserInfo().Org.Id
	zone, err := service.GetAllMobileZone(id)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeDataException, "添加设备失败")
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"zone": zone,
	})
}

func (this *StaffScheduleApiController) GetPatientScheduleList() {
	orgid := this.GetMobileAdminUserInfo().Org.Id
	fmt.Println("orgid", orgid)
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	start_time := this.GetString("start_time")
	var startTime int64
	if len(start_time) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
		if err != nil {
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		startTime = theTime.Unix()
	}
	zoneid, _ := this.GetInt64("zoneid")
	fmt.Println(zoneid)
	classtype, _ := this.GetInt64("classtype")

	is_open, _ := this.GetInt64("is_open")

	if is_open == 0 {
		//获取当天排班的病人情况
		schedule, err := service.GetPatientSchedule(startTime, zoneid, classtype, orgid)

		if err != nil {
			this.ServeFailJsonSend(enums.ErrorCodeDataException, "添加设备失败")
			return
		}
		this.ServeSuccessJSON(map[string]interface{}{
			"schedule": schedule,
		})
	}
	if is_open == 1 {
		//获取空床位的排班数据
		list, err := service.GetPatientScheduleByBed(startTime, zoneid, orgid, classtype)
		stockType, _ := service.GetStockType(orgid)
		if err != nil {
			this.ServeFailJsonSend(enums.ErrorCodeDataException, "添加设备失败")
			return
		}
		this.ServeSuccessJSON(map[string]interface{}{
			"schedule":  list,
			"stockType": stockType,
		})
	}
}

func (this *StaffScheduleApiController) DeleteSchedule() {
	id, _ := this.GetInt64("id")
	fmt.Println("id", id)

	org_id := this.GetMobileAdminUserInfo().Org.Id
	err := service.DeleteSchedule(id)
	schedule, _ := service.GetScheduleNight(org_id, id)

	redis := service.RedisClient()

	//处方
	keyOne := strconv.FormatInt(org_id, 10) + ":" + strconv.FormatInt(schedule.ScheduleDate, 10) + ":prescriptions_list_all"
	redis.Set(keyOne, "", time.Second)

	//医嘱
	keyTwo := strconv.FormatInt(org_id, 10) + ":" + strconv.FormatInt(schedule.ScheduleDate, 10) + ":advice_list_all"
	redis.Set(keyTwo, "", time.Second)

	keySix := strconv.FormatInt(org_id, 10) + ":" + strconv.FormatInt(schedule.ScheduleDate, 10) + ":assessment_befores_list_all"
	redis.Set(keySix, "", time.Second)
	keyThree := strconv.FormatInt(org_id, 10) + ":" + strconv.FormatInt(schedule.ScheduleDate, 10) + ":assessment_after_dislysis_list_all"
	redis.Set(keyThree, "", time.Second)

	keyFour := strconv.FormatInt(org_id, 10) + ":" + strconv.FormatInt(schedule.ScheduleDate, 10) + ":monitor_record_list_all"
	redis.Set(keyFour, "", time.Second)

	keyFive := strconv.FormatInt(org_id, 10) + ":" + strconv.FormatInt(schedule.ScheduleDate, 10) + ":treatment_summarys_list_all"
	redis.Set(keyFive, "", time.Second)

	keySeven := strconv.FormatInt(org_id, 10) + ":" + strconv.FormatInt(schedule.ScheduleDate, 10) + ":dialysis_orders_list_all"
	redis.Set(keySeven, "", time.Second)

	defer redis.Close()
	fmt.Println(err)

	returnData := make(map[string]interface{}, 0)
	returnData["msg"] = "ok"
	this.ServeSuccessJSON(returnData)
	return
}

func (this *StaffScheduleApiController) SearchPatient() {
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	keyword := this.GetString("keyword")
	fmt.Println(keyword)
	orgId := this.GetMobileAdminUserInfo().Org.Id
	start_time := this.GetString("start_time")
	var startTime int64
	if len(start_time) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
		if err != nil {
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		startTime = theTime.Unix()
	}
	schedule, err := service.GetSearchPatient(keyword, orgId, startTime)

	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeDataException, "添加设备失败")
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"schedule": schedule,
	})
}

func (this *StaffScheduleApiController) UpdatePatientScheduleById() {

	ids := this.GetString("ids")
	idSplit := strings.Split(ids, ",")
	var err error
	//查询患者信息
	list, _ := service.GetStaffScheduleById(idSplit)
	if len(list) > 0 {
		for index, _ := range list {
			fmt.Println("index2322332", index)
			schedule := models.XtSchedule{
				PatientId: list[0].PatientId,
				ModeId:    list[0].ModeId,
			}
			xtSchedule := models.WeekSchedule{
				PatientId: list[1].PatientId,
				ModeId:    list[1].ModeId,
			}
			err = service.UpdateStaffSchedule(list[1].ID, schedule)
			fmt.Println("errrrrrrr2323323232323", err)
			service.UpdateStaffScheduleOne(list[0].ID, xtSchedule)
		}
	}
	fmt.Println(err)
	this.ServeSuccessJSON(map[string]interface{}{
		"msg": "切换成功",
	})
}
func (this *StaffScheduleApiController) UpdateDialysisPrescription() {
	patient_id, _ := this.GetInt64("patient_id")
	start_time, _ := this.GetInt64("start_time")
	mode_id, _ := this.GetInt64("mode_id")
	dialyzer_perfusion_apparatus := this.GetString("dialyzer_perfusion_apparatus")
	dialysis_irrigation := this.GetString("dialysis_irrigation")
	//更改透析模式
	_, errcode := service.GetDialyisSolution(patient_id, start_time)
	if errcode == gorm.ErrRecordNotFound {
		orgId := this.GetMobileAdminUserInfo().Org.Id
		prescription := models.DialysisPrescription{
			DialysisDialyszers: dialyzer_perfusion_apparatus,
			DialysisIrrigation: dialysis_irrigation,
			PatientId:          patient_id,
			UserOrgId:          orgId,
			Status:             1,
			RecordDate:         start_time,
			CreatedTime:        time.Now().Unix(),
			ModeId:             mode_id,
		}
		err := service.CreateDialysisPrescription(&prescription)

		if err != nil {
			this.ServeFailJsonSend(enums.ErrorCodeDataException, "添加设备失败")
			return
		}
		this.ServeSuccessJSON(map[string]interface{}{
			"msg": "保存成功",
		})
	} else if errcode == nil {
		prescription := models.DialysisPrescription{
			DialysisDialyszers: dialyzer_perfusion_apparatus,
			DialysisIrrigation: dialysis_irrigation,
			ModeId:             mode_id,
		}
		err := service.UpdateDialysisPrescriptionOne(prescription, patient_id, start_time, mode_id)
		if err != nil {
			this.ServeFailJsonSend(enums.ErrorCodeDataException, "添加设备失败")
			return
		}
		this.ServeSuccessJSON(map[string]interface{}{
			"msg": "保存成功",
		})
	}
}

func (this *StaffScheduleApiController) UpdateBloodScheduleMode() {
	id, _ := this.GetInt64("id")
	mode_id, _ := this.GetInt64("mode_id")
	schedule := models.XtSchedule{
		ModeId: mode_id,
	}
	service.UpdatedScheduleMode(schedule, id)
	this.ServeSuccessJSON(map[string]interface{}{
		"msg": "保存成功",
	})
}

func (this *StaffScheduleApiController) UpdateBloodSchedule() {

	patient_id, _ := this.GetInt64("patient_id")
	fmt.Println(patient_id)
	mode_id, _ := this.GetInt64("mode_id")
	schedule_type, _ := this.GetInt64("schedule_type")
	start_time, _ := this.GetInt64("start_time")
	bed_id, _ := this.GetInt64("bed_id")
	//更改排班
	schedule := models.XtSchedule{
		ScheduleType: schedule_type,
		ModeId:       mode_id,
	}

	//查询该床位该班次是否存在排班
	_, errschedulecode := service.GetPatientScheduleIsExist(start_time, schedule_type, bed_id)
	if errschedulecode == gorm.ErrRecordNotFound {
		service.UpdatedSchedule(schedule, patient_id, start_time, schedule_type, bed_id)
		this.ServeSuccessJSON(map[string]interface{}{
			"msgerr": "保存成功",
		})
	} else if errschedulecode == nil {
		this.ServeSuccessJSON(map[string]interface{}{
			"msg":    "1",
			"msgerr": "排班已存在",
		})
	}

}

func (this *StaffScheduleApiController) GetSchedulePatient() {

	schedule, _ := this.GetInt64("schedule", 0) //1已2未
	contagion, _ := this.GetInt64("contagion", 0)
	keywords := this.GetString("keywords", "")
	adminInfo := this.GetMobileAdminUserInfo()
	thisTime := time.Now()
	weekDay := int(thisTime.Weekday())
	if weekDay == 0 {
		weekDay = 7
	}
	thisWeekEnd := 7 - weekDay
	weekStartPoint := thisWeekEnd - 6
	weekStartDay := thisTime.AddDate(0, 0, weekStartPoint)
	weekEndPoint := thisWeekEnd + 7
	weekEndDay := thisTime.AddDate(0, 0, weekEndPoint)
	fmt.Println(weekStartPoint, weekStartDay, weekEndPoint, weekEndDay)

	weekStartTime := weekStartDay.Format("2006-01-02") + " 00:00:00"
	weekEndTime := weekEndDay.Format("2006-01-02") + " 23:59:59"
	fmt.Println(weekStartTime, weekEndTime)

	timeLayout := "2006-01-02 15:04:05"
	loc, _ := time.LoadLocation("Local")
	theStarTime, _ := time.ParseInLocation(timeLayout, weekStartTime, loc)
	theEndTime, _ := time.ParseInLocation(timeLayout, weekEndTime, loc)
	weekStart := theStarTime.Unix()
	weekEnd := theEndTime.Unix()

	patients, _ := service.GetPatientWithScheduleAndSolution(adminInfo.Org.Id, keywords, weekStart, weekEnd, schedule, contagion)

	this.ServeSuccessJSON(map[string]interface{}{
		"patients": patients,
	})
	return
}

func (c *StaffScheduleApiController) CreateMobileSchedulePatient() {

	patientID, _ := c.GetInt64("patient_id", 0)
	if patientID <= 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	adminUserInfo := c.GetMobileAdminUserInfo()
	patientInfo, _ := service.FindPatientById(adminUserInfo.Org.Id, patientID)
	if patientInfo.ID == 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
		return
	}

	var schedule models.Schedule
	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
	}

	if dataBody["schedule_date"] == nil || reflect.TypeOf(dataBody["schedule_date"]).String() != "string" {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	scheduleDate, _ := dataBody["schedule_date"].(string)
	if len(scheduleDate) == 0 {
		utils.ErrorLog("len(schedule_date) == 0")
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", scheduleDate+" 00:00:00", loc)
	if err != nil {
		utils.ErrorLog(err.Error())
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	schedule.ScheduleDate = theTime.Unix()

	timeNow := time.Now().Format("2006-01-02")
	if timeNow > scheduleDate {
		utils.ErrorLog(timeNow)
		utils.ErrorLog(scheduleDate)
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCantSetScheduleBeforeNow)
		return
	}

	if dataBody["schedule_type"] == nil || reflect.TypeOf(dataBody["schedule_type"]).String() != "float64" {
		utils.ErrorLog("schedule_type")
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	scheduleType := int64(dataBody["schedule_type"].(float64))
	if scheduleType < 1 || scheduleType > 3 {
		utils.ErrorLog("scheduleType < 3")
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	schedule.ScheduleType = scheduleType

	if dataBody["bed_id"] == nil || reflect.TypeOf(dataBody["bed_id"]).String() != "float64" {
		utils.ErrorLog("bed_id")
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	bedId := int64(dataBody["bed_id"].(float64))
	if bedId < 1 {
		utils.ErrorLog("bedId < 1")
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	schedule.BedId = bedId

	if dataBody["partition_id"] == nil || reflect.TypeOf(dataBody["partition_id"]).String() != "float64" {
		utils.ErrorLog("partition_id")
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	partitionId := int64(dataBody["partition_id"].(float64))
	if partitionId < 1 {
		utils.ErrorLog("partitionId < 1")
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	schedule.PartitionId = partitionId

	if dataBody["schedule_week"] == nil || reflect.TypeOf(dataBody["schedule_week"]).String() != "float64" {
		utils.ErrorLog("schedule_week")
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	scheduleWeek := int64(dataBody["schedule_week"].(float64))
	if scheduleWeek < 1 || scheduleWeek > 7 {
		utils.ErrorLog("scheduleWeek < 1")
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	schedule.ScheduleWeek = scheduleWeek

	if dataBody["mode_id"] == nil || reflect.TypeOf(dataBody["mode_id"]).String() != "float64" {
		utils.ErrorLog("mode_id")
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	modeId := int64(dataBody["mode_id"].(float64))
	if modeId < 1 && modeId > 14 {
		utils.ErrorLog("modeId < 1")
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	schedule.ModeId = modeId

	schedule.PatientId = patientID
	schedule.CreatedTime = time.Now().Unix()
	schedule.UpdatedTime = time.Now().Unix()
	schedule.Status = 1
	schedule.UserOrgId = adminUserInfo.Org.Id

	bed, _ := service.GetDeviceNumberByID(adminUserInfo.Org.Id, schedule.BedId)
	if bed == nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDeviceNumberNotExist)
		return
	}
	if bed.ZoneID != schedule.PartitionId {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDeviceNumberNotTheZone)
		return
	}

	scheduleDateStart := scheduleDate + " 00:00:00"
	scheduleDateEnd := scheduleDate + " 23:59:59"
	timeLayout = "2006-01-02 15:04:05"
	theStartTime, _ := time.ParseInLocation(timeLayout, scheduleDateStart, loc)
	theEndTime, _ := time.ParseInLocation(timeLayout, scheduleDateEnd, loc)
	startTime := theStartTime.Unix()
	endTime := theEndTime.Unix()

	//一天只有排班一次
	daySchedule, err := service.GetDaySchedule(adminUserInfo.Org.Id, startTime, endTime, patientID)
	if daySchedule.ID > 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCantSetScheduleAgainOneDay)
		return
	}

	//同天同位置只能排一个
	pointSchedule, err := service.GetPointSchedule(adminUserInfo.Org.Id, schedule.ScheduleDate, schedule.ScheduleWeek, schedule.ScheduleType, schedule.BedId)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}
	if pointSchedule.ID > 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePointScheduleExist)
		return
	}

	redis := service.RedisClient()
	err = service.CreateSchedule(&schedule)
	key := "scheduals_" + scheduleDate + "_" + strconv.FormatInt(adminUserInfo.Org.Id, 10)
	redis.Set(key, "", time.Second)
	defer redis.Close()
	fmt.Println(err)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreateScheduleFail)
		return
	}
	schedule.Patient = patientInfo.Name

	c.ServeSuccessJSON(map[string]interface{}{
		"msg":      "ok",
		"schedule": schedule,
	})
	return

}

func (c *StaffScheduleApiController) GetSolutionSchedule() {

	orgId := c.GetMobileAdminUserInfo().Org.Id
	scheduleDate := c.GetString("start_time")
	zoneid, _ := c.GetInt64("zoneid")
	classtype, _ := c.GetInt64("classtype")
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	theTime, _ := time.ParseInLocation(timeLayout+" 15:04:05", scheduleDate+" 00:00:00", loc)
	fmt.Println("时间错2332233323223", theTime.Unix())
	schedule, _ := service.GetSolutionScheduleBySchedule(orgId, zoneid, classtype, theTime.Unix())
	c.ServeSuccessJSON(map[string]interface{}{
		"schedule": schedule,
	})
}
