package city

import (
	"Data_Upload_Api/models/sz"
	"Data_Upload_Api/service"
	"XT/utils"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/jinzhu/gorm"
	"github.com/robfig/cron"
	"math"
	"strconv"
	"strings"
	"time"
)

var createUploadDataCronJob *cron.Cron

func init() {
	utils.InfoLog("开启定时任务")
	createUploadDataCronJob = cron.New()
	spec := "0 0 0 * * ?" // 每天凌晨0点检测数据上报情况
	createUploadDataCronJob.AddFunc(spec, func() {
		AutoSZUploadData() //深圳市数据上报

	})
}

func BeginAutoJob() {
	createUploadDataCronJob.Start()
}

func AutoSZUploadData() {
	//查出所有需要上传到深圳市健康数据中心的机构数据上报配置
	//这里暂时用上报到深圳市的方式，来处理数据，如果以后有其他城市，需要在这里对不同城市进行不同数据处理
	sz_province, _ := beego.AppConfig.Int64("sz_province")
	sz_city, _ := beego.AppConfig.Int64("sz_city")
	configs, _ := service.FindAllDataUploadConfigOrgInfo(sz_province, sz_city, 3)
	for _, config := range configs {

		//机构
		_, err := service.FindDataUploadOrgInfo(config.OrgId, 1)
		if err == gorm.ErrRecordNotFound {
			if GetDiffDay(config) <= 0 {

				//新增
				org, _ := service.FindOrgData(config.OrgId)
				hospital := &sz.TempHdHospital{
					HospitalId:     strconv.FormatInt(org.ID, 10),
					InstType:       strconv.FormatInt(1, 10),
					AuthorizedBeds: int64(len(org.DeviceNumber)),
					CreateTime:     time.Now(),
					UpdateTime:     time.Now(),
					Sjscsj:         time.Now(),
					Xgbz:           0,
				}
				err := service.CreateOrgRecord(hospital)
				if err == nil {
					upload := &sz.DataUpload{
						ModuleType:   1,
						OrgId:        org.ID,
						UploadDate:   time.Now().Unix(),
						UploadStatus: 1,
						UploadType:   1,
					}
					err := service.CreateUploadRecord(upload)
					if err != nil {
						utils.ErrorLog("%v", err)

					}
				}
			}
		}

		//机构人员
		record, err_two := service.FindDataUploadOrgInfo(config.OrgId, 2)
		if err_two == gorm.ErrRecordNotFound {
			if GetDiffDay(config) <= 0 {

				var staffs []*sz.TempHdStaff
				roles, _ := service.FindOrgRolesData(config.OrgId, 0, 0)
				for _, role := range roles {
					var title string
					switch role.UserType {
					case 2:
						title = strconv.FormatInt(1, 10)
						break
					case 3:
						title = strconv.FormatInt(2, 10)
						break
					}

					staff := &sz.TempHdStaff{
						HospitalId:    strconv.FormatInt(role.OrgId, 10),
						StaffId:       strconv.FormatInt(role.ID, 10),
						StaffName:     role.UserName,
						Position:      title,
						PermanentType: strconv.FormatInt(1, 10),
						CreateTime:    time.Now(),
						UpdateTime:    time.Now(),
						Sjscsj:        time.Now(),
						Xgbz:          strconv.FormatInt(0, 10),
					}
					staffs = append(staffs, staff)
				}

				err := service.BatchCreateStaffRecord(staffs, r)
				if err == nil {
					upload := &sz.DataUpload{
						ModuleType:   2,
						OrgId:        config.OrgId,
						UploadDate:   time.Now().Unix(),
						UploadStatus: 1,
						UploadType:   1,
					}
					err := service.CreateUploadRecord(upload)
					if err != nil {
						utils.ErrorLog("%v", err)

					}
				}
			}

		} else if err_two == nil {
			if GetDiffDay2(config, record) <= 0 {
				var staffs []*sz.TempHdStaff
				roles, _ := service.FindOrgRolesData(record.OrgId, record.UploadDate, time.Now().Unix())
				for _, role := range roles {
					var title string
					switch role.UserType {
					case 2:
						title = strconv.FormatInt(1, 10)
						break
					case 3:
						title = strconv.FormatInt(2, 10)
						break
					}

					staff := &sz.TempHdStaff{
						HospitalId:    strconv.FormatInt(role.OrgId, 10),
						StaffId:       strconv.FormatInt(role.ID, 10),
						StaffName:     role.UserName,
						Position:      title,
						PermanentType: strconv.FormatInt(1, 10),
						CreateTime:    time.Now(),
						UpdateTime:    time.Now(),
						Sjscsj:        time.Now(),
						Xgbz:          strconv.FormatInt(0, 10),
					}
					staffs = append(staffs, staff)
				}

				err := service.BatchCreateStaffRecord(staffs)
				if err == nil {
					upload := &sz.DataUpload{
						ModuleType:   2,
						OrgId:        record.OrgId,
						UploadDate:   time.Now().Unix(),
						UploadStatus: 1,
						UploadType:   1,
					}
					err := service.CreateUploadRecord(upload)
					if err != nil {
						utils.ErrorLog("%v", err)
					}
				}
			}
		}

		record, err_four := service.FindDataUploadOrgInfo(config.OrgId, 4)
		if err_four == gorm.ErrRecordNotFound {
			if GetDiffDay(config) <= 0 {
				var hdPatients []*sz.TempHdPatient
				patients, _ := service.FindOrgPatientData(config.OrgId, 0, 0)

				for _, patient := range patients {

					idcard_year, _ := strconv.Atoi(Substr(patient.IdCardNo, 6, 4)) // 年
					idcard_mo, _ := strconv.Atoi(Substr(patient.IdCardNo, 10, 2))  // 月
					idcard_day, _ := strconv.Atoi(Substr(patient.IdCardNo, 12, 2)) // 日

					date := strconv.Itoa(idcard_year) + "-" + strconv.Itoa(idcard_mo) + "-" + strconv.Itoa(idcard_day)

					local, _ := time.LoadLocation("Local")
					birthday, _ := time.ParseInLocation("2006-01-02", date, local)

					var isCKD int

					value := strings.Index(patient.Diagnose, "慢性肾脏病")
					value2 := strings.Index(patient.Diagnose, "CKD")
					value3 := strings.Index(patient.Diagnose, "慢性肾衰竭")

					if value != -1 || value2 != -1 || value3 != -1 {
						isCKD = 1
					} else {
						isCKD = 0
					}

					p := &sz.TempHdPatient{
						HospitalId:       strconv.FormatInt(patient.UserOrgId, 10),
						PatientNk:        strconv.FormatInt(patient.ID, 10),
						CardNo:           "000000000000000000",
						CardType:         "01",
						IdNo:             patient.IdCardNo,
						IdType:           "01",
						PatientName:      patient.Name,
						Gender:           strconv.FormatInt(patient.Gender, 10),
						BornDate:         birthday,
						DiagnosisSummary: patient.Diagnose,
						IsCrf:            strconv.Itoa(isCKD),
						CreatedTime:      time.Now(),
						UpdateTime:       time.Now(),
						Sjscsj:           time.Now(),
						Xgbz:             strconv.FormatInt(0, 10),
					}

					if patient.FirstDialysisDate != 0 {
						p.DialysisStartTime = time.Unix(patient.FirstDialysisDate, 0)
					}
					if patient.HospitalFirstDialysisDate != 0 {
						p.LocalStartTime = time.Unix(patient.HospitalFirstDialysisDate, 0)
					}

					hdPatients = append(hdPatients, p)
				}

				for _, item := range hdPatients {
					service.XTWriteDB().Model(&sz.TempHdPatient{}).Create(item)
				}

				upload := &sz.DataUpload{
					ModuleType:   4,
					OrgId:        config.OrgId,
					UploadDate:   time.Now().Unix(),
					UploadStatus: 1,
					UploadType:   1,
				}
				err := service.CreateUploadRecord(upload)
				if err != nil {
					utils.ErrorLog("%v", err)
				}
			}
		} else if err_four == nil {
			if GetDiffDay2(config, record) <= 0 {

				var hdPatients []*sz.TempHdPatient
				patients, _ := service.FindOrgPatientData(record.OrgId, record.UploadDate, time.Now().Unix())
				for _, patient := range patients {
					idcard_year, _ := strconv.Atoi(Substr(patient.IdCardNo, 6, 4)) // 年
					idcard_mo, _ := strconv.Atoi(Substr(patient.IdCardNo, 10, 2))  // 月
					idcard_day, _ := strconv.Atoi(Substr(patient.IdCardNo, 12, 2)) // 日
					date := strconv.Itoa(idcard_year) + "-" + strconv.Itoa(idcard_mo) + "-" + strconv.Itoa(idcard_day)
					local, _ := time.LoadLocation("Local")
					birthday, _ := time.ParseInLocation("2006-01-02", date, local)

					var isCKD int

					value := strings.Index(patient.Diagnose, "慢性肾脏病")
					value2 := strings.Index(patient.Diagnose, "CKD")
					value3 := strings.Index(patient.Diagnose, "慢性肾衰竭")

					if value != -1 || value2 != -1 || value3 != -1 {
						isCKD = 1
					} else {
						isCKD = 0
					}

					p := &sz.TempHdPatient{
						HospitalId:       strconv.FormatInt(patient.UserOrgId, 10),
						PatientNk:        strconv.FormatInt(patient.ID, 10),
						CardNo:           "000000000000000000",
						CardType:         "01",
						IdNo:             patient.IdCardNo,
						IdType:           "01",
						PatientName:      patient.Name,
						Gender:           strconv.FormatInt(patient.Gender, 10),
						BornDate:         birthday,
						DiagnosisSummary: patient.Diagnose,
						IsCrf:            strconv.Itoa(isCKD),
						CreatedTime:      time.Now(),
						UpdateTime:       time.Now(),
						Sjscsj:           time.Now(),
						Xgbz:             strconv.FormatInt(0, 10),
					}

					if patient.FirstDialysisDate != 0 {
						p.DialysisStartTime = time.Unix(patient.FirstDialysisDate, 0)
					}
					if patient.HospitalFirstDialysisDate != 0 {
						p.LocalStartTime = time.Unix(patient.HospitalFirstDialysisDate, 0)
					}

					hdPatients = append(hdPatients, p)
				}

				for _, item := range hdPatients {
					service.XTReadDB().Model(&sz.TempHdPatient{}).Create(item)
				}

				upload := &sz.DataUpload{
					ModuleType:   4,
					OrgId:        record.OrgId,
					UploadDate:   time.Now().Unix(),
					UploadStatus: 1,
					UploadType:   1,
				}
				err := service.CreateUploadRecord(upload)
				if err != nil {
					utils.ErrorLog("%v", err)
				}
			}
		}

		//record, err_five := service.FindDataUploadOrgInfo(config.OrgId, 5)
		//if err_five == gorm.ErrRecordNotFound {
		//	if 	GetDiffDay(config) <= 0 {
		//
		//		var hdPatientOuts []*sz.TempHdPatientOut
		//		patients, _ := service.FindOrgPatientOutData(config.OrgId, 0, 0)
		////
		//		for _, patient := range patients {
		//
		//			p := &sz.TempHdPatientOut{
		//				Sn:           strconv.FormatInt(patient.ID, 10),
		//				HospitalId:   strconv.FormatInt(patient.UserOrgId, 10),
		//				PatientNk:    strconv.FormatInt(patient.ID, 10),
		//				SequelaeType: "99",
		//				ExtReason:    "98",
		//				CreateTime:   time.Now(),
		//				Sjscsj:       time.Now(),
		//				Xgbz:         0,
		//			}
		//
		//			if len(patient.PatientLapseto) > 0{
		//				p.SequelaeDate = time.Unix(patient.PatientLapseto[len(patient.PatientLapseto)].LapsetoTime, 0)
		//			}
		//
		//			hdPatientOuts = append(hdPatientOuts, p)
		//		}
		//
		//		for _, item := range hdPatientOuts {
		//			service.XTWriteDB().Model(&sz.TempHdPatientOut{}).Create(item)
		//		}
		//
		//		upload := &sz.DataUpload{
		//			ModuleType:   5,
		//			OrgId:        config.OrgId,
		//			UploadDate:   time.Now().Unix(),
		//			UploadStatus: 1,
		//			UploadType:   1,
		//		}
		//		err := service.CreateUploadRecord(upload)
		//		if err != nil{
		//			utils.ErrorLog("%v",err)
		//		}
		//	}
		//
		//} else if err_five == nil {
		//	if 	GetDiffDay2(config,record) <= 0 {
		//
		//		var hdPatientOuts []*sz.TempHdPatientOut
		//		patients, _ := service.FindOrgPatientOutData(record.OrgId, record.UploadDate, time.Now().Unix())
		//
		//		for _, patient := range patients {
		//
		//			p := &sz.TempHdPatientOut{
		//				Sn:           strconv.FormatInt(patient.ID, 10),
		//				HospitalId:   strconv.FormatInt(patient.UserOrgId, 10),
		//				PatientNk:    strconv.FormatInt(patient.ID, 10),
		//				SequelaeDate: time.Unix(patient.PatientLapseto[len(patient.PatientLapseto)].LapsetoTime, 0),
		//				SequelaeType: "99",
		//				ExtReason:    "98",
		//				CreateTime:   time.Now(),
		//				Sjscsj:       time.Now(),
		//				Xgbz:         0,
		//			}
		//
		//			hdPatientOuts = append(hdPatientOuts, p)
		//		}
		//
		//		for _, item := range hdPatientOuts {
		//			service.XTWriteDB().Model(&sz.TempHdPatientOut{}).Create(item)
		//		}
		//
		//		upload := &sz.DataUpload{
		//			ModuleType:   5,
		//			OrgId:        record.OrgId,
		//			UploadDate:   time.Now().Unix(),
		//			UploadStatus: 1,
		//			UploadType:   1,
		//		}
		//		err := service.CreateUploadRecord(upload)
		//		if err != nil{
		//			utils.ErrorLog("%v",err)
		//		}
		//	}
		//
		//}

		record, err_six := service.FindDataUploadOrgInfo(config.OrgId, 6)
		if err_six == gorm.ErrRecordNotFound {

			if GetDiffDay(config) <= 0 {

				var hdPrescription []*sz.TempHdPs
				prescriptions, _ := service.FindOrgDialysisPrescriptionData(config.OrgId, 0, 0)

				for _, item := range prescriptions {

					ps := &sz.TempHdPs{
						PrescribeId:   strconv.FormatInt(item.ID, 10),
						HospitalId:    strconv.FormatInt(item.UserOrgId, 10),
						PatientNk:     strconv.FormatInt(item.PatientId, 10),
						K:             item.Kalium,
						Ca:            item.Calcium,
						Na:            item.Sodium,
						CreateTime:    time.Now(),
						Sjscsj:        time.Now(),
						Xgbz:          0,
						PrescribeTime: time.Unix(item.RecordDate, 0),
					}

					switch item.ModeId {
					case 1:
						ps.DialysisFrequency = item.AssessmentBeforeDislysis.DialysisCount
						ps.FrequencyUnit = 1
						ps.DialysisDuration = item.DialysisDuration
						ps.Hdf = "0"
						ps.Hp = "0"

						break
					case 2:
						ps.Hdf = "1"
						ps.Hp = "0"
						ps.HdfFrequency = item.AssessmentBeforeDislysis.DialysisCount
						ps.HdfFrequencyUnit = 1
						ps.HpDuration = item.DialysisDuration
						break
					case 4:
						ps.Hdf = "0"
						ps.Hp = "1"
						ps.HpFrequency = item.AssessmentBeforeDislysis.DialysisCount
						ps.HpFrequencyUnit = 1
						ps.HpDuration = item.DialysisDuration
						break
					}

					hdPrescription = append(hdPrescription, ps)
				}

				for _, item := range hdPrescription {
					service.XTWriteDB().Model(&sz.TempHdPs{}).Create(item)
				}

				upload := &sz.DataUpload{
					ModuleType:   6,
					OrgId:        config.OrgId,
					UploadDate:   time.Now().Unix(),
					UploadStatus: 1,
					UploadType:   1,
				}
				err := service.CreateUploadRecord(upload)
				if err != nil {
					utils.ErrorLog("%v", err)
				}
			}

		} else if err_six == nil {
			if GetDiffDay2(config, record) <= 0 {

				var hdPrescription []*sz.TempHdPs
				prescriptions, _ := service.FindOrgDialysisPrescriptionData(record.OrgId, record.UploadDate, time.Now().Unix())

				for _, item := range prescriptions {

					ps := &sz.TempHdPs{
						PrescribeId:   strconv.FormatInt(item.ID, 10),
						HospitalId:    strconv.FormatInt(item.UserOrgId, 10),
						PatientNk:     strconv.FormatInt(item.PatientId, 10),
						K:             item.Kalium,
						Ca:            item.Calcium,
						Na:            item.Sodium,
						CreateTime:    time.Now(),
						Sjscsj:        time.Now(),
						Xgbz:          0,
						PrescribeTime: time.Unix(item.RecordDate, 0),
					}

					switch item.ModeId {
					case 1:
						ps.DialysisFrequency = item.AssessmentBeforeDislysis.DialysisCount
						ps.FrequencyUnit = 1
						ps.DialysisDuration = item.DialysisDuration
						ps.Hdf = "0"
						ps.Hp = "0"

						break
					case 2:
						ps.Hdf = "1"
						ps.Hp = "0"
						ps.HdfFrequency = item.AssessmentBeforeDislysis.DialysisCount
						ps.HdfFrequencyUnit = 1
						ps.HpDuration = item.DialysisDuration
						break
					case 4:
						ps.Hdf = "0"
						ps.Hp = "1"
						ps.HpFrequency = item.AssessmentBeforeDislysis.DialysisCount
						ps.HpFrequencyUnit = 1
						ps.HpDuration = item.DialysisDuration
						break
					}

					hdPrescription = append(hdPrescription, ps)
				}

				for _, item := range hdPrescription {
					service.XTWriteDB().Model(&sz.TempHdPs{}).Create(item)
				}

				upload := &sz.DataUpload{
					ModuleType:   6,
					OrgId:        record.OrgId,
					UploadDate:   time.Now().Unix(),
					UploadStatus: 1,
					UploadType:   1,
				}
				err := service.CreateUploadRecord(upload)
				if err != nil {
					utils.ErrorLog("%v", err)
				}
			}
		}

		record, err_seven := service.FindDataUploadOrgInfo(config.OrgId, 7)
		if err_seven == gorm.ErrRecordNotFound {
			if GetDiffDay(config) <= 0 {
				var hdPsMedicine []*sz.TempHdPsMedicine
				prescriptions, _ := service.FindOrgDialysisPrescriptionData(config.OrgId, 0, 0)

				for _, item := range prescriptions {

					psm := &sz.TempHdPsMedicine{
						Sn:             strconv.FormatInt(item.ID, 10),
						PrescribeId:    strconv.FormatInt(item.ID, 10),
						HospitalId:     strconv.FormatInt(item.UserOrgId, 10),
						MedicineTypeId: "2",
						CreatedTime:    time.Now(),
						Sjscsj:         time.Now(),
						Xgbz:           0,
					}

					switch item.Anticoagulant {
					case 1:
						psm.MedicineId = "3"

						break
					case 2:
						psm.MedicineId = "1"

						break
					case 3:
						psm.MedicineId = "2"

						break
					case 4:
						psm.MedicineId = "5"

						break
					case 5:
						psm.MedicineId = "4"

						break
					}

					hdPsMedicine = append(hdPsMedicine, psm)
				}

				for _, item := range hdPsMedicine {
					service.XTWriteDB().Model(&sz.TempHdPsMedicine{}).Create(item)
				}

				upload := &sz.DataUpload{
					ModuleType:   7,
					OrgId:        config.OrgId,
					UploadDate:   time.Now().Unix(),
					UploadStatus: 1,
					UploadType:   1,
				}
				err := service.CreateUploadRecord(upload)
				if err != nil {
					utils.ErrorLog("%v", err)
				}
			}

		} else if err_seven == nil {
			if GetDiffDay2(config, record) <= 0 {
				var hdPsMedicine []*sz.TempHdPsMedicine
				prescriptions, _ := service.FindOrgDialysisPrescriptionData(record.OrgId, record.UploadDate, time.Now().Unix())

				for _, item := range prescriptions {

					psm := &sz.TempHdPsMedicine{
						Sn:             strconv.FormatInt(item.ID, 10),
						PrescribeId:    strconv.FormatInt(item.ID, 10),
						HospitalId:     strconv.FormatInt(item.UserOrgId, 10),
						MedicineTypeId: "2",
						CreatedTime:    time.Now(),
						Sjscsj:         time.Now(),
						Xgbz:           0,
					}

					switch item.Anticoagulant {
					case 1:
						psm.MedicineId = "3"

						break
					case 2:
						psm.MedicineId = "1"

						break
					case 3:
						psm.MedicineId = "2"

						break
					case 4:
						psm.MedicineId = "5"

						break
					case 5:
						psm.MedicineId = "4"

						break
					}

					hdPsMedicine = append(hdPsMedicine, psm)
				}

				for _, item := range hdPsMedicine {
					service.XTWriteDB().Model(&sz.TempHdPsMedicine{}).Create(item)
				}

				upload := &sz.DataUpload{
					ModuleType:   7,
					OrgId:        config.OrgId,
					UploadDate:   time.Now().Unix(),
					UploadStatus: 1,
					UploadType:   1,
				}
				err := service.CreateUploadRecord(upload)
				if err != nil {
					utils.ErrorLog("%v", err)
				}
			}
		}
		//
		//	//排班
		record, err_eight := service.FindDataUploadOrgInfo(config.OrgId, 8)
		if err_eight == gorm.ErrRecordNotFound {
			if GetDiffDay(config) <= 0 {

				var hdShift []*sz.TempHdShift
				schs, _ := service.FindOrgScheduleData(config.OrgId, 0, 0)

				for _, sch := range schs {

					shift := &sz.TempHdShift{
						PsId:           strconv.FormatInt(sch.ID, 10),
						HospitalId:     strconv.FormatInt(sch.UserOrgId, 10),
						PatientNk:      strconv.FormatInt(sch.PatientId, 10),
						ScheduleDate:   time.Unix(sch.ScheduleDate, 0),
						ShiftType:      strconv.FormatInt(sch.ScheduleType, 10),
						SickbedNo:      sch.DeviceNumber.Number,
						ScheduleStatus: "1",
						CreateTime:     time.Now(),
						Sjscsj:         time.Now(),
						Xgbz:           0,
					}

					hdShift = append(hdShift, shift)

				}

				for _, item := range hdShift {
					service.XTWriteDB().Model(&sz.TempHdShift{}).Create(item)
				}

				upload := &sz.DataUpload{
					ModuleType:   8,
					OrgId:        config.OrgId,
					UploadDate:   time.Now().Unix(),
					UploadStatus: 1,
					UploadType:   1,
				}
				err := service.CreateUploadRecord(upload)
				if err != nil {
					utils.ErrorLog("%v", err)
				}
			}

		} else if err_eight == nil {
			if GetDiffDay2(config, record) <= 0 {

				var hdShift []*sz.TempHdShift
				schs, _ := service.FindOrgScheduleData(record.OrgId, record.UploadDate, time.Now().Unix())

				for _, sch := range schs {

					shift := &sz.TempHdShift{
						PsId:           strconv.FormatInt(sch.ID, 10),
						HospitalId:     strconv.FormatInt(sch.UserOrgId, 10),
						PatientNk:      strconv.FormatInt(sch.PatientId, 10),
						ScheduleDate:   time.Unix(sch.ScheduleDate, 0),
						ShiftType:      strconv.FormatInt(sch.ScheduleType, 10),
						SickbedNo:      sch.DeviceNumber.Number,
						ScheduleStatus: "1",
						CreateTime:     time.Now(),
						Sjscsj:         time.Now(),
						Xgbz:           0,
					}

					hdShift = append(hdShift, shift)

				}

				for _, item := range hdShift {
					service.XTWriteDB().Model(&sz.TempHdShift{}).Create(item)
				}

				upload := &sz.DataUpload{
					ModuleType:   8,
					OrgId:        config.OrgId,
					UploadDate:   time.Now().Unix(),
					UploadStatus: 1,
					UploadType:   1,
				}
				err := service.CreateUploadRecord(upload)
				if err != nil {
					utils.ErrorLog("%v", err)
				}
			}

		}
		//
		record, err_nine := service.FindDataUploadOrgInfo(config.OrgId, 9)
		if err_nine == gorm.ErrRecordNotFound {

			if GetDiffDay(config) <= 0 {

				var hdDoctorAdvices []*sz.TempHdDoctorsAdvice
				dialysisPrescriptions, _ := service.FindOrgDialysisPrescriptionData(or, 0, 0)

				for _, dp := range dialysisPrescriptions {

					advice := &sz.TempHdDoctorsAdvice{
						MedicalOrDerId:   strconv.FormatInt(dp.ID, 10),
						HospitalId:       strconv.FormatInt(dp.UserOrgId, 10),
						DialysisId:       strconv.FormatInt(dp.DialysisOrder.ID, 10),
						OrderType:        "1",
						PatientNk:        strconv.FormatInt(dp.PatientId, 10),
						DialysisDuration: dp.DialysisDurationHour*60 + dp.DialysisDurationMinute,
						BloodVol:         int64(math.Floor(dp.BloodFlowVolume + 0/5)),
						CreateTime:       time.Now(),
						Sjscsj:           time.Now(),
						Xgbz:             0,
					}

					hdDoctorAdvices = append(hdDoctorAdvices, advice)

				}

				for _, item := range hdDoctorAdvices {
					service.XTWriteDB().Model(&sz.TempHdDoctorsAdvice{}).Create(item)
				}

				upload := &sz.DataUpload{
					ModuleType:   9,
					OrgId:        config.OrgId,
					UploadDate:   time.Now().Unix(),
					UploadStatus: 1,
					UploadType:   1,
				}
				err := service.CreateUploadRecord(upload)
				if err != nil {
					utils.ErrorLog("%v", err)
				}
			}

		} else if err_nine == nil {
			if GetDiffDay2(config, record) <= 0 {

				var hdDoctorAdvices []*sz.TempHdDoctorsAdvice
				dialysisPrescriptions, _ := service.FindOrgDialysisPrescriptionData(record.OrgId, record.UploadDate, time.Now().Unix())
				for _, dp := range dialysisPrescriptions {
					advice := &sz.TempHdDoctorsAdvice{
						MedicalOrDerId:   strconv.FormatInt(dp.ID, 10),
						HospitalId:       strconv.FormatInt(dp.UserOrgId, 10),
						DialysisId:       strconv.FormatInt(dp.DialysisOrder.ID, 10),
						OrderType:        "1",
						PatientNk:        strconv.FormatInt(dp.PatientId, 10),
						DialysisDuration: dp.DialysisDurationHour*60 + dp.DialysisDurationMinute,
						BloodVol:         int64(math.Floor(dp.BloodFlowVolume + 0/5)),
						CreateTime:       time.Now(),
						Sjscsj:           time.Now(),
						Xgbz:             0,
					}
					hdDoctorAdvices = append(hdDoctorAdvices, advice)
				}
				for _, item := range hdDoctorAdvices {
					service.XTWriteDB().Model(&sz.TempHdDoctorsAdvice{}).Create(item)
				}

				upload := &sz.DataUpload{
					ModuleType:   9,
					OrgId:        config.OrgId,
					UploadDate:   time.Now().Unix(),
					UploadStatus: 1,
					UploadType:   1,
				}
				err := service.CreateUploadRecord(upload)
				if err != nil {
					utils.ErrorLog("%v", err)
				}
			}
		}
		//
		record, err_ten := service.FindDataUploadOrgInfo(config.OrgId, 10)
		fmt.Println(err_ten)
		fmt.Println(record)

		if err_ten == gorm.ErrRecordNotFound {
			if GetDiffDay(config) <= 0 {

				var hdDialysis []*sz.TempHdDialysis
				schs, erra := service.FindOrgDialysisData(config.OrgId, 0, 0)
				fmt.Println(schs)
				fmt.Println(erra)

				for _, sch := range schs {

					dialysis := &sz.TempHdDialysis{
						PsId:       strconv.FormatInt(sch.ID, 10),
						HospitalId: strconv.FormatInt(sch.UserOrgId, 10),

						SickbedNo:    sch.DeviceNumber.Number,
						DivisionId:   strconv.FormatInt(sch.DeviceNumber.ZoneId, 10),
						Ufv:          int64(math.Floor(sch.VMDialysisPrescription.Ultrafiltration + 0/5)),
						TotalReplace: int64(math.Floor(sch.VMDialysisPrescription.ReplacementTotal + 0/5)),
						BeforeWeight: sch.AssessmentBeforeDislysis.WeighingBefore,

						PatientNk:  strconv.FormatInt(sch.PatientId, 10),
						CreateTime: time.Now(),
						Sjscsj:     time.Now(),
						Xgbz:       0,
					}

					if sch.DialysisOrder.ID > 0 {
						dialysis.DialysisId = strconv.FormatInt(sch.DialysisOrder.ID, 10)
						dialysis.DialysisDate = time.Unix(sch.DialysisOrder.DialysisDate, 0)
						if sch.DialysisOrder.StartTime > 0 {
							dialysis.StartTime = time.Unix(sch.DialysisOrder.StartTime, 0)

						}

						if sch.DialysisOrder.EndTime > 0 {
							dialysis.EndTime = time.Unix(sch.DialysisOrder.EndTime, 0)

						}
					}

					if len(sch.MonitoringRecord) > 0 {
						dialysis.BeforeDbp = int64(math.Floor(sch.MonitoringRecord[0].DiastolicBloodPressure + 0/5))
						dialysis.BeforeSbp = int64(math.Floor(sch.MonitoringRecord[0].SystolicBloodPressure + 0/5))
						dialysis.AfterDbp = int64(math.Floor(sch.MonitoringRecord[len(sch.MonitoringRecord)-1].DiastolicBloodPressure + 0/5))
						dialysis.AfterSbp = int64(math.Floor(sch.MonitoringRecord[len(sch.MonitoringRecord)-1].SystolicBloodPressure + 0/5))

					}

					hdDialysis = append(hdDialysis, dialysis)

				}

				for _, item := range hdDialysis {
					service.XTWriteDB().Model(&sz.TempHdDialysis{}).Create(item)
				}

				upload := &sz.DataUpload{
					ModuleType:   10,
					OrgId:        config.OrgId,
					UploadDate:   time.Now().Unix(),
					UploadStatus: 1,
					UploadType:   1,
				}
				err := service.CreateUploadRecord(upload)
				if err != nil {
					utils.ErrorLog("%v", err)
				}
			}

		} else if err_ten == nil {
			if GetDiffDay2(config, record) <= 0 {

				var hdDialysis []*sz.TempHdDialysis
				schs, _ := service.FindOrgDialysisData(record.OrgId, record.UploadDate, time.Now().Unix())
				for _, sch := range schs {
					dialysis := &sz.TempHdDialysis{
						PsId:         strconv.FormatInt(sch.ID, 10),
						HospitalId:   strconv.FormatInt(sch.UserOrgId, 10),
						DialysisId:   strconv.FormatInt(sch.DialysisOrder.ID, 10),
						DialysisDate: time.Unix(sch.DialysisOrder.DialysisDate, 0),
						SickbedNo:    sch.DeviceNumber.Number,
						DivisionId:   strconv.FormatInt(sch.DeviceNumber.ZoneId, 10),
						Ufv:          int64(math.Floor(sch.VMDialysisPrescription.Ultrafiltration + 0/5)),
						TotalReplace: int64(math.Floor(sch.VMDialysisPrescription.ReplacementTotal + 0/5)),
						BeforeDbp:    int64(math.Floor(sch.MonitoringRecord[0].DiastolicBloodPressure + 0/5)),
						BeforeSbp:    int64(math.Floor(sch.MonitoringRecord[0].SystolicBloodPressure + 0/5)),
						AfterDbp:     int64(math.Floor(sch.MonitoringRecord[len(sch.MonitoringRecord)].DiastolicBloodPressure + 0/5)),
						AfterSbp:     int64(math.Floor(sch.MonitoringRecord[len(sch.MonitoringRecord)].SystolicBloodPressure + 0/5)),
						BeforeWeight: sch.AssessmentBeforeDislysis.WeighingBefore,
						StartTime:    time.Unix(sch.DialysisOrder.StartTime, 0),
						EndTime:      time.Unix(sch.DialysisOrder.EndTime, 0),
						PatientNk:    strconv.FormatInt(sch.PatientId, 10),
						CreateTime:   time.Now(),
						Sjscsj:       time.Now(),
						Xgbz:         0,
					}

					hdDialysis = append(hdDialysis, dialysis)

				}

				for _, item := range hdDialysis {
					service.XTWriteDB().Model(&sz.TempHdDialysis{}).Create(item)
				}

				upload := &sz.DataUpload{
					ModuleType:   10,
					OrgId:        config.OrgId,
					UploadDate:   time.Now().Unix(),
					UploadStatus: 1,
					UploadType:   1,
				}
				err := service.CreateUploadRecord(upload)
				if err != nil {
					utils.ErrorLog("%v", err)
				}
			}

		}
		//
		record, err_eleven := service.FindDataUploadOrgInfo(config.OrgId, 11)
		if err_eleven == gorm.ErrRecordNotFound {
			if GetDiffDay(config) <= 0 {

				var hdMiddle []*sz.TempHdMiddle
				monitors, _ := service.FindOrgMonitorRecordData(config.OrgId, 0, 0)

				for _, item := range monitors {

					mid := &sz.TempHdMiddle{
						HospitalId:  strconv.FormatInt(item.UserOrgId, 10),
						DialysisId:  strconv.FormatInt(item.DialysisOrder.ID, 10),
						MonitorTime: time.Unix(item.OperateTime, 0),
						Sbp:         int64(math.Floor(item.SystolicBloodPressure + 0/5)),
						Dbp:         int64(math.Floor(item.DiastolicBloodPressure + 0/5)),
						PatientNk:   strconv.FormatInt(item.PatientId, 10),
						CreateTime:  time.Now(),
						Sjscsj:      time.Now(),
						Xgbz:        0,
					}

					hdMiddle = append(hdMiddle, mid)

				}

				for _, item := range hdMiddle {
					service.XTWriteDB().Model(&sz.TempHdMiddle{}).Create(item)
				}

				upload := &sz.DataUpload{
					ModuleType:   11,
					OrgId:        config.OrgId,
					UploadDate:   time.Now().Unix(),
					UploadStatus: 1,
					UploadType:   1,
				}
				err := service.CreateUploadRecord(upload)
				if err != nil {
					utils.ErrorLog("%v", err)
				}
			}

		} else if err == nil {
			if GetDiffDay2(config, record) <= 0 {

				var hdMiddle []*sz.TempHdMiddle
				monitors, _ := service.FindOrgMonitorRecordData(record.OrgId, record.UploadDate, time.Now().Unix())

				for _, item := range monitors {

					mid := &sz.TempHdMiddle{
						HospitalId:  strconv.FormatInt(item.UserOrgId, 10),
						DialysisId:  strconv.FormatInt(item.DialysisOrder.ID, 10),
						MonitorTime: time.Unix(item.OperateTime, 0),
						Sbp:         int64(math.Floor(item.SystolicBloodPressure + 0/5)),
						Dbp:         int64(math.Floor(item.DiastolicBloodPressure + 0/5)),
						PatientNk:   strconv.FormatInt(item.PatientId, 10),
						CreateTime:  time.Now(),
						Sjscsj:      time.Now(),
						Xgbz:        0,
					}

					hdMiddle = append(hdMiddle, mid)

				}

				for _, item := range hdMiddle {
					service.XTWriteDB().Model(&sz.TempHdMiddle{}).Create(item)
				}

				upload := &sz.DataUpload{
					ModuleType:   11,
					OrgId:        config.OrgId,
					UploadDate:   time.Now().Unix(),
					UploadStatus: 1,
					UploadType:   1,
				}
				err := service.CreateUploadRecord(upload)
				if err != nil {
					utils.ErrorLog("%v", err)
				}
			}
		}
		//
		record, err_twelve := service.FindDataUploadOrgInfo(config.OrgId, 12)
		if err_twelve == gorm.ErrRecordNotFound {
			if GetDiffDay(config) <= 0 {

				var divisions []*sz.TempHdDivision
				zones, _ := service.FindOrgDeviceZoneRecordData(config.OrgId, 0, 0)

				for _, item := range zones {
					nowTime := time.Now()
					div := &sz.TempHdDivision{
						DivisionId:   strconv.FormatInt(item.ID, 10),
						HospitalId:   strconv.FormatInt(item.OrgId, 10),
						DevisionName: item.Name,
						CreateTime:   nowTime,
						UpdateTime:   nowTime,
						UpdateFlag:   strconv.FormatInt(0, 10),
						Sjscsj:       time.Now(),
						Xgbz:         0,
					}

					divisions = append(divisions, div)

				}

				for _, item := range divisions {
					service.XTWriteDB().Model(&sz.TempHdDivision{}).Create(item)
				}

				upload := &sz.DataUpload{
					ModuleType:   12,
					OrgId:        config.OrgId,
					UploadDate:   time.Now().Unix(),
					UploadStatus: 1,
					UploadType:   1,
				}
				err := service.CreateUploadRecord(upload)
				if err != nil {
					utils.ErrorLog("%v", err)
				}
			}

		} else if err_twelve == nil {
			if GetDiffDay2(config, record) <= 0 {

				var divisions []*sz.TempHdDivision
				zones, _ := service.FindOrgDeviceZoneRecordData(record.OrgId, record.UploadDate, time.Now().Unix())

				for _, item := range zones {
					nowTime := time.Now()
					div := &sz.TempHdDivision{
						DivisionId:   strconv.FormatInt(item.ID, 10),
						HospitalId:   strconv.FormatInt(item.OrgId, 10),
						DevisionName: item.Name,
						CreateTime:   nowTime,
						UpdateTime:   nowTime,
						UpdateFlag:   strconv.FormatInt(0, 10),
						Sjscsj:       time.Now(),
						Xgbz:         0,
					}
					divisions = append(divisions, div)
				}

				for _, item := range divisions {
					service.XTWriteDB().Model(&sz.TempHdDivision{}).Create(item)
				}

				upload := &sz.DataUpload{
					ModuleType:   12,
					OrgId:        config.OrgId,
					UploadDate:   time.Now().Unix(),
					UploadStatus: 1,
					UploadType:   1,
				}
				err := service.CreateUploadRecord(upload)
				if err != nil {
					utils.ErrorLog("%v", err)
				}
			}

		}
		//
	}

}

