package controllers

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

	"github.com/astaxie/beego"
)

type ScheduleApiController struct {
	BaseAuthAPIController
}

func ScheduleApiRegistRouters() {
	beego.Router("/api/schedule/weekpanel", &ScheduleApiController{}, "Get:GetWeekPanels")

	beego.Router("/api/schedule/schedules", &ScheduleApiController{}, "Get:GetSchedules")
	beego.Router("/api/excel_date/init", &ScheduleApiController{}, "Get:GetInitExcelInitDate")

	beego.Router("/api/schedule/patients", &ScheduleApiController{}, "Get:GetPatients")
	beego.Router("/api/schedule/create", &ScheduleApiController{}, "Post:CreateSchedule")
	beego.Router("/api/schedule/delete", &ScheduleApiController{}, "Delete:DeleteSchedule")
	beego.Router("/api/schedule/change", &ScheduleApiController{}, "Put:ChangeSchedule")
	beego.Router("/api/schedule/urgentinit", &ScheduleApiController{}, "Get:UrgentScheduleData")
	beego.Router("/api/schedule/print/initdata", &ScheduleApiController{}, "get:PrintInitData")
	beego.Router("/api/schedule/search", &ScheduleApiController{}, "get:SearchSchedulePatients")
	beego.Router("/api/schedule/week", &ScheduleApiController{}, "get:GetWeekDaySchedule")
	beego.Router("/api/schedule/export", &ScheduleApiController{}, "post:ExportSchedule")
	beego.Router("/api/schedule_template/export", &ScheduleApiController{}, "post:ExportScheduleTemplate")

	beego.Router("/api/schedule_template/search", &ScheduleApiController{}, "get:SearchTemplateSchedulePatients")

	beego.Router("/api/schedule_template/cancel", &ScheduleApiController{}, "post:CancelScheduleTemplate")
	beego.Router("/api/schedule/getnextscheduleweekday", &ScheduleApiController{}, "Get:GetNextWeekDaySchedule")

	beego.Router("/api/schedule/getthreeweeklist", &ScheduleApiController{}, "Get:GetThreeWeekList")

	beego.Router("/api/schedule/getallzones", &ScheduleApiController{}, "Get:GetAllZones")

	beego.Router("/api/schedule/copypatientschedules", &ScheduleApiController{}, "Get:GetCopyPatientSchedules")

	beego.Router("/api/schedule/saveremindprint", &ScheduleApiController{}, "Get:SaveRemindPrint")

	beego.Router("/api/schedule/getremindprintlist", &ScheduleApiController{}, "Get:GetRemindPrintList")

	beego.Router("/api/schedule/getbloodschedulelist", &ScheduleApiController{}, "Get:GetBloodScheduleList")

	beego.Router("/api/schedule/getprintlist", &ScheduleApiController{}, "Get:GetPrintList")

	beego.Router("/api/schedule/getallzonelist", &ScheduleApiController{}, "Get:GetAllZoneList")

	beego.Router("/api/schedule/getpatientschedulecount", &ScheduleApiController{}, "Get:GetPatientScheduleCount")

	beego.Router("/api/schedule/weekpanelone", &ScheduleApiController{}, "Get:GetWeekPanelsOne")
	beego.Router("/api/schedule/schedulesone", &ScheduleApiController{}, "Get:GetScheduleOne")
	beego.Router("/api/schedule/postscheduletemplate", &ScheduleApiController{}, "Get:SaveScheduleTemplate")
	beego.Router("/api/schedule/getscheduletemplate", &ScheduleApiController{}, "Get:GetScheduleTemplate")
	beego.Router("/api/order/changefuncprint", &ScheduleApiController{}, "Get:ChangeFuncPrint")
	beego.Router("/api/order/getdataprint", &ScheduleApiController{}, "Get:GetDataPrint")
	beego.Router("/api/schedule/getnextweekpanels", &ScheduleApiController{}, "Get:GetNextWeekPanels")
	beego.Router("/api/schedule/synchroschedule", &ScheduleApiController{}, "Get:SynchroSchedule")
	beego.Router("/api/schedule/getpatientscheduletemplate", &ScheduleApiController{}, "Get:GetPatientScheduleTempalate")
	beego.Router("/api/schedule/getsolutionschedule", &ScheduleApiController{}, "Get:GetSolutionSchedule")
}

func (c *ScheduleApiController) GetWeekPanels() {

	data, _ := c.GetInt64("data", 1)
	patitionId, _ := c.GetInt64("patitionid")
	adminInfo := c.GetAdminUserInfo()
	thisTime := time.Now()
	year, monthTime, day := thisTime.Date()
	month := int(monthTime)
	_, theWeek := thisTime.ISOWeek()
	weekDay := int(thisTime.Weekday())
	if weekDay == 0 {
		weekDay = 7
	}
	weekEnd := 7 - weekDay
	weekStart := weekEnd - 6
	weekDays := make([]string, 0)
	for index := weekStart; index <= weekEnd; index++ {
		theDay := thisTime.AddDate(0, 0, index)
		indexYear, indexMonthTime, indexDay := theDay.Date()
		indexMonth := int(indexMonthTime)
		indexWeek := strconv.Itoa(indexYear) + "." + strconv.Itoa(indexMonth) + "." + strconv.Itoa(indexDay)
		weekDays = append(weekDays, indexWeek)
	}

	returnData := map[string]interface{}{
		"year":     year,
		"month":    month,
		"day":      day,
		"theWeek":  theWeek,
		"weekDay":  weekDay,
		"weekDays": weekDays,
	}

	if data == 1 {
		partitions, _ := service.GetSchedulePartitionPanelOne(adminInfo.CurrentOrgId, patitionId)
		returnData["partitions"] = partitions
	}

	c.ServeSuccessJSON(returnData)
	return
}

func (c *ScheduleApiController) GetSchedules() {
	week, _ := c.GetInt64("weekTime", 0) //1:last, 2:this 3:next 4 nextTwo
	partition_id, _ := c.GetInt64("partition_id")
	schedule_type, _ := c.GetInt64("schedule_type")

	adminInfo := c.GetAdminUserInfo()

	thisTime := time.Now()
	today := thisTime.Format("2006-01-02")
	if week < 1 || week > 4 {
		week = 2
	}
	if week == 1 {
		thisTime = thisTime.AddDate(0, 0, -7)
	} else if week == 3 {
		thisTime = thisTime.AddDate(0, 0, 7)
	} else if week == 4 {
		thisTime = thisTime.AddDate(0, 0, 14)
	}

	weekDay := int(thisTime.Weekday())
	if weekDay == 0 {
		weekDay = 7
	}
	weekEnd := 7 - weekDay
	weekStart := weekEnd - 6
	weekTitle := make([]string, 0)
	days := make([]string, 0)
	for index := weekStart; index <= weekEnd; index++ {
		theDay := thisTime.AddDate(0, 0, index)
		indexYear, indexMonthTime, indexDay := theDay.Date()
		indexMonth := int(indexMonthTime)
		indexWeek := strconv.Itoa(indexYear) + "." + strconv.Itoa(indexMonth) + "." + strconv.Itoa(indexDay)
		weekTitle = append(weekTitle, indexWeek)
		days = append(days, theDay.Format("2006-01-02"))
	}

	weekStartDay := thisTime.AddDate(0, 0, weekStart)
	weekEndDay := thisTime.AddDate(0, 0, weekEnd)
	weekStartTime := weekStartDay.Format("2006-01-02") + " 00:00:00"
	weekEndTime := weekEndDay.Format("2006-01-02") + " 23:59:59"

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

	schdules, _ := service.GetWeekScheduleOne(adminInfo.CurrentOrgId, weekStartPoint, weekEndPoint, partition_id, schedule_type)
	c.ServeSuccessJSON(map[string]interface{}{
		"days":      days,
		"weekTitle": weekTitle,
		"schdules":  schdules,
		"today":     today,
	})
	return
}

func (c *ScheduleApiController) GetPatients() {
	keywords := c.GetString("keywords", "")
	schedule, _ := c.GetInt64("schedule", 0) //1已2未
	contagion, _ := c.GetInt64("contagion", 0)

	adminInfo := c.GetAdminUserInfo()

	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.CurrentOrgId, keywords, weekStart, weekEnd, schedule, contagion)

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

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

	adminUserInfo := c.GetAdminUserInfo()
	patientInfo, _ := service.FindPatientById(adminUserInfo.CurrentOrgId, 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.CurrentOrgId

	bed, _ := service.GetDeviceNumberByID(adminUserInfo.CurrentOrgId, 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.CurrentOrgId, startTime, endTime, patientID)
	if daySchedule.ID > 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCantSetScheduleAgainOneDay)
		return
	}

	//同天同位置只能排一个
	pointSchedule, err := service.GetPointSchedule(adminUserInfo.CurrentOrgId, 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.CurrentOrgId, 10)

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

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

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

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

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

	keySeven := strconv.FormatInt(adminUserInfo.CurrentOrgId, 10) + ":" + strconv.FormatInt(schedule.ScheduleDate, 10) + ":dialysis_orders_list_all"
	redis.Set(keySeven, "", time.Second)
	fmt.Println(err)
	defer redis.Close()
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreateScheduleFail)
		return
	}
	schedule.Patient = patientInfo.Name

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

func (c *ScheduleApiController) DeleteSchedule() {
	id, _ := c.GetInt64("id", 0)
	if id <= 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	adminINfo := c.GetAdminUserInfo()

	schedule, _ := service.GetSchedule(adminINfo.CurrentOrgId, id)
	if schedule == nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeScheduleNotExist)
		return
	}

	order, err := service.GetOneDialysisOrder(adminINfo.CurrentOrgId, schedule.ScheduleDate, schedule.PatientId)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}

	if order != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDelScheduleFailByDialysis)
		return
	}

	schedule.Status = 0
	schedule.UpdatedTime = time.Now().Unix()
	err = service.UpdateSchedule(schedule)
	redis := service.RedisClient()

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

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

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

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

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

	keySeven := strconv.FormatInt(adminINfo.CurrentOrgId, 10) + ":" + strconv.FormatInt(schedule.ScheduleDate, 10) + ":dialysis_orders_list_all"
	redis.Set(keySeven, "", time.Second)
	fmt.Println(err)
	defer redis.Close()
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDeleteScheduleFail)
		return
	}

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

