package service

import (
	"XT_New/models"
	"XT_New/utils"
	"fmt"
	"github.com/jinzhu/gorm"
	"github.com/robfig/cron"
	"strconv"
	"time"
)

// cron表达式 https://www.cnblogs.com/zuxingyu/p/6023919.html
var createWeekDisinfectionCronJob *cron.Cron

func init() {
	createWeekDisinfectionCronJob = cron.New()
	//spec := "0 0 23 * * ?" // 每天23点执行一次
	spec := "0 55 23 * * ?" // 每天23点55执行一次
	//spec := "0 0 5 * * ?" // 每天23点55执行一次
	//spec := "0 */1 * * * ?" // 每1分钟执行一次
	createWeekDisinfectionCronJob.AddFunc(spec, func() {

		AutoCreateWeekDisinfectionJob()
	})
}

func BeginAutoCreateWeekDisinfectionJob() {

	createWeekDisinfectionCronJob.Start()
}

func AutoCreateWeekDisinfectionJob() {
	timeStr := time.Now().Format("2006-01-02")
	timeLayout := "2006-01-02 15:04:05"
	fmt.Println("timeStr:", timeStr)
	timeStringToTime, _ := utils.ParseTimeStringToTime(timeLayout, timeStr+" 00:00:00")
	timenow := timeStringToTime.Unix()
	fmt.Println("timenow是什么", timenow)
	//查询当天排班所有机构
	org, errs := GetAllOrgID(timenow)
	fmt.Print("错误是什么", errs)
	//fmt.Println("查询有机构失败", err)
	for _, item := range org {
		//查询机构是否开启自动使用登记
		remander, errs := GetRemanderDatas(item.UserOrgId)
		fmt.Print("查询自动使用登记错误", errs)
		//开启
		if remander.IsRun == 1 {
			fmt.Println("机构id", item.UserOrgId)
			//查询当天机构的所有下机病人id
			order, _ := GetAllPatientByOrgID(item.UserOrgId, timenow)
			for _, it := range order {
				//fmt.Println("病人", it.PatientId)

				//查询病人信息
				patients, err := GetPatientInformation(it.PatientId, it.UserOrgId)
				fmt.Println("查询病人信息报错", err)
				var con = ""
				if patients.IsInfectious == 0 {
					con = ""
				}
				if patients.IsInfectious == 1 {
					con = "无"
				}
				if patients.IsInfectious == 2 {
					con = "有"
				}
				//fmt.Print("con------------------------", con)
				//	fmt.Print("传染病", patients.IsInfectious)
				//查询病人的班次
				//schedules, _ := GetAllPatientSchedule(it.PatientId, it.UserOrgId,timenow)
				schedules, _ := GetAllPatientSchedule(it.PatientId, it.UserOrgId, timenow)
				fmt.Println("班次", schedules.ScheduleType)
				//查询病人今日的透析模式
				prescription, _ := GetDialysisPrescription(it.PatientId, it.UserOrgId, timenow)
				fmt.Println("透析模式", prescription.ModeId)

				//查询病人今日透后评估数据
				dislysis, err := GetAssessmentAfterDissData(it.PatientId, it.UserOrgId, timenow)
				fmt.Println("透后评估错误", err)
				fmt.Print("透析时长", dislysis.ActualTreatmentHour+'h'+dislysis.ActualTreatmentMinute+'m'+'i'+'n')
				//			//根据床位号获取设备id
				addmacher, _ := GetEquimentID(schedules.BedId, it.UserOrgId)
				unitype, err := strconv.ParseInt(addmacher.UnitType, 10, 64)
				fmt.Println(" 设备id", addmacher.ID)
				//根据设备id获取设备类型
				//equimentname, _ := GetAddmacher(addmacher.ID, it.UserOrgId)

				fmt.Println("班次", it.SchedualType)
				//查看该设备是否有消毒计划，无怎返回,有则添加
				plan, errplan := GetDisinfection(unitype, it.SchedualType, it.UserOrgId)
				fmt.Print("plan", plan)
				fmt.Println("错误是什么", errplan)
				if errplan == gorm.ErrRecordNotFound {
					fmt.Println("该设备无消毒计划")
					return
				} else if errplan == nil {
					//fmt.Println("消毒时长", plan.DisinfecTime)
					//fmt.Println("基表消毒方式", plan.Way)
					//fmt.Println("基表消毒液", plan.MachineDisinfectant)
					//fmt.Println("液路消毒方式", plan.DisinfectanWay)
					//fmt.Println("液路消毒液", plan.Disinfectant)
					//fmt.Println("上机时间", it.StartTime)
					//fmt.Println("下机时间", it.EndTime)
					//fmt.Println("传染病", con)
					//fmt.Println("体重减少", strconv.FormatFloat(dislysis.WeightLoss, 'f', -1, 64))
					//fmt.Println("时间超滤量", strconv.FormatFloat(dislysis.ActualUltrafiltration, 'f', -1, 64))
					//fmt.Println("透析时长", strconv.FormatInt(dislysis.ActualTreatmentHour, 10))
					//查询该病人是否有记录，无记录的则添加
					information, errcode := GetInfor(it.PatientId, timenow, it.UserOrgId, it.SchedualType)
					//fmt.Println("errcode是什么", errcode)
					fmt.Println("information", information)
					if errcode == gorm.ErrRecordNotFound {
						information := models.DeviceInformation{
							Date:                  timenow,
							Zone:                  schedules.PartitionId,
							Class:                 it.SchedualType,
							BedNumber:             schedules.BedId,
							PatientId:             schedules.PatientId,
							DialysisMode:          prescription.ModeId,
							LongTime:              strconv.FormatInt(plan.DisinfecTime, 10),
							Disinfection:          1,
							DialysisConcentration: 1,
							DisinfectionStatus:    1,
							Move:                  1,
							UserOrgId:             it.UserOrgId,
							DisinfectType:         plan.Way,                 //基表消毒方式
							DisinfectantType:      plan.MachineDisinfectant, //基表消毒液
							FluidPath:             plan.DisinfectanWay,      //液路消毒方式
							Disinfectant:          plan.Disinfectant,        //液路消毒液
							Ctime:                 time.Now().Unix(),
							Status:                1,
							SignName:              it.FinishNurse,
							EquimentId:            addmacher.ID,
							DisinfectionResidue:   2,
							Bed:                   addmacher.BedNumber,
							StartTime:             it.StartTime,
							EndTime:               it.EndTime,
							Contagion:             con,
							WeightLoss:            strconv.FormatFloat(dislysis.WeightLoss, 'f', -1, 64),
							Hyperfiltratio:        strconv.FormatFloat(dislysis.ActualUltrafiltration, 'f', -1, 64),
							DialysisHour:          strconv.FormatInt(dislysis.ActualTreatmentHour, 10),
							MachineRun:            1,
						}
						err := CreateInformation(&information)
						fmt.Println("报错", err)
					} else if errcode == nil {

					} else {

					}
				} else {

					return
				}
			}
		}

		//关闭
		if remander.IsRun == 2 {
			fmt.Print("已关闭")
		}
	}

}