func Substr(str string, start, length int) string {
	rs := []rune(str)
	rl := len(rs)
	end := 0
	if start < 0 {
		start = rl - 1 + start
	}
	end = start + length
	if start > end {
		start, end = end, start
	}
	if start < 0 {
		start = 0
	}
	if start > rl {
		start = rl
	}
	if end < 0 {
		end = 0
	}
	if end > rl {
		end = rl
	}
	return string(rs[start:end])

}

//没有上报数据记录的时候，使用配置创建时间来计算上报时间
func GetDiffDay(config *sz.DataUploadConfig) float64 {
	var diffDay float64
	switch config.TimeQuantum {
	case 1:
		tm := time.Unix(config.CreateTime, 0)
		dateStr := tm.Format("2006-1-2") + " 00:00:00"
		date, _ := time.Parse("2006-1-2 15:04:05", dateStr)
		year, month, day := date.Date()
		endTime := time.Date(year, month, day+7, 0, 0, 0, 0, time.Local)
		years, months, days := time.Now().Date()
		todayTime := time.Date(years, months, days, 0, 0, 0, 0, time.Local)
		diffDay = endTime.Sub(todayTime).Hours() / 24

		break
	case 2:
		tm := time.Unix(config.CreateTime, 0)
		dateStr := tm.Format("2006-1-2") + " 00:00:00"
		date, _ := time.Parse("2006-1-2 15:04:05", dateStr)
		year, month, day := date.Date()
		endTime := time.Date(year, month, day+14, 0, 0, 0, 0, time.Local)
		years, months, days := time.Now().Date()
		todayTime := time.Date(years, months, days, 0, 0, 0, 0, time.Local)
		diffDay = endTime.Sub(todayTime).Hours() / 24

		break
	case 3:
		tm := time.Unix(config.CreateTime, 0)
		dateStr := tm.Format("2006-1-2") + " 00:00:00"
		date, _ := time.Parse("2006-1-2 15:04:05", dateStr)
		year, month, day := date.Date()
		endTime := time.Date(year, month+1, day, 0, 0, 0, 0, time.Local)
		years, months, days := time.Now().Date()
		todayTime := time.Date(years, months, days, 0, 0, 0, 0, time.Local)
		diffDay = endTime.Sub(todayTime).Hours() / 24

		break
	case 4:
		tm := time.Unix(config.CreateTime, 0)
		dateStr := tm.Format("2006-1-2") + " 00:00:00"
		date, _ := time.Parse("2006-1-2 15:04:05", dateStr)
		year, month, day := date.Date()
		endTime := time.Date(year, month+3, day, 0, 0, 0, 0, time.Local)
		years, months, days := time.Now().Date()
		todayTime := time.Date(years, months, days, 0, 0, 0, 0, time.Local)
		diffDay = endTime.Sub(todayTime).Hours() / 24

		break
	}

	return diffDay

}