func (c *ScheduleApiController) ChangeSchedule() {
	id, _ := c.GetInt64("id", 0)
	if id <= 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	adminINfo := c.GetAdminUserInfo()

	schedule, _ := service.GetSchedule(adminINfo.CurrentOrgId, id)
	if schedule == nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeScheduleNotExist)
		return
	}

	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["change_action"] == nil || reflect.TypeOf(dataBody["change_action"]).String() != "string" {
		utils.ErrorLog("change_action")
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	changeAction := dataBody["change_action"].(string)

	if changeAction == "change_mode" {
		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 {
			utils.ErrorLog("modeId < 1")
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		schedule.ModeId = modeId

		order, err := service.GetOneDialysisOrder(adminINfo.CurrentOrgId, schedule.ScheduleDate, schedule.PatientId)
		if err != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}

		if order != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeChangeMode)
			return
		}

	} else if changeAction == "change_device" {

		order, err := service.GetOneDialysisOrder(adminINfo.CurrentOrgId, schedule.ScheduleDate, schedule.PatientId)
		if err != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}

		if order != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeChangeDeviceNumber)
			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

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

		startTime := schedule.ScheduleDate
		endTime := startTime + 86399

		//一天只有排班一次
		daySchedule, err := service.GetDaySchedule(adminINfo.CurrentOrgId, startTime, endTime, schedule.PatientId)
		if daySchedule.ID > 0 && daySchedule.ID != schedule.ID {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCantSetScheduleAgainOneDay)
			return
		}

		//同天同位置只能排一个
		pointSchedule, err := service.GetPointSchedule(adminINfo.CurrentOrgId, 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
		}
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	schedule.UpdatedTime = time.Now().Unix()
	err = service.UpdateSchedule(schedule)

	prescription := models.DialysisPrescription{
		ModeId: schedule.ModeId,
	}
	_, errcode := service.GetDialysisPrescribe(schedule.UserOrgId, schedule.PatientId, schedule.ScheduleDate)
	if errcode == gorm.ErrRecordNotFound {
		if err != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeChangeScheduleFail)
			return
		}
		c.ServeSuccessJSON(map[string]interface{}{
			"msg":      "ok",
			"schedule": &schedule,
		})
	} else if errcode == nil {
		err = service.UpdatedDialysisPrescription(&prescription, schedule.ScheduleDate, schedule.PatientId, schedule.UserOrgId)

		if err != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeChangeScheduleFail)
			return
		}
		c.ServeSuccessJSON(map[string]interface{}{
			"msg":      "ok",
			"schedule": &schedule,
		})
	}
}