//
//func GetAllOrgID(status int64) (org []*models.Org, err error) {
//
//	err = UserReadDB().Where("status = ?", status).Find(&org).Error
//
//	return org, err
//}

//查询当天有排班的所有机构
func GetAllOrgID(time int64) (schedule []*models.XtSchedule, err error) {

	err = XTReadDB().Raw("select user_org_id,id,partition_id,bed_id,patient_id,schedule_date,schedule_type,schedule_week,mode_id from xt_schedule where schedule_date = ?  group by user_org_id", time).Scan(&schedule).Error

	return schedule, err
}

func GetAllPatientByOrgID(orgid int64, timenow int64) (order []*models.DialysisOrder, err error) {

	err = XTReadDB().Where("user_org_id = ? AND dialysis_date = ? AND stage = 2 AND status = ?", orgid, timenow, 1).Find(&order).Error
	return order, err
}

func CreateInformation(information *models.DeviceInformation) error {
	err := UserWriteDB().Create(&information).Error
	return err
}

func GetAllPatientSchedule(patientid int64, orgID int64, timenow int64) (models.Schedule, error) {
	schedules := models.Schedule{}
	err := XTReadDB().Where("patient_id = ? AND user_org_id = ? AND schedule_date = ?", patientid, orgID, timenow).Find(&schedules).Error
	return schedules, err
}

func GetInfor(patientid int64, timenow int64, orgid int64, class int64) (*models.DeviceInformation, error) {
	var pre models.DeviceInformation
	var err error
	err = readUserDb.Model(&pre).Where("patient_id = ? AND date = ? AND user_org_id = ? AND class = ? AND status = 1", patientid, timenow, orgid, class).Find(&pre).Error
	if err == gorm.ErrRecordNotFound {
		return nil, err
	}
	if err != nil {
		return nil, err
	}
	return &pre, nil
}

func GetDisinfection(equitType int64, enquitType int64, orgID int64) (*models.DevicePlan, error) {
	var plan models.DevicePlan
	var err error
	err = readUserDb.Model(&plan).Where("device_type = ? AND classtime = ? AND user_org_id = ? AND status = 1", equitType, enquitType, orgID).Find(&plan).Error
	if err == gorm.ErrRecordNotFound {
		return nil, err
	}
	if err != nil {
		return nil, err
	}
	return &plan, nil
}

func GetDialysisPrescription(patientid int64, orgID int64, timenow int64) (models.DialysisPrescription, error) {
	prescription := models.DialysisPrescription{}
	err := XTReadDB().Model(&prescription).Where("patient_id = ? AND user_org_id = ? AND record_date = ?", patientid, orgID, timenow).Find(&prescription).Error
	return prescription, err
}

func GetAssessmentAfterDissData(patientid int64, orgID int64, timenow int64) (models.XtAssessmentAfterDislysis, error) {
	dislysis := models.XtAssessmentAfterDislysis{}
	err := XTReadDB().Where("patient_id = ? AND user_org_id = ? AND assessment_date = ?", patientid, orgID, timenow).Find(&dislysis).Error
	return dislysis, err
}

func GetEquimentID(bedId int64, orgID int64) (models.DeviceAddmacher, error) {
	addmacher := models.DeviceAddmacher{}
	err := readUserDb.Model(&addmacher).Where("bed_id = ? AND user_org_id = ? AND status = ?", bedId, orgID, 1).Find(&addmacher).Error
	return addmacher, err
}

func GetAddmacher(equitmentid int64, orgid int64) (models.DeviceEquimentname, error) {
	equimentname := models.DeviceEquimentname{}
	err := readUserDb.Model(&equimentname).Where("equitment_id = ? AND user_org_id = ? AND status = 1", equitmentid, orgid).Find(&equimentname).Error
	return equimentname, err
}

func GetPatientInformation(id int64, orgid int64) (models.Patients, error) {
	patients := models.Patients{}
	err := XTReadDB().Where("id = ? AND user_org_id = ?", id, orgid).Find(&patients).Error
	return patients, err
}

func GetRemanderDatas(orgid int64) (remander models.DeviceRemander, err error) {

	err = UserReadDB().Model(&models.DeviceRemander{}).Where("user_org_id = ? and status = 1", orgid).Find(&remander).Error
	return
}