//有上报数据记录的时候，使用上报时间来计算下次上报时间
func GetDiffDay2(config *sz.DataUploadConfig, updateDate sz.DataUpload) float64 {
	var diffDay float64
	switch config.TimeQuantum {
	case 1:
		tm := time.Unix(updateDate.UploadDate, 0)
		dateStr := tm.Format("2006-1-2") + " 00:00:00"
		date, _ := time.Parse("2006-1-2 15:04:05", dateStr)
		year, month, day := date.Date()
		endTime := time.Date(year, month, day+7, 0, 0, 0, 0, time.Local)
		years, months, days := time.Now().Date()
		todayTime := time.Date(years, months, days, 0, 0, 0, 0, time.Local)
		diffDay = endTime.Sub(todayTime).Hours() / 24 //透析日期1年与当前天数差

		break
	case 2:
		tm := time.Unix(updateDate.UploadDate, 0)
		dateStr := tm.Format("2006-1-2") + " 00:00:00"
		date, _ := time.Parse("2006-1-2 15:04:05", dateStr)
		year, month, day := date.Date()
		endTime := time.Date(year, month, day+14, 0, 0, 0, 0, time.Local)
		years, months, days := time.Now().Date()
		todayTime := time.Date(years, months, days, 0, 0, 0, 0, time.Local)
		diffDay = endTime.Sub(todayTime).Hours() / 24 //透析日期1年与当前天数差

		break
	case 3:
		tm := time.Unix(updateDate.UploadDate, 0)
		dateStr := tm.Format("2006-1-2") + " 00:00:00"
		date, _ := time.Parse("2006-1-2 15:04:05", dateStr)
		year, month, day := date.Date()
		endTime := time.Date(year, month+1, day, 0, 0, 0, 0, time.Local)
		years, months, days := time.Now().Date()
		todayTime := time.Date(years, months, days, 0, 0, 0, 0, time.Local)
		diffDay = endTime.Sub(todayTime).Hours() / 24 //透析日期1年与当前天数差

		break
	case 4:
		tm := time.Unix(updateDate.UploadDate, 0)
		dateStr := tm.Format("2006-1-2") + " 00:00:00"
		date, _ := time.Parse("2006-1-2 15:04:05", dateStr)
		year, month, day := date.Date()
		endTime := time.Date(year, month+3, day, 0, 0, 0, 0, time.Local)
		years, months, days := time.Now().Date()
		todayTime := time.Date(years, months, days, 0, 0, 0, 0, time.Local)
		diffDay = endTime.Sub(todayTime).Hours() / 24 //透析日期1年与当前天数差

		break
	}

	return diffDay

}