// /api/schedule/print/initdata [get]
// @param date:string yyyy-MM-dd 要打印的那一周中的任一天
func (this *ScheduleApiController) PrintInitData() {
	dateStr := this.GetString("date")
	//week_type, _ := this.GetInt64("type", 0)
	var date *time.Time
	if len(dateStr) == 0 {
		now := time.Now()
		date = &now
	} else {
		var parseErr error
		date, parseErr = utils.ParseTimeStringToTime("2006-01-02", dateStr)
		if parseErr != nil {
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
	}

	adminUserInfo := this.GetAdminUserInfo()
	// 获取本周的排班
	var monday time.Time
	var sunday time.Time
	//switch week_type {
	//case 1:
	monday, sunday = utils.GetMondayAndSundayOfWeekDate(date)

	//	break
	//case 2:
	//	monday, sunday = utils.GetMondayAndSundayOfNextWeekDate(date)
	//
	//	break
	//case 3:
	//	monday, sunday = utils.GetMondayAndSundayOfNextNextWeekDate(date)
	//	break
	//}
	schedules, getScheduleErr := service.GetPrinitWeekSchedules(adminUserInfo.CurrentOrgId, monday.Unix(), sunday.Unix())
	total, getScheduleErr := service.GetPrinitWeekTotal(adminUserInfo.CurrentOrgId, monday.Unix(), sunday.Unix())
	if getScheduleErr != nil {
		this.ErrorLog("获取周排班失败:%v", getScheduleErr)
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}

	thisTime := date

	weekDay := int(thisTime.Weekday())
	if weekDay == 0 {
		weekDay = 7
	}
	weekEnd := 7 - weekDay
	weekStart := weekEnd - 6
	days := make([]string, 0)
	for index := weekStart; index <= weekEnd; index++ {
		theDay := thisTime.AddDate(0, 0, index)
		days = append(days, theDay.Format("2006-01-02"))
	}

	this.ServeSuccessJSON(map[string]interface{}{
		"total":     total,
		"schedules": schedules,
		"monday":    monday.Unix(),
		"days":      days,
	})
}

func (this *ScheduleApiController) UrgentScheduleData() {
	schedule_type, _ := this.GetInt("type", 0)
	schedule_date := this.GetString("date")
	var date *time.Time
	if len(schedule_date) == 0 {
		now := time.Now()
		date = &now
	} else {
		var parseErr error
		date, parseErr = utils.ParseTimeStringToTime("2006-01-02", schedule_date)
		if parseErr != nil {
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
	}

	adminUserInfo := this.GetAdminUserInfo()
	deviceNumbers, getDeviceNumbersErr := service.MobileGetAllDeviceNumbersForUrgentSchedule(adminUserInfo.CurrentOrgId, date.Unix(), schedule_type)
	if getDeviceNumbersErr != nil {
		this.ErrorLog("获取所有床位失败:%v", getDeviceNumbersErr)
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}
	// today := utils.ZeroHourTimeOfDay(time.Now())
	schedules, getSchedulesErr := service.MobileGetOtherSchedulesForUrgentSchedule(adminUserInfo.CurrentOrgId, date.Unix(), schedule_type)
	if getSchedulesErr != nil {
		this.ErrorLog("获取所有排班失败:%v", getSchedulesErr)
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"device_numbers": deviceNumbers,
		"schedules":      schedules,
	})
}

func (this *ScheduleApiController) SearchSchedulePatients() {
	keywords := this.GetString("keywords")
	week_type, _ := this.GetInt64("week_type", 0)

	thisTime1 := time.Now()
	thisTime2 := time.Now()

	thisTime1 = thisTime1.AddDate(0, 0, 7)
	thisTime2 = thisTime2.AddDate(0, 0, 14)

	var start_time string
	var end_time string

	switch week_type {
	case 1:

		adminUserInfo := this.GetAdminUserInfo()
		list, _ := service.GetSchedualPatientsByKeywords(keywords, adminUserInfo.CurrentOrgId)
		this.ServeSuccessJSON(map[string]interface{}{
			"schdules": list,
		})

		break
	case 2:
		days := make([]string, 0)

		weekDay1 := int(thisTime1.Weekday())
		if weekDay1 == 0 {
			weekDay1 = 7
		}
		weekEnd1 := 7 - weekDay1
		weekStart1 := weekEnd1 - 6
		for index := weekStart1; index <= weekEnd1; index++ {
			fmt.Println(index)
			theDay := thisTime1.AddDate(0, 0, index)
			days = append(days, theDay.Format("2006-01-02"))

		}

		fmt.Println(days)

		start_time = days[0]
		end_time = days[len(days)-1]

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

		var theStartTime int64
		if len(start_time) > 0 {
			theTime, _ := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
			theStartTime = theTime.Unix()
		}
		var theEndtTime int64
		if len(end_time) > 0 {
			theTime, _ := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
			theEndtTime = theTime.Unix()
		}

		adminUserInfo := this.GetAdminUserInfo()
		list, _ := service.GetSchedualPatientsByKeywordsAndWeek(keywords, adminUserInfo.CurrentOrgId, theStartTime, theEndtTime)
		this.ServeSuccessJSON(map[string]interface{}{
			"schdules": list,
		})

		break
	case 3:
		days := make([]string, 0)

		weekDay2 := int(thisTime2.Weekday())
		if weekDay2 == 0 {
			weekDay2 = 7
		}
		weekEnd2 := 7 - weekDay2
		weekStart2 := weekEnd2 - 6
		for index := weekStart2; index <= weekEnd2; index++ {
			theDay := thisTime2.AddDate(0, 0, index)
			days = append(days, theDay.Format("2006-01-02"))

		}

		start_time = days[0]
		end_time = days[len(days)-1]

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

		var theStartTime int64
		if len(start_time) > 0 {
			theTime, _ := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
			theStartTime = theTime.Unix()
		}
		var theEndtTime int64
		if len(end_time) > 0 {
			theTime, _ := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
			theEndtTime = theTime.Unix()
		}

		adminUserInfo := this.GetAdminUserInfo()
		list, _ := service.GetSchedualPatientsByKeywordsAndWeek(keywords, adminUserInfo.CurrentOrgId, theStartTime, theEndtTime)
		this.ServeSuccessJSON(map[string]interface{}{
			"schdules": list,
		})

		break
	}

}

func (this *ScheduleApiController) GetWeekDaySchedule() {
	week_type, _ := this.GetInt64("week_type", -1)
	week_time, _ := this.GetInt64("week_time")

	thisTime := time.Now()
	weekDay := int(thisTime.Weekday())
	if weekDay == 0 {
		weekDay = 7
	}
	weekEnd := 7 - weekDay
	weekStart := weekEnd - 6
	weekTitle := make([]string, 0)
	days := make([]string, 0)
	for index := weekStart; index <= weekEnd; index++ {
		theDay := thisTime.AddDate(0, 0, index)
		indexYear, indexMonthTime, indexDay := theDay.Date()
		indexMonth := int(indexMonthTime)
		indexWeek := strconv.Itoa(indexYear) + "." + strconv.Itoa(indexMonth) + "." + strconv.Itoa(indexDay)
		weekTitle = append(weekTitle, indexWeek)
		days = append(days, theDay.Format("2006-01-02"))
	}
	fmt.Println(days)

	var targetDayStr string
	var startTime string
	var endTime string
	switch week_type {
	case 0:
		{
			startTime = days[0]
			endTime = days[6]
		}
	case 1:
		targetDayStr = days[0]
		break
	case 2:
		targetDayStr = days[1]

		break
	case 3:
		targetDayStr = days[2]

		break
	case 4:
		targetDayStr = days[3]

		break
	case 5:
		targetDayStr = days[4]

		break
	case 6:
		targetDayStr = days[5]

		break
	case 7:
		targetDayStr = days[6]

		break
	}
	targetDay, parseErr := utils.ParseTimeStringToTime("2006-01-02", targetDayStr)
	startDay, _ := utils.ParseTimeStringToTime("2006-01-02", startTime)
	endDay, _ := utils.ParseTimeStringToTime("2006-01-02", endTime)
	fmt.Println(startDay, endDay)
	if parseErr != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	orgId := this.GetAdminUserInfo().CurrentOrgId

	list, _ := service.GetWeekDayScheduleTwo(orgId, targetDay.Unix(), targetDay, week_time)

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

}

func Struct2Map(obj interface{}) map[string]interface{} {
	t := reflect.TypeOf(obj)
	v := reflect.ValueOf(obj)

	var data = make(map[string]interface{})
	for i := 0; i < t.NumField(); i++ {
		data[t.Field(i).Name] = v.Field(i).Interface()
	}
	return data
}

func (this *ScheduleApiController) ExportSchedule() {

	dataBody := make(map[string]interface{}, 0)
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &dataBody)
	if err != nil {
		utils.ErrorLog(err.Error())
		return
	}
	utils.ErrorLog("%v", dataBody)
	export_time := time.Now().Unix()
	var schedules []*models.Schedule
	var failed_total int
	var total_schedule []interface{}
	var patients []*models.Patients

	patients, _, _ = service.GetAllPatientList(this.GetAdminUserInfo().CurrentOrgId)

	start_time := dataBody["start_time"].(string)

	end_time := dataBody["end_time"].(string)

	delete_type := int64(dataBody["delete_type"].(float64))
	fmt.Println("delete_type", delete_type)
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	theTimeStart, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
	theTimeEnd, err := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 00:00:00", loc)

	fmt.Println("theTimeStart23232322332322323", theTimeStart.Unix())
	fmt.Println("theTimeStart23232322332322323", theTimeEnd.Unix())

	if dataBody["failed_schedule"] != nil || reflect.TypeOf(dataBody["failed_schedule"]).String() == "[]interface {}" {
		tempSchedule := dataBody["failed_schedule"].([]interface{})
		failed_total = len(tempSchedule)

	}

	if dataBody["schedule"] != nil || reflect.TypeOf(dataBody["schedule"]).String() == "[]interface {}" {
		tempSchedule := dataBody["schedule"].([]interface{})
		total_schedule = tempSchedule
		for _, schMap := range tempSchedule {
			schMapM := schMap.(map[string]interface{})
			var sch models.Schedule

			if schMapM["name"] == nil || reflect.TypeOf(schMapM["name"]).String() != "string" {
				utils.ErrorLog("name")
				return
			}

			name, _ := schMapM["name"].(string)
			fmt.Println(name)
			if len(name) == 0 { //名字为空则生成一条导入错误日志
				err_log := models.ExportErrLog{
					LogType:    2,
					UserOrgId:  this.GetAdminUserInfo().CurrentOrgId,
					ErrMsg:     "第" + strconv.FormatInt(int64(schMapM["index"].(float64)), 10) + "行,第" + schMapM["row"].(string) + "列的姓名不能为空",
					Status:     1,
					CreateTime: time.Now().Unix(),
					UpdateTime: time.Now().Unix(),
					ExportTime: export_time,
				}
				service.CreateExportErrLog(&err_log)
				continue

			} else {
				var patient []*models.Patients
				for _, item := range patients {
					if strings.Replace(item.Name, " ", "", -1) == name {
						patient = append(patient, item)
					}
				}
				if len(patient) == 0 { //错误日志
					err_log := models.ExportErrLog{
						LogType:    2,
						UserOrgId:  this.GetAdminUserInfo().CurrentOrgId,
						ErrMsg:     "第" + strconv.FormatInt(int64(schMapM["index"].(float64)), 10) + "行,第" + schMapM["row"].(string) + "列,患者姓名为\"" + name + "\"在系统中不存在,请在系统中添加该患者",
						Status:     1,
						CreateTime: time.Now().Unix(),
						UpdateTime: time.Now().Unix(),
						ExportTime: export_time,
					}
					service.CreateExportErrLog(&err_log)
					continue

				} else if len(patient) == 1 { //
					sch.PatientId = patient[0].ID

				} else if len(patient) > 1 { //出现同名的情况

					err_log := models.ExportErrLog{
						LogType:   2,
						UserOrgId: this.GetAdminUserInfo().CurrentOrgId,
						//ErrMsg:     "第" + strconv.FormatInt(int64(schMapM["index"].(float64)), 10) + "行,第" + schMapM["row"].(string) + "列" + "患者姓名为" + name + "在当前机构中存在重名,无法确定到具体患者",

						ErrMsg: "第" + strconv.FormatInt(int64(schMapM["index"].(float64)), 10) + "行,第" + schMapM["row"].(string) + "列,患者姓名为\"" + name + "\"在在当前机构中存在重名,无法确定到具体患者",

						Status:     1,
						CreateTime: time.Now().Unix(),
						UpdateTime: time.Now().Unix(),
						ExportTime: export_time,
					}
					service.CreateExportErrLog(&err_log)
					continue

				}
			}

			if schMapM["schedule_type"] == nil && reflect.TypeOf(schMapM["schedule_type"]).String() != "float64" {
				utils.ErrorLog("schedule_type")
				return
			}
			schedule_type := int64(schMapM["schedule_type"].(float64))
			if schedule_type <= 0 { //班次格式有误,插入日志

				log := models.ExportLog{
					LogType:    2,
					UserOrgId:  this.GetAdminUserInfo().CurrentOrgId,
					TotalNum:   int64(len(total_schedule) + failed_total),
					FailNum:    1 + int64(failed_total),
					SuccessNum: int64(len(schedules)),
					CreateTime: time.Now().Unix(),
					UpdateTime: time.Now().Unix(),
					ExportTime: export_time,
					Status:     1,
				}
				service.CreateExportLog(&log)

				err_log := models.ExportErrLog{
					LogType:    2,
					UserOrgId:  this.GetAdminUserInfo().CurrentOrgId,
					ErrMsg:     "第2行第" + schMapM["row"].(string) + "列的班次格式有误",
					Status:     1,
					CreateTime: time.Now().Unix(),
					UpdateTime: time.Now().Unix(),
					ExportTime: export_time,
				}
				service.CreateExportErrLog(&err_log)
				this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeExportError)
				return

			} else {
				sch.ScheduleType = schedule_type
			}

			if schMapM["partition_name"] == nil || reflect.TypeOf(schMapM["partition_name"]).String() != "string" {
				utils.ErrorLog("partition_name")
				return
			}

			partition_name, _ := schMapM["partition_name"].(string)
			if len(partition_name) == 0 { //分区为空
				log := models.ExportLog{
					LogType:    2,
					UserOrgId:  this.GetAdminUserInfo().CurrentOrgId,
					TotalNum:   int64(len(total_schedule) + failed_total),
					FailNum:    1 + int64(failed_total),
					SuccessNum: int64(len(schedules)),
					CreateTime: time.Now().Unix(),
					UpdateTime: time.Now().Unix(),
					ExportTime: export_time,
					Status:     1,
				}
				service.CreateExportLog(&log)

				err_log := models.ExportErrLog{
					LogType:   2,
					UserOrgId: this.GetAdminUserInfo().CurrentOrgId,
					//ErrMsg:     "第" + 	strconv.FormatInt(int64(schMapM["index"].(float64)) ,10)+ "行" + "的姓名不能为空",
					ErrMsg:     "第" + strconv.FormatInt(int64(schMapM["index"].(float64)), 10) + "行第1列所属的分区格式有误",
					Status:     1,
					CreateTime: time.Now().Unix(),
					UpdateTime: time.Now().Unix(),
					ExportTime: export_time,
				}
				service.CreateExportErrLog(&err_log)
				this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeExportError)
				return

			} else {
				zone, err := service.FindDeviceZoneByName(partition_name, this.GetAdminUserInfo().CurrentOrgId)
				if err == nil {
					sch.PartitionId = zone.ID
				} else if err == gorm.ErrRecordNotFound { //查不到数据,插入错误日志

					log := models.ExportLog{
						LogType:    2,
						UserOrgId:  this.GetAdminUserInfo().CurrentOrgId,
						TotalNum:   int64(len(total_schedule) + failed_total),
						FailNum:    1 + int64(failed_total),
						SuccessNum: int64(len(schedules)),
						CreateTime: time.Now().Unix(),
						UpdateTime: time.Now().Unix(),
						ExportTime: export_time,
						Status:     1,
					}
					service.CreateExportLog(&log)

					err_log := models.ExportErrLog{
						LogType:   2,
						UserOrgId: this.GetAdminUserInfo().CurrentOrgId,
						//ErrMsg:     "第" + 	strconv.FormatInt(int64(schMapM["index"].(float64)) ,10)+ "行" + "的姓名不能为空",
						ErrMsg:     "第" + strconv.FormatInt(int64(schMapM["index"].(float64)), 10) + "行第1列所属的分区格式有误",
						Status:     1,
						CreateTime: time.Now().Unix(),
						UpdateTime: time.Now().Unix(),
						ExportTime: export_time,
					}
					service.CreateExportErrLog(&err_log)
					this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeExportError)
					return

				}

			}

			if schMapM["device_number_name"] == nil || reflect.TypeOf(schMapM["device_number_name"]).String() != "string" {
				utils.ErrorLog("device_number_name")
				return
			}

			device_number_name, _ := schMapM["device_number_name"].(string)
			if len(device_number_name) == 0 { //分区为空

				log := models.ExportLog{
					LogType:    2,
					UserOrgId:  this.GetAdminUserInfo().CurrentOrgId,
					TotalNum:   int64(len(total_schedule) + failed_total),
					FailNum:    1 + int64(failed_total),
					SuccessNum: int64(len(schedules)),
					CreateTime: time.Now().Unix(),
					UpdateTime: time.Now().Unix(),
					ExportTime: export_time,
					Status:     1,
				}
				service.CreateExportLog(&log)

				err_log := models.ExportErrLog{
					LogType:   2,
					UserOrgId: this.GetAdminUserInfo().CurrentOrgId,
					//ErrMsg:     "第" + 	strconv.FormatInt(int64(schMapM["index"].(float64)) ,10)+ "行" + "的姓名不能为空",
					ErrMsg: "第" + strconv.FormatInt(int64(schMapM["index"].(float64)), 10) + "行第2列机号格式有误",

					Status:     1,
					CreateTime: time.Now().Unix(),
					UpdateTime: time.Now().Unix(),
					ExportTime: export_time,
				}
				service.CreateExportErrLog(&err_log)
				this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeExportError)
				return

			} else {
				device, err := service.FindDeviceByName(device_number_name, this.GetAdminUserInfo().CurrentOrgId, sch.PartitionId)
				if err == nil {
					if len(device) == 0 { //没查到数据,插入错误日志

						log := models.ExportLog{
							LogType:    2,
							UserOrgId:  this.GetAdminUserInfo().CurrentOrgId,
							TotalNum:   int64(len(total_schedule) + failed_total),
							FailNum:    1 + int64(failed_total),
							SuccessNum: int64(len(schedules)),
							CreateTime: time.Now().Unix(),
							UpdateTime: time.Now().Unix(),
							ExportTime: export_time,
							Status:     1,
						}
						service.CreateExportLog(&log)

						err_log := models.ExportErrLog{
							LogType:    2,
							UserOrgId:  this.GetAdminUserInfo().CurrentOrgId,
							ErrMsg:     "第" + strconv.FormatInt(int64(schMapM["index"].(float64)), 10) + "行第2列机号格式有误",
							Status:     1,
							CreateTime: time.Now().Unix(),
							UpdateTime: time.Now().Unix(),
							ExportTime: export_time,
						}
						service.CreateExportErrLog(&err_log)
						this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeExportError)
						return

					} else if len(device) == 1 {
						sch.BedId = device[0].ID

					} else if len(device) > 1 { //出现重名,插入错误日志

						log := models.ExportLog{
							LogType:    2,
							UserOrgId:  this.GetAdminUserInfo().CurrentOrgId,
							TotalNum:   int64(len(total_schedule) + failed_total),
							FailNum:    1 + int64(failed_total),
							SuccessNum: int64(len(schedules)),
							CreateTime: time.Now().Unix(),
							UpdateTime: time.Now().Unix(),
							ExportTime: export_time,
							Status:     1,
						}
						service.CreateExportLog(&log)

						err_log := models.ExportErrLog{
							LogType:    2,
							UserOrgId:  this.GetAdminUserInfo().CurrentOrgId,
							ErrMsg:     "出现两个床位号相同的床位",
							Status:     1,
							CreateTime: time.Now().Unix(),
							UpdateTime: time.Now().Unix(),
							ExportTime: export_time,
						}
						service.CreateExportErrLog(&err_log)
						this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeExportError)
						return

					}
				}
			}

			if schMapM["schedule_week"] == nil || reflect.TypeOf(schMapM["schedule_week"]).String() != "string" {
				utils.ErrorLog("schedule_week")
				return
			}
			schedule_week, _ := schMapM["schedule_week"].(string)
			if len(schedule_week) == 0 { //周几为空则生成一条导入错误日志

				log := models.ExportLog{
					LogType:    2,
					UserOrgId:  this.GetAdminUserInfo().CurrentOrgId,
					TotalNum:   int64(len(total_schedule) + failed_total),
					FailNum:    1 + int64(failed_total),
					SuccessNum: int64(len(schedules)),
					CreateTime: time.Now().Unix(),
					UpdateTime: time.Now().Unix(),
					ExportTime: export_time,
					Status:     1,
				}
				service.CreateExportLog(&log)

				err_log := models.ExportErrLog{
					LogType:   2,
					UserOrgId: this.GetAdminUserInfo().CurrentOrgId,
					//ErrMsg:     "第" + 	strconv.FormatInt(int64(schMapM["index"].(float64)) ,10)+ "行" + "的姓名不能为空",
					ErrMsg: "第1行第" + schMapM["row"].(string) + "列的星期名格式有误",

					Status:     1,
					CreateTime: time.Now().Unix(),
					UpdateTime: time.Now().Unix(),
					ExportTime: export_time,
				}
				service.CreateExportErrLog(&err_log)
				this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeExportError)
				return

			} else if schedule_week == "0" { //周几不符合格式则生成一条导入错误日志

				log := models.ExportLog{
					LogType:    2,
					UserOrgId:  this.GetAdminUserInfo().CurrentOrgId,
					TotalNum:   int64(len(total_schedule) + failed_total),
					FailNum:    1 + int64(failed_total),
					SuccessNum: int64(len(schedules)),
					CreateTime: time.Now().Unix(),
					UpdateTime: time.Now().Unix(),
					ExportTime: export_time,
					Status:     1,
				}
				service.CreateExportLog(&log)

				err_log := models.ExportErrLog{
					LogType:    2,
					UserOrgId:  this.GetAdminUserInfo().CurrentOrgId,
					ErrMsg:     "第1行第" + schMapM["row"].(string) + "列的星期名格式有误",
					Status:     1,
					CreateTime: time.Now().Unix(),
					UpdateTime: time.Now().Unix(),
					ExportTime: export_time,
				}
				service.CreateExportErrLog(&err_log)
				this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeExportError)
				return

			} else {
				schedule_week, _ := strconv.ParseInt(schedule_week, 10, 64)
				sch.ScheduleWeek = schedule_week

			}

			if schMapM["schedule_date"] == nil || reflect.TypeOf(schMapM["schedule_date"]).String() != "string" {
				utils.ErrorLog("schedule_date")
				return
			}
			schedule_date, _ := schMapM["schedule_date"].(string)

			if len(schedule_date) == 0 { //周几为空则生成一条导入错误日志

				log := models.ExportLog{
					LogType:    2,
					UserOrgId:  this.GetAdminUserInfo().CurrentOrgId,
					TotalNum:   int64(len(total_schedule) + failed_total),
					FailNum:    1 + int64(failed_total),
					SuccessNum: int64(len(schedules)),
					CreateTime: time.Now().Unix(),
					UpdateTime: time.Now().Unix(),
					ExportTime: export_time,
					Status:     1,
				}
				service.CreateExportLog(&log)

				err_log := models.ExportErrLog{
					LogType:    2,
					UserOrgId:  this.GetAdminUserInfo().CurrentOrgId,
					ErrMsg:     "第1行第" + schMapM["row"].(string) + "列的星期名格式有误",
					Status:     1,
					CreateTime: time.Now().Unix(),
					UpdateTime: time.Now().Unix(),
					ExportTime: export_time,
				}
				service.CreateExportErrLog(&err_log)
				this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeExportError)
				return

			} else if schedule_date == "0" { //周几不符合格式则生成一条导入错误日志

				log := models.ExportLog{
					LogType:    2,
					UserOrgId:  this.GetAdminUserInfo().CurrentOrgId,
					TotalNum:   int64(len(total_schedule) + failed_total),
					FailNum:    1 + int64(failed_total),
					SuccessNum: int64(len(schedules)),
					CreateTime: time.Now().Unix(),
					UpdateTime: time.Now().Unix(),
					ExportTime: export_time,
					Status:     1,
				}
				service.CreateExportLog(&log)

				err_log := models.ExportErrLog{
					LogType:    2,
					UserOrgId:  this.GetAdminUserInfo().CurrentOrgId,
					ErrMsg:     "第1行第" + schMapM["row"].(string) + "列的星期名格式有误",
					Status:     1,
					CreateTime: time.Now().Unix(),
					UpdateTime: time.Now().Unix(),
					ExportTime: export_time,
				}
				service.CreateExportErrLog(&err_log)
				this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeExportError)
				return

			} else {
				date, _ := utils.ParseTimeStringToTime("2006-01-02", schedule_date)
				sch.ScheduleDate = date.Unix()
			}

			sch.CreatedTime = time.Now().Unix()
			sch.UpdatedTime = time.Now().Unix()
			sch.ModeId = 1
			sch.Status = 1
			sch.UserOrgId = this.GetAdminUserInfo().CurrentOrgId
			sch.IsExport = 1
			schedules = append(schedules, &sch)
		}

		errLogs, _ := service.FindSchedualExportLog(this.GetAdminUserInfo().CurrentOrgId, export_time)

		if len(schedules) > 0 {
			schedule_date := time.Now().Format("2006-01-02")
			date, _ := utils.ParseTimeStringToTime("2006-01-02", schedule_date)
			clear_schedule_date := date.Unix() //根据日期去清除,该日期未来的排班数据
			//	err := service.UpdateScheduleStatus(clear_schedule_date, this.GetAdminUserInfo().CurrentOrgId)
			if err == nil {
				//清除该机构的排班
				//if delete_type == 1 {
				//  service.ModeScheduleByTimeOne(theTimeStart.Unix(), theTimeEnd.Unix(), this.GetAdminUserInfo().CurrentOrgId)
				//}
				//if delete_type == 0 {
				//  service.ModeScheduleByTime(theTimeStart.Unix(), theTimeEnd.Unix(), this.GetAdminUserInfo().CurrentOrgId)
				//}

				for _, item := range schedules {
					// fmt.Println("clear_schedule_date3232232332232332232323",clear_schedule_date)
					if item.ScheduleDate > clear_schedule_date {
						//删除当天的以后日期排班
						// service.DeleteScheduleExist(item.ScheduleDate, item.UserOrgId)
						//查找当天日期是否存在
						_, errcode := service.GetTodayScheduleIsExistOne(item.PatientId, item.ScheduleDate, item.UserOrgId)
						if errcode == gorm.ErrRecordNotFound {

							//清除当天该床位已有的患者
							service.ModeFyScheduleById(item.ScheduleDate, item.BedId, item.ScheduleType)
							service.CreateSchedule(item)
						} else if errcode == nil {
							schedule := models.XtSchedule{
								PartitionId:  item.PartitionId,
								BedId:        item.BedId,
								PatientId:    item.PatientId,
								ScheduleDate: item.ScheduleDate,
								ScheduleType: item.ScheduleType,
								ScheduleWeek: item.ScheduleWeek,
								ModeId:       item.ModeId,
								Status:       1,
							}

							service.UpdateScheduleByOrgIdOne(item.PatientId, item.ScheduleDate, item.UserOrgId, &schedule)
						}
					}
				}

				log := models.ExportLog{
					LogType:    2,
					UserOrgId:  this.GetAdminUserInfo().CurrentOrgId,
					TotalNum:   int64(len(total_schedule) + failed_total),
					FailNum:    int64(len(errLogs) + failed_total),
					SuccessNum: int64(len(schedules)),
					CreateTime: time.Now().Unix(),
					UpdateTime: time.Now().Unix(),
					ExportTime: export_time,
					Status:     1,
				}
				service.CreateExportLog(&log)

				if failed_total > 0 {
					err_log := models.ExportErrLog{
						LogType:   2,
						UserOrgId: this.GetAdminUserInfo().CurrentOrgId,
						ErrMsg: "当前日期(" + time.Now().Format("2006-01-02") + " " + GetWeekString(time.Now().Weekday().String()) +
							")及以前的排班数据" + strconv.FormatInt(int64(failed_total), 10) + "条,不执行导入",
						Status:     1,
						CreateTime: time.Now().Unix(),
						UpdateTime: time.Now().Unix(),
						ExportTime: export_time,
					}
					service.CreateExportErrLog(&err_log)
				}

				this.ServeSuccessJSON(map[string]interface{}{
					"msg":         "导入成功",
					"total_num":   len(total_schedule) + failed_total,
					"success_num": len(schedules),
					"fail_num":    int64(len(errLogs)),
				})
			} else {
				log := models.ExportLog{
					LogType:    2,
					UserOrgId:  this.GetAdminUserInfo().CurrentOrgId,
					TotalNum:   int64(len(total_schedule) + failed_total),
					FailNum:    int64(len(errLogs) + failed_total),
					SuccessNum: int64(len(schedules)),
					CreateTime: time.Now().Unix(),
					UpdateTime: time.Now().Unix(),
					ExportTime: export_time,
					Status:     1,
				}
				service.CreateExportLog(&log)

				if failed_total > 0 {
					err_log := models.ExportErrLog{
						LogType:   2,
						UserOrgId: this.GetAdminUserInfo().CurrentOrgId,
						ErrMsg: "当前日期(" + time.Now().Format("2006-01-02") + " " + GetWeekString(time.Now().Weekday().String()) +
							")及以前的排班数据" + strconv.FormatInt(int64(failed_total), 10) + "条,不执行导入",
						Status:     1,
						CreateTime: time.Now().Unix(),
						UpdateTime: time.Now().Unix(),
						ExportTime: export_time,
					}
					service.CreateExportErrLog(&err_log)
				}

				this.ServeSuccessJSON(map[string]interface{}{
					"msg":         "导入成功",
					"total_num":   len(total_schedule),
					"success_num": len(schedules),
					"fail_num":    int64(len(errLogs)),
				})
			}
		} else {
			log := models.ExportLog{
				LogType:    2,
				UserOrgId:  this.GetAdminUserInfo().CurrentOrgId,
				TotalNum:   int64(len(total_schedule) + failed_total),
				FailNum:    int64(len(errLogs) + failed_total),
				SuccessNum: int64(len(schedules)),
				CreateTime: time.Now().Unix(),
				UpdateTime: time.Now().Unix(),
				ExportTime: export_time,
				Status:     1,
			}
			service.CreateExportLog(&log)

			if failed_total > 0 {
				err_log := models.ExportErrLog{
					LogType:   2,
					UserOrgId: this.GetAdminUserInfo().CurrentOrgId,
					ErrMsg: "当前日期(" + time.Now().Format("2006-01-02") + " " + GetWeekString(time.Now().Weekday().String()) +
						")及以前的排班数据" + strconv.FormatInt(int64(failed_total), 10) + "条,不执行导入",
					Status:     1,
					CreateTime: time.Now().Unix(),
					UpdateTime: time.Now().Unix(),
					ExportTime: export_time,
				}
				service.CreateExportErrLog(&err_log)
			}

			this.ServeSuccessJSON(map[string]interface{}{
				"msg":         "导入成功",
				"total_num":   len(total_schedule),
				"success_num": len(schedules),
				"fail_num":    int64(len(errLogs)),
			})
		}
	}

}

func (this *ScheduleApiController) ExportScheduleTemplate() {
	dataBody := make(map[string]interface{}, 0)
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &dataBody)
	if err != nil {
		utils.ErrorLog(err.Error())
		return
	}
	utils.ErrorLog("%v", dataBody)
	export_time := time.Now().Unix()
	var schedules []*models.PatientScheduleTemplateItem
	var total_schedule []interface{}

	patients, _, _ := service.GetAllPatientList(this.GetAdminUserInfo().CurrentOrgId)

	if dataBody["schedule"] != nil || reflect.TypeOf(dataBody["schedule"]).String() == "[]interface {}" {
		tempSchedule := dataBody["schedule"].([]interface{})
		total_schedule = tempSchedule
		for _, schMap := range tempSchedule {
			schMapM := schMap.(map[string]interface{})
			var sch models.PatientScheduleTemplateItem

			if schMapM["name"] == nil || reflect.TypeOf(schMapM["name"]).String() != "string" {
				utils.ErrorLog("name")
				return
			}

			name, _ := schMapM["name"].(string)
			fmt.Println(name)
			if len(name) == 0 { //名字为空则生成一条导入错误日志
				err_log := models.ExportErrLog{
					LogType:    3,
					UserOrgId:  this.GetAdminUserInfo().CurrentOrgId,
					ErrMsg:     "第" + strconv.FormatInt(int64(schMapM["index"].(float64)), 10) + "行,第" + schMapM["row"].(string) + "列的姓名不能为空",
					Status:     1,
					CreateTime: time.Now().Unix(),
					UpdateTime: time.Now().Unix(),
					ExportTime: export_time,
				}
				service.CreateExportErrLog(&err_log)
				continue

			} else {
				var patient []*models.Patients
				for _, item := range patients {
					if strings.Replace(item.Name, " ", "", -1) == name {
						patient = append(patient, item)
					}
				}
				if len(patient) == 0 { //错误日志
					err_log := models.ExportErrLog{
						LogType:   3,
						UserOrgId: this.GetAdminUserInfo().CurrentOrgId,
						//ErrMsg:     "第" + strconv.FormatInt(int64(schMapM["index"].(float64)), 10) + "行,第" + schMapM["row"].(string) + "列的姓名在系统中不存在,请在系统中添加该病人",
						ErrMsg: "第" + strconv.FormatInt(int64(schMapM["index"].(float64)), 10) + "行,第" + schMapM["row"].(string) + "列患者姓名为\"" + name + "\"在系统中不存在,请在系统中添加该患者",

						Status:     1,
						CreateTime: time.Now().Unix(),
						UpdateTime: time.Now().Unix(),
						ExportTime: export_time,
					}
					service.CreateExportErrLog(&err_log)
					continue

				} else if len(patient) == 1 { //
					sch.PatientID = patient[0].ID

				} else if len(patient) > 1 { //出现同名的情况

					err_log := models.ExportErrLog{
						LogType:   3,
						UserOrgId: this.GetAdminUserInfo().CurrentOrgId,
						//ErrMsg:     "第" + strconv.FormatInt(int64(schMapM["index"].(float64)), 10) + "行,第" + schMapM["row"].(string) + "列" + "患者姓名为" + name + "在当前机构中存在重名,无法确定到具体患者",
						ErrMsg: "第" + strconv.FormatInt(int64(schMapM["index"].(float64)), 10) + "行,第" + schMapM["row"].(string) + "列患者姓名为\"" + name + "\"在当前机构中存在重名,无法确定到具体患者",

						Status:     1,
						CreateTime: time.Now().Unix(),
						UpdateTime: time.Now().Unix(),
						ExportTime: export_time,
					}
					service.CreateExportErrLog(&err_log)
					continue

				}
			}

			if schMapM["schedule_type"] == nil && reflect.TypeOf(schMapM["schedule_type"]).String() != "float64" {
				utils.ErrorLog("schedule_type")
				return
			}
			schedule_type := int64(schMapM["schedule_type"].(float64))
			if schedule_type <= 0 { //班次格式有误,插入日志
				log := models.ExportLog{
					LogType:    3,
					UserOrgId:  this.GetAdminUserInfo().CurrentOrgId,
					TotalNum:   int64(len(total_schedule)),
					FailNum:    1,
					SuccessNum: int64(len(schedules)),
					CreateTime: time.Now().Unix(),
					UpdateTime: time.Now().Unix(),
					ExportTime: export_time,
					Status:     1,
				}
				service.CreateExportLog(&log)

				err_log := models.ExportErrLog{
					LogType:    3,
					UserOrgId:  this.GetAdminUserInfo().CurrentOrgId,
					ErrMsg:     "第2行第" + schMapM["row"].(string) + "列的班次格式有误",
					Status:     1,
					CreateTime: time.Now().Unix(),
					UpdateTime: time.Now().Unix(),
					ExportTime: export_time,
				}
				service.CreateExportErrLog(&err_log)
				this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeExportError)
				return

			} else {
				sch.TimeType = int8(schedule_type)
			}

			if schMapM["template_id"] == nil && reflect.TypeOf(schMapM["template_id"]).String() != "float64" {
				utils.ErrorLog("template_id")
				return
			}

			template_id := int64(schMapM["template_id"].(float64))
			sch.TemplateID = template_id

			if schMapM["device_number_name"] == nil || reflect.TypeOf(schMapM["device_number_name"]).String() != "string" {
				utils.ErrorLog("device_number_name")
				return
			}

			partition_name, _ := schMapM["partition_name"].(string)
			zone, _ := service.FindDeviceZoneByName(partition_name, this.GetAdminUserInfo().CurrentOrgId)

			device_number_name, _ := schMapM["device_number_name"].(string)
			if len(device_number_name) == 0 { //分区为空
				log := models.ExportLog{
					LogType:    3,
					UserOrgId:  this.GetAdminUserInfo().CurrentOrgId,
					TotalNum:   int64(len(total_schedule)),
					FailNum:    1,
					SuccessNum: int64(len(schedules)),
					CreateTime: time.Now().Unix(),
					UpdateTime: time.Now().Unix(),
					ExportTime: export_time,
					Status:     1,
				}
				service.CreateExportLog(&log)

				err_log := models.ExportErrLog{
					LogType:   3,
					UserOrgId: this.GetAdminUserInfo().CurrentOrgId,
					//ErrMsg:     "第" + 	strconv.FormatInt(int64(schMapM["index"].(float64)) ,10)+ "行" + "的姓名不能为空",
					ErrMsg: "第" + strconv.FormatInt(int64(schMapM["index"].(float64)), 10) + "行第2列机号格式有误",

					Status:     1,
					CreateTime: time.Now().Unix(),
					UpdateTime: time.Now().Unix(),
					ExportTime: export_time,
				}
				service.CreateExportErrLog(&err_log)
				this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeExportError)
				return

			} else {
				device, err := service.FindDeviceByNameTwo(device_number_name, this.GetAdminUserInfo().CurrentOrgId, zone.ID)
				if err == nil {
					if len(device) == 0 { //没查到数据,插入错误日志
						log := models.ExportLog{
							LogType:    3,
							UserOrgId:  this.GetAdminUserInfo().CurrentOrgId,
							TotalNum:   int64(len(total_schedule)),
							FailNum:    1,
							SuccessNum: int64(len(schedules)),
							CreateTime: time.Now().Unix(),
							UpdateTime: time.Now().Unix(),
							ExportTime: export_time,
							Status:     1,
						}
						service.CreateExportLog(&log)

						err_log := models.ExportErrLog{
							LogType:    3,
							UserOrgId:  this.GetAdminUserInfo().CurrentOrgId,
							ErrMsg:     "第" + strconv.FormatInt(int64(schMapM["index"].(float64)), 10) + "行第2列机号格式有误",
							Status:     1,
							CreateTime: time.Now().Unix(),
							UpdateTime: time.Now().Unix(),
							ExportTime: export_time,
						}
						service.CreateExportErrLog(&err_log)
						this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeExportError)
						return

					} else if len(device) == 1 {
						sch.DeviceNumberID = device[0].ID

					} else if len(device) > 1 { //出现重名,插入错误日志
						log := models.ExportLog{
							LogType:    3,
							UserOrgId:  this.GetAdminUserInfo().CurrentOrgId,
							TotalNum:   int64(len(total_schedule)),
							FailNum:    1,
							SuccessNum: int64(len(schedules)),
							CreateTime: time.Now().Unix(),
							UpdateTime: time.Now().Unix(),
							ExportTime: export_time,
							Status:     1,
						}
						service.CreateExportLog(&log)

						err_log := models.ExportErrLog{
							LogType:    3,
							UserOrgId:  this.GetAdminUserInfo().CurrentOrgId,
							ErrMsg:     "出现两个床位号相同的床位",
							Status:     1,
							CreateTime: time.Now().Unix(),
							UpdateTime: time.Now().Unix(),
							ExportTime: export_time,
						}
						service.CreateExportErrLog(&err_log)
						this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeExportError)
						return

					}
				}
			}

			if schMapM["schedule_week"] == nil || reflect.TypeOf(schMapM["schedule_week"]).String() != "string" {
				utils.ErrorLog("schedule_week")
				return
			}
			schedule_week, _ := schMapM["schedule_week"].(string)
			if len(schedule_week) == 0 { //周几为空则生成一条导入错误日志

				log := models.ExportLog{
					LogType:    3,
					UserOrgId:  this.GetAdminUserInfo().CurrentOrgId,
					TotalNum:   int64(len(total_schedule)),
					FailNum:    1,
					SuccessNum: int64(len(schedules)),
					CreateTime: time.Now().Unix(),
					UpdateTime: time.Now().Unix(),
					ExportTime: export_time,
					Status:     1,
				}
				service.CreateExportLog(&log)

				err_log := models.ExportErrLog{
					LogType:   3,
					UserOrgId: this.GetAdminUserInfo().CurrentOrgId,
					//ErrMsg:     "第" + 	strconv.FormatInt(int64(schMapM["index"].(float64)) ,10)+ "行" + "的姓名不能为空",
					ErrMsg: "第1行第" + schMapM["row"].(string) + "列的星期名格式有误",

					Status:     1,
					CreateTime: time.Now().Unix(),
					UpdateTime: time.Now().Unix(),
					ExportTime: export_time,
				}
				service.CreateExportErrLog(&err_log)
				this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeExportError)
				return

			} else if schedule_week == "0" { //周几不符合格式则生成一条导入错误日志

				log := models.ExportLog{
					LogType:    3,
					UserOrgId:  this.GetAdminUserInfo().CurrentOrgId,
					TotalNum:   int64(len(total_schedule)),
					FailNum:    1,
					SuccessNum: int64(len(schedules)),
					CreateTime: time.Now().Unix(),
					UpdateTime: time.Now().Unix(),
					ExportTime: export_time,
					Status:     1,
				}
				service.CreateExportLog(&log)

				err_log := models.ExportErrLog{
					LogType:    3,
					UserOrgId:  this.GetAdminUserInfo().CurrentOrgId,
					ErrMsg:     "第1行第" + schMapM["row"].(string) + "列的星期名格式有误",
					Status:     1,
					CreateTime: time.Now().Unix(),
					UpdateTime: time.Now().Unix(),
					ExportTime: export_time,
				}
				service.CreateExportErrLog(&err_log)
				this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeExportError)
				return

			} else {
				schedule_week, _ := strconv.ParseInt(schedule_week, 10, 64)
				sch.Weekday = int8(schedule_week)

			}

			sch.CreateTime = time.Now().Unix()
			sch.ModifyTime = time.Now().Unix()
			sch.TreatMode = 1
			sch.Status = 1
			sch.OrgID = this.GetAdminUserInfo().CurrentOrgId
			sch.IsExport = 1
			schedules = append(schedules, &sch)
		}

		errLogs, _ := service.FindSchedualTemplateExportLog(this.GetAdminUserInfo().CurrentOrgId, export_time)

		if len(schedules) > 0 {
			err := service.UpdateScheduleTemplateStatus(this.GetAdminUserInfo().CurrentOrgId)
			if err == nil {
				for _, item := range schedules {
					service.CreateScheduleTemplate(item)
				}

				log := models.ExportLog{
					LogType:    3,
					UserOrgId:  this.GetAdminUserInfo().CurrentOrgId,
					TotalNum:   int64(len(total_schedule)),
					FailNum:    int64(len(errLogs)),
					SuccessNum: int64(len(schedules)),
					CreateTime: time.Now().Unix(),
					UpdateTime: time.Now().Unix(),
					ExportTime: export_time,
					Status:     1,
				}
				service.CreateExportLog(&log)

				this.ServeSuccessJSON(map[string]interface{}{
					"msg":         "导入成功",
					"total_num":   len(total_schedule),
					"success_num": len(schedules),
					"fail_num":    int64(len(errLogs)),
				})
			} else {
				log := models.ExportLog{
					LogType:    3,
					UserOrgId:  this.GetAdminUserInfo().CurrentOrgId,
					TotalNum:   int64(len(total_schedule)),
					FailNum:    int64(len(errLogs)),
					SuccessNum: int64(len(schedules)),
					CreateTime: time.Now().Unix(),
					UpdateTime: time.Now().Unix(),
					ExportTime: export_time,
					Status:     1,
				}
				service.CreateExportLog(&log)

				this.ServeSuccessJSON(map[string]interface{}{
					"msg":         "导入成功",
					"total_num":   len(total_schedule),
					"success_num": len(schedules),
					"fail_num":    int64(len(errLogs)),
				})
			}
		} else {
			log := models.ExportLog{
				LogType:    3,
				UserOrgId:  this.GetAdminUserInfo().CurrentOrgId,
				TotalNum:   int64(len(total_schedule)),
				FailNum:    int64(len(errLogs)),
				SuccessNum: int64(len(schedules)),
				CreateTime: time.Now().Unix(),
				UpdateTime: time.Now().Unix(),
				ExportTime: export_time,
				Status:     1,
			}
			service.CreateExportLog(&log)

			this.ServeSuccessJSON(map[string]interface{}{
				"msg":         "导入成功",
				"total_num":   len(total_schedule),
				"success_num": len(schedules),
				"fail_num":    int64(len(errLogs)),
			})
		}
	}

}

func (c *ScheduleApiController) GetInitExcelInitDate() {

	thisTime := time.Now()
	thisTime1 := time.Now()
	thisTime2 := time.Now()

	thisTime1 = thisTime1.AddDate(0, 0, 7)
	thisTime2 = thisTime2.AddDate(0, 0, 14)

	weekDay := int(thisTime.Weekday())
	if weekDay == 0 {
		weekDay = 7
	}
	weekEnd := 7 - weekDay
	weekStart := weekEnd - 6
	days := make([]string, 0)
	for index := weekStart; index <= weekEnd; index++ {
		theDay := thisTime.AddDate(0, 0, index)
		days = append(days, theDay.Format("2006-01-02"))
	}

	weekDay1 := int(thisTime1.Weekday())
	if weekDay1 == 0 {
		weekDay1 = 7
	}
	weekEnd1 := 7 - weekDay1
	weekStart1 := weekEnd1 - 6
	for index := weekStart1; index <= weekEnd1; index++ {
		theDay := thisTime1.AddDate(0, 0, index)
		days = append(days, theDay.Format("2006-01-02"))
	}

	weekDay2 := int(thisTime2.Weekday())
	if weekDay2 == 0 {
		weekDay2 = 7
	}
	weekEnd2 := 7 - weekDay2
	weekStart2 := weekEnd2 - 6
	for index := weekStart2; index <= weekEnd2; index++ {
		theDay := thisTime2.AddDate(0, 0, index)
		days = append(days, theDay.Format("2006-01-02"))
	}

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

func GetWeekString(week string) string {
	var weekStr string
	switch week {
	case "Sunday":
		weekStr = "周日"
		break
	case "Monday":
		weekStr = "周一"
		break
	case "Tuesday":
		weekStr = "周二"
		break
	case "Wednesday":
		weekStr = "周三"
		break
	case "Thursday":
		weekStr = "周四"

		break
	case "Friday":
		weekStr = "周五"

		break
	case "Saturday":
		weekStr = "周六"
		break
	default:
		weekStr = ""
		break

	}
	return weekStr
}

func (c *ScheduleApiController) SearchTemplateSchedulePatients() {
	template_id, _ := c.GetInt64("template_id", 0)
	keywords := c.GetString("keywords")
	adminInfo := c.GetAdminUserInfo()
	scheduleItems, _ := service.GetTemplateSchedualPatientsByKeywords(keywords, adminInfo.CurrentOrgId, template_id)
	c.ServeSuccessJSON(map[string]interface{}{
		"schdules": scheduleItems,
	})
}

func (c *ScheduleApiController) CancelScheduleTemplate() {
	item_id, _ := c.GetInt64("id")
	adminInfo := c.GetAdminUserInfo()
	err := service.UpdateNewScheduleTemplateStatus(item_id, adminInfo.CurrentOrgId)

	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"msg": "取消成功",
		})
		return
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeExportError)
		return
	}
}

func (this *ScheduleApiController) GetNextWeekDaySchedule() {

	week_type, _ := this.GetInt64("week_type", -1)
	week_time, _ := this.GetInt64("week_time")
	//start_time, _ := this.GetInt64("start_time")
	//end_time, _ := this.GetInt64("end_time")
	record_date := this.GetString("record_date")

	zons := this.GetString("zone")
	zone := strings.Split(zons, ",")
	start_time := this.GetString("start_time")
	end_time := this.GetString("end_time")
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	theTimeStart, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
	theTimeEnd, err := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 00:00:00", loc)

	adminUserInfo := this.GetAdminUserInfo()
	var theStartTIme int64
	if len(record_date) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", record_date+" 00:00:00", loc)
		if err != nil {
			utils.ErrorLog(err.Error())
		}
		theStartTIme = theTime.Unix()
	}

	schedule, err := service.GetNextWeekDaySchedule(week_type, week_time, theTimeStart.Unix(), theTimeEnd.Unix(), adminUserInfo.CurrentOrgId, zone, theStartTIme)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"schedule": schedule,
	})
}

func (this *ScheduleApiController) GetThreeWeekList() {
	start_time := this.GetString("start_time")
	end_time := this.GetString("end_time")
	partition_id, _ := this.GetInt64("partition_id")
	schedule_type, _ := this.GetInt64("schedule_type")
	fmt.Println(partition_id, schedule_type)
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")

	var theStartTIme int64
	if len(start_time) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
		if err != nil {
			utils.ErrorLog(err.Error())
		}
		theStartTIme = theTime.Unix()
	}
	var theEndtTIme int64
	if len(end_time) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 00:00:00", loc)
		if err != nil {
			utils.ErrorLog(err.Error())
		}
		theEndtTIme = theTime.Unix()
	}

	adminUserInfo := this.GetAdminUserInfo()
	orgId := adminUserInfo.CurrentOrgId
	partitions, _ := service.GetSchedulePartitionPanel(orgId)
	list, err := service.GetThreeWeekList(theStartTIme, theEndtTIme, orgId, schedule_type, partition_id)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"list":       list,
		"partitions": partitions,
	})
}

func (this *ScheduleApiController) GetAllZones() {

	adminUserInfo := this.GetAdminUserInfo()
	orgId := adminUserInfo.CurrentOrgId
	zones, err := service.GetAllZoneOne(orgId)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"zones": zones,
	})
}

func (this *ScheduleApiController) GetCopyPatientSchedules() {
	adminUserInfo := this.GetAdminUserInfo()
	orgId := adminUserInfo.CurrentOrgId
	start_time, _ := this.GetInt64("start_time")
	fmt.Println("start_time", start_time)
	end_time, _ := this.GetInt64("end_time")
	fmt.Println("end_time", end_time)
	copy_startime, _ := this.GetInt64("copy_startime")
	fmt.Println("copy_startime", copy_startime)
	copy_endtime, _ := this.GetInt64("copy_endtime")

	//获取本周患者排班
	schedules, _ := service.GetWeekSchedules(orgId, start_time, end_time)

	//先清除复制周的排班
	errcode := service.UpdatePatientSchedule(orgId, copy_startime, copy_endtime)
	fmt.Println(errcode)
	for _, item := range schedules {
		//fmt.Println(item.StartTime+604800)
		//礼拜1
		if item.ScheduleWeek == 1 {
			item.ScheduleDate = copy_startime
		}
		if item.ScheduleWeek == 2 {
			item.ScheduleDate = copy_startime + 86400
		}
		if item.ScheduleWeek == 3 {
			item.ScheduleDate = copy_startime + 172800
		}
		if item.ScheduleWeek == 4 {
			item.ScheduleDate = copy_startime + 259200
		}
		if item.ScheduleWeek == 5 {
			item.ScheduleDate = copy_startime + 345600
		}

		if item.ScheduleWeek == 6 {
			item.ScheduleDate = copy_startime + 432000
		}
		//礼拜天
		if item.ScheduleWeek == 7 {
			item.ScheduleDate = copy_endtime
		}
		schedule := models.XtSchedule{
			UserOrgId:    item.UserOrgId,
			PartitionId:  item.PartitionId,
			BedId:        item.BedId,
			PatientId:    item.PatientId,
			ScheduleDate: item.ScheduleDate,
			ScheduleType: item.ScheduleType,
			ScheduleWeek: item.ScheduleWeek,
			ModeId:       item.ModeId,
			Status:       1,
			CreatedTime:  time.Now().Unix(),
		}

		err := service.AddPatientSchedule(&schedule)
		if err != nil {
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}
		this.ServeSuccessJSON(map[string]interface{}{
			"schedule": schedule,
		})
	}
	//查询复制中的排班日期是否存在
	//_, errcode := service.GetLastWeekSchedule(orgId, copy_startime, copy_endtime)
	//
	//if errcode == gorm.ErrRecordNotFound {
	//	//如果没有直接新增
	//
	//	for _, item := range schedules {
	//		//fmt.Println(item.StartTime+604800)
	//		//礼拜1
	//		if item.ScheduleWeek == 1 {
	//			item.ScheduleDate = copy_startime
	//		}
	//		if item.ScheduleWeek == 2 {
	//			item.ScheduleDate = copy_startime + 86400
	//		}
	//		if item.ScheduleWeek == 3 {
	//			item.ScheduleDate = copy_startime + 172800
	//		}
	//		if item.ScheduleWeek == 4 {
	//			item.ScheduleDate = copy_startime + 259200
	//		}
	//		if item.ScheduleWeek == 5 {
	//			item.ScheduleDate = copy_startime + 345600
	//		}
	//
	//		if item.ScheduleWeek == 6 {
	//			item.ScheduleDate = copy_startime + 432000
	//		}
	//		//礼拜天
	//		if item.ScheduleWeek == 0 {
	//			item.ScheduleDate = copy_endtime
	//		}
	//		schedule := models.XtSchedule{
	//			UserOrgId:    item.UserOrgId,
	//			PartitionId:  item.PartitionId,
	//			BedId:        item.BedId,
	//			PatientId:    item.PatientId,
	//			ScheduleDate: item.ScheduleDate,
	//			ScheduleType: item.ScheduleType,
	//			ScheduleWeek: item.ScheduleWeek,
	//			ModeId:       item.ModeId,
	//			Status:       1,
	//			CreatedTime:  time.Now().Unix(),
	//		}
	//
	//		err := service.AddPatientSchedule(&schedule)
	//		if err != nil {
	//			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
	//			return
	//		}
	//		this.ServeSuccessJSON(map[string]interface{}{
	//			"schedule": schedule,
	//		})
	//	}
	//} else if errcode == nil {
	//
	//	//先清除复制周的排班
	//	errcode := service.UpdatePatientSchedule(orgId, copy_startime, copy_endtime)
	//	fmt.Println(errcode)
	//	for _, item := range schedules {
	//		//fmt.Println(item.StartTime+604800)
	//		//礼拜1
	//		if item.ScheduleWeek == 1 {
	//			item.ScheduleDate = copy_startime
	//		}
	//		if item.ScheduleWeek == 2 {
	//			item.ScheduleDate = copy_startime + 86400
	//		}
	//		if item.ScheduleWeek == 3 {
	//			item.ScheduleDate = copy_startime + 172800
	//		}
	//		if item.ScheduleWeek == 4 {
	//			item.ScheduleDate = copy_startime + 259200
	//		}
	//		if item.ScheduleWeek == 5 {
	//			item.ScheduleDate = copy_startime + 345600
	//		}
	//
	//		if item.ScheduleWeek == 6 {
	//			item.ScheduleDate = copy_startime + 432000
	//		}
	//		//礼拜天
	//		if item.ScheduleWeek == 0 {
	//			item.ScheduleDate = copy_endtime
	//		}
	//		schedule := models.XtSchedule{
	//			UserOrgId:    item.UserOrgId,
	//			PartitionId:  item.PartitionId,
	//			BedId:        item.BedId,
	//			PatientId:    item.PatientId,
	//			ScheduleDate: item.ScheduleDate,
	//			ScheduleType: item.ScheduleType,
	//			ScheduleWeek: item.ScheduleWeek,
	//			ModeId:       item.ModeId,
	//			Status:       1,
	//			CreatedTime:  time.Now().Unix(),
	//		}
	//
	//		err := service.AddPatientSchedule(&schedule)
	//		if err != nil {
	//			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
	//			return
	//		}
	//		this.ServeSuccessJSON(map[string]interface{}{
	//			"schedule": schedule,
	//		})
	//	}
	//}
}

func (this *ScheduleApiController) SaveRemindPrint() {

	id, _ := this.GetInt64("id")
	anticoagulants, _ := this.GetInt64("anticoagulant")
	anticoagulant_zongliang, _ := this.GetInt64("anticoagulant_zongliang")
	classes, _ := this.GetInt64("classes")
	dialyzers, _ := this.GetInt64("dialyzers")
	doctor_advice, _ := this.GetInt64("doctor_advice")
	mode, _ := this.GetInt64("mode")
	name, _ := this.GetInt64("name")
	number, _ := this.GetInt64("number")
	perfusion_apparatus, _ := this.GetInt64("perfusion_apparatus")
	prescription_status, _ := this.GetInt64("prescription_status")
	week, _ := this.GetInt64("week")
	zone, _ := this.GetInt64("zone")
	adminUserInfo := this.GetAdminUserInfo()
	orgId := adminUserInfo.CurrentOrgId
	setting := models.XtRemindPrintSetting{
		Anticoagulant:          anticoagulants,
		Classes:                classes,
		AnticoagulantZongliang: anticoagulant_zongliang,
		Dialyzers:              dialyzers,
		DoctorAdvice:           doctor_advice,
		Mode:                   mode,
		Name:                   name,
		Number:                 number,
		PerfusionApparatus:     perfusion_apparatus,
		PrescriptionStatus:     prescription_status,
		Week:                   week,
		Zone:                   zone,
		UserOrgId:              orgId,
		Status:                 1,
		Ctime:                  time.Now().Unix(),
	}
	_, errcode := service.GetSettingById(id)
	if errcode == gorm.ErrRecordNotFound {
		err := service.CreateSetting(&setting)
		if err != nil {
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}

		this.ServeSuccessJSON(map[string]interface{}{
			"setting": setting,
		})
	} else if errcode == nil {
		err := service.UpdatedRemindPrint(&setting, id)
		if err != nil {
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}

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

}
func (this *ScheduleApiController) GetRemindPrintList() {

	adminUserInfo := this.GetAdminUserInfo()
	orgId := adminUserInfo.CurrentOrgId
	list, err := service.GetRemindPrintList(orgId)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}

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

func (this *ScheduleApiController) GetBloodScheduleList() {

	week_type, _ := this.GetInt64("week_type", -1)
	week_time, _ := this.GetInt64("week_time")
	zones := this.GetString("zone")
	zone := strings.Split(zones, ",")
	thisTime := time.Now()
	weekDay := int(thisTime.Weekday())
	if weekDay == 0 {
		weekDay = 7
	}
	weekEnd := 7 - weekDay
	weekStart := weekEnd - 6
	weekTitle := make([]string, 0)
	days := make([]string, 0)
	for index := weekStart; index <= weekEnd; index++ {
		theDay := thisTime.AddDate(0, 0, index)
		indexYear, indexMonthTime, indexDay := theDay.Date()
		indexMonth := int(indexMonthTime)
		indexWeek := strconv.Itoa(indexYear) + "." + strconv.Itoa(indexMonth) + "." + strconv.Itoa(indexDay)
		weekTitle = append(weekTitle, indexWeek)
		days = append(days, theDay.Format("2006-01-02"))
	}
	fmt.Println(days)

	var targetDayStr string
	var startTime string
	switch week_type {
	case 0:
		startTime = days[0]
		targetDayStr = days[6]
		break
	case 1:
		targetDayStr = days[0]
		break
	case 2:
		targetDayStr = days[1]

		break
	case 3:
		targetDayStr = days[2]

		break
	case 4:
		targetDayStr = days[3]

		break
	case 5:
		targetDayStr = days[4]

		break
	case 6:
		targetDayStr = days[5]

		break
	case 7:
		targetDayStr = days[6]

		break
	}
	targetDay, parseErr := utils.ParseTimeStringToTime("2006-01-02", targetDayStr)

	if parseErr != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	orgId := this.GetAdminUserInfo().CurrentOrgId
	if week_type > 0 {
		list, err := service.GetWeekDayScheduleByIdThee(orgId, targetDay.Unix(), week_time, zone)

		if err != nil {
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}

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

	if week_type == 0 {
		startDate, _ := utils.ParseTimeStringToTime("2006-01-02", startTime)
		list, err := service.GetWeekDayScheduleByIdTwo(orgId, targetDay.Unix(), week_time, startDate.Unix(), zone)

		if err != nil {
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}

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

}

func (this *ScheduleApiController) GetPrintList() {

	adminUserInfo := this.GetAdminUserInfo()
	orgId := adminUserInfo.CurrentOrgId

	list, err := service.GetRemindPrintList(orgId)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}

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

func (this *ScheduleApiController) GetAllZoneList() {

	adminUserInfo := this.GetAdminUserInfo()
	orgId := adminUserInfo.CurrentOrgId
	zoneList, err := service.GetAllZoneOne(orgId)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}

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

func (this *ScheduleApiController) GetPatientScheduleCount() {
	patitionIdStr := this.GetString("partition_id")
	week, _ := this.GetInt64("weekTime", 0) //1:last, 2:this 3:next 4 nextTwo
	ids := strings.Split(patitionIdStr, ",")
	adminUserInfo := this.GetAdminUserInfo()
	orgId := adminUserInfo.CurrentOrgId
	thisTime := time.Now()
	weekDay := int(thisTime.Weekday())
	if week < 1 || week > 4 {
		week = 2
	}
	if week == 1 {
		thisTime = thisTime.AddDate(0, 0, -7)
	} else if week == 3 {
		thisTime = thisTime.AddDate(0, 0, 7)
	} else if week == 4 {
		thisTime = thisTime.AddDate(0, 0, 14)
	}
	if weekDay == 0 {
		weekDay = 7
	}
	weekEnd := 7 - weekDay
	weekStart := weekEnd - 6
	weekTitle := make([]string, 0)
	days := make([]string, 0)
	for index := weekStart; index <= weekEnd; index++ {
		theDay := thisTime.AddDate(0, 0, index)
		indexYear, indexMonthTime, indexDay := theDay.Date()
		indexMonth := int(indexMonthTime)
		indexWeek := strconv.Itoa(indexYear) + "." + strconv.Itoa(indexMonth) + "." + strconv.Itoa(indexDay)
		weekTitle = append(weekTitle, indexWeek)
		days = append(days, theDay.Format("2006-01-02"))
	}

	weekStartDay := thisTime.AddDate(0, 0, weekStart)
	weekEndDay := thisTime.AddDate(0, 0, weekEnd)
	weekStartTime := weekStartDay.Format("2006-01-02") + " 00:00:00"
	weekEndTime := weekEndDay.Format("2006-01-02") + " 23:59:59"

	timeLayout := "2006-01-02 15:04:05"
	loc, _ := time.LoadLocation("Local")
	theStarTime, _ := time.ParseInLocation(timeLayout, weekStartTime, loc)
	theEndTime, _ := time.ParseInLocation(timeLayout, weekEndTime, loc)
	weekStartPoint := theStarTime.Unix()
	weekEndPoint := theEndTime.Unix()
	fmt.Println("startTime222222222222222", weekStartPoint)
	fmt.Println("endtime33333333333333", weekEndPoint)
	list, err := service.GetPatientScheduleCount(orgId, weekStartPoint, weekEndPoint, ids)
	_, total, _ := service.GetTotalBedNumber(orgId, ids)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}

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

func (c *ScheduleApiController) GetWeekPanelsOne() {

	data, _ := c.GetInt64("data", 1)
	patitionIdStr := c.GetString("patitionid")

	ids := strings.Split(patitionIdStr, ",")

	adminInfo := c.GetAdminUserInfo()
	thisTime := time.Now()
	year, monthTime, day := thisTime.Date()
	month := int(monthTime)
	_, theWeek := thisTime.ISOWeek()
	weekDay := int(thisTime.Weekday())
	if weekDay == 0 {
		weekDay = 7
	}
	weekEnd := 7 - weekDay
	weekStart := weekEnd - 6
	weekDays := make([]string, 0)
	for index := weekStart; index <= weekEnd; index++ {
		theDay := thisTime.AddDate(0, 0, index)
		indexYear, indexMonthTime, indexDay := theDay.Date()
		indexMonth := int(indexMonthTime)
		indexWeek := strconv.Itoa(indexYear) + "." + strconv.Itoa(indexMonth) + "." + strconv.Itoa(indexDay)
		weekDays = append(weekDays, indexWeek)
	}

	returnData := map[string]interface{}{
		"year":     year,
		"month":    month,
		"day":      day,
		"theWeek":  theWeek,
		"weekDay":  weekDay,
		"weekDays": weekDays,
	}

	if data == 1 {
		partitions, _ := service.GetSchedulePartitionPanelTwo(adminInfo.CurrentOrgId, ids)
		returnData["partitions"] = partitions
	}

	c.ServeSuccessJSON(returnData)
	return
}

func (c *ScheduleApiController) GetScheduleOne() {

	week, _ := c.GetInt64("weekTime", 0) //1:last, 2:this 3:next 4 nextTwo
	patitionIdStr := c.GetString("patitionid")

	ids := strings.Split(patitionIdStr, ",")
	fmt.Println("patitonStr", ids)
	schedule_type, _ := c.GetInt64("schedule_type")

	adminInfo := c.GetAdminUserInfo()

	thisTime := time.Now()
	today := thisTime.Format("2006-01-02")
	if week < 1 || week > 4 {
		week = 2
	}
	if week == 1 {
		thisTime = thisTime.AddDate(0, 0, -7)
	} else if week == 3 {
		thisTime = thisTime.AddDate(0, 0, 7)
	} else if week == 4 {
		thisTime = thisTime.AddDate(0, 0, 14)
	}

	weekDay := int(thisTime.Weekday())
	if weekDay == 0 {
		weekDay = 7
	}
	weekEnd := 7 - weekDay
	weekStart := weekEnd - 6
	weekTitle := make([]string, 0)
	days := make([]string, 0)
	for index := weekStart; index <= weekEnd; index++ {
		theDay := thisTime.AddDate(0, 0, index)
		indexYear, indexMonthTime, indexDay := theDay.Date()
		indexMonth := int(indexMonthTime)
		indexWeek := strconv.Itoa(indexYear) + "." + strconv.Itoa(indexMonth) + "." + strconv.Itoa(indexDay)
		weekTitle = append(weekTitle, indexWeek)
		days = append(days, theDay.Format("2006-01-02"))
	}

	weekStartDay := thisTime.AddDate(0, 0, weekStart)
	weekEndDay := thisTime.AddDate(0, 0, weekEnd)
	weekStartTime := weekStartDay.Format("2006-01-02") + " 00:00:00"
	weekEndTime := weekEndDay.Format("2006-01-02") + " 23:59:59"

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

	schdules, _ := service.GetWeekScheduleTwo(adminInfo.CurrentOrgId, weekStartPoint, weekEndPoint, ids, schedule_type)
	c.ServeSuccessJSON(map[string]interface{}{
		"days":      days,
		"weekTitle": weekTitle,
		"schdules":  schdules,
		"today":     today,
	})
	return
}

func (c *ScheduleApiController) SaveScheduleTemplate() {

	template_id, _ := c.GetInt64("template_id")
	orgId := c.GetAdminUserInfo().CurrentOrgId
	template := models.ScheduleTemplate{
		TemplateId: template_id,
		UserOrgId:  orgId,
		Status:     1,
		Ctime:      time.Now().Unix(),
	}

	_, errcodes := service.GetScheudleTemplateById(orgId)
	if errcodes == gorm.ErrRecordNotFound {
		service.CreateXtscheduleTemplate(&template)
	} else if errcodes == nil {
		service.UpdateXtScheduleTemplate(&template, orgId)
	}

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

}

func (c *ScheduleApiController) GetScheduleTemplate() {

	adminUserInfo := c.GetAdminUserInfo()
	orgId := adminUserInfo.CurrentOrgId
	template, _ := service.GetScheduleTemplate(orgId)
	c.ServeSuccessJSON(map[string]interface{}{
		"template": template,
	})
	return
}

func (c *ScheduleApiController) ChangeFuncPrint() {

	adminUserInfo := c.GetAdminUserInfo()
	orgId := adminUserInfo.CurrentOrgId
	is_open, _ := c.GetInt64("is_open")
	dataPrint := models.XtDataPrint{
		UserOrgId: orgId,
		IsOpen:    is_open,
		Status:    1,
		Ctime:     time.Now().Unix(),
	}

	_, errcode := service.GetDataPrintByOrgId(orgId)
	fmt.Println("errcode222234444555556t66", errcode)
	if errcode == gorm.ErrRecordNotFound {
		service.CreateDataPrint(&dataPrint)
		c.ServeSuccessJSON(map[string]interface{}{
			"dataPrint": dataPrint,
		})
		return
	} else if errcode == nil {
		service.UpdteDataPrint(orgId, &dataPrint)
		c.ServeSuccessJSON(map[string]interface{}{
			"dataPrint": dataPrint,
		})
		return
	}

}

func (c *ScheduleApiController) GetDataPrint() {

	adminUserInfo := c.GetAdminUserInfo()
	orgId := adminUserInfo.CurrentOrgId

	dataPrint, _ := service.GetDataPrint(orgId)
	c.ServeSuccessJSON(map[string]interface{}{
		"dataPrint": dataPrint,
	})
	return
}

func (c *ScheduleApiController) GetNextWeekPanels() {
	start_time, _ := c.GetInt64("start_time")
	fmt.Println("start_time", start_time)
	end_time, _ := c.GetInt64("end_time")
	fmt.Println("end_time", end_time)
	orgId := c.GetAdminUserInfo().CurrentOrgId
	schedule, _ := service.GetNextWeekPanels(start_time, end_time, orgId)
	c.ServeSuccessJSON(map[string]interface{}{
		"schedule": schedule,
	})
}

func (c *ScheduleApiController) SynchroSchedule() {

	template_id, _ := c.GetInt64("template_id")
	copy_startime, _ := c.GetInt64("copy_startime")
	copy_endtime, _ := c.GetInt64("copy_endtime")

	orgId := c.GetAdminUserInfo().CurrentOrgId
	//根据模板ID获取模板数据
	list, _ := service.GetTemplateListByTemplateId(template_id, orgId)

	recordDateStr := time.Now().Format("2006-01-02")
	recordDate, _ := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)

	nowtime := recordDate.Unix()
	fmt.Println("今日时间", nowtime)
	fmt.Println("后期日期", copy_startime)
	var tuesday int64
	var wednesday int64
	var thursday int64
	var friday int64
	var saturday int64

	//如果选择的开始日期大于当前日期
	if copy_startime > nowtime {
		//清空该时间段的所有排班数据
		service.DeletePatientSchedule(copy_startime, copy_endtime, orgId)

		tuesday = copy_startime + 86400
		wednesday = copy_startime + 172800
		thursday = copy_startime + 259200
		friday = copy_startime + 345600
		saturday = copy_startime + 432000

		for _, item := range list {
			if item.Weekday == 1 {
				item.ScheduleDate = copy_startime
			}
			if item.Weekday == 2 {
				item.ScheduleDate = tuesday
			}
			if item.Weekday == 3 {
				item.ScheduleDate = wednesday
			}
			if item.Weekday == 4 {
				item.ScheduleDate = thursday
			}
			if item.Weekday == 5 {
				item.ScheduleDate = friday
			}
			if item.Weekday == 6 {
				item.ScheduleDate = saturday
			}
			if item.Weekday == 7 {
				item.ScheduleDate = copy_endtime
			}

			//根据床位号获取区号
			number, _ := service.GetBedNumberById(item.DeviceNumberID, orgId)
			item.ZoneId = number.ZoneID
		}

		for _, item := range list {
			schedule := models.XtSchedule{
				UserOrgId:    orgId,
				PartitionId:  item.ZoneId,
				BedId:        item.DeviceNumberID,
				PatientId:    item.PatientID,
				ScheduleDate: item.ScheduleDate,
				ScheduleType: item.TimeType,
				ScheduleWeek: item.Weekday,
				ModeId:       item.TreatMode,
				Status:       1,
				CreatedTime:  time.Now().Unix(),
				UpdatedTime:  0,
			}

			service.CreatePatientSchedule(&schedule)
		}
	}
	//如果选择的日期小于当前日期,只同步今日以后的数据
	if copy_startime <= nowtime {
		//清空今日以后的数据
		service.DeletePatientScheduleToday(nowtime, copy_endtime, orgId)
		var tuesday int64
		var wednesday int64
		var thursday int64
		var friday int64
		var saturday int64

		tuesday = copy_startime + 86400
		wednesday = copy_startime + 172800
		thursday = copy_startime + 259200
		friday = copy_startime + 345600
		saturday = copy_startime + 432000

		for _, item := range list {
			if item.Weekday == 1 {
				item.ScheduleDate = copy_startime
			}
			if item.Weekday == 2 {
				item.ScheduleDate = tuesday
			}
			if item.Weekday == 3 {
				item.ScheduleDate = wednesday
			}
			if item.Weekday == 4 {
				item.ScheduleDate = thursday
			}
			if item.Weekday == 5 {
				item.ScheduleDate = friday
			}
			if item.Weekday == 6 {
				item.ScheduleDate = saturday
			}
			if item.Weekday == 7 {
				item.ScheduleDate = copy_endtime
			}

			//根据床位号获取区号
			number, _ := service.GetBedNumberById(item.DeviceNumberID, orgId)
			item.ZoneId = number.ZoneID
		}

		for _, item := range list {
			// 同步今日以后的数据
			if item.ScheduleDate > nowtime {
				schedule := models.XtSchedule{
					UserOrgId:    orgId,
					PartitionId:  item.ZoneId,
					BedId:        item.DeviceNumberID,
					PatientId:    item.PatientID,
					ScheduleDate: item.ScheduleDate,
					ScheduleType: item.TimeType,
					ScheduleWeek: item.Weekday,
					ModeId:       item.TreatMode,
					Status:       1,
					CreatedTime:  time.Now().Unix(),
					UpdatedTime:  0,
				}
				service.CreatePatientSchedule(&schedule)
			}
		}

	}

	returnData := make(map[string]interface{}, 0)
	returnData["list"] = list
	c.ServeSuccessJSON(returnData)
	return
}

func (c *ScheduleApiController) GetPatientScheduleTempalate() {

	orgId := c.GetAdminUserInfo().CurrentOrgId
	tempalate, _ := service.GetPatientScheduleTempalate(orgId)
	c.ServeSuccessJSON(map[string]interface{}{
		"schedule": tempalate,
	})
}

func (c *ScheduleApiController) GetSolutionSchedule() {

	orgId := c.GetAdminUserInfo().CurrentOrgId
	solution, _ := service.GetSolutionSchedule(orgId)
	c.ServeSuccessJSON(map[string]interface{}{
		"solution": solution,
	})
	return
}