package service

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

var createWeekPlanCronJob *cron.Cron

func init() {
	utils.InfoLog("第二次开启自动消毒时任务")
	spec := "0 0 22 * * ?" // 每天22点执行一次
	//spec := "0 */1 * * * ?" // 每1分钟执行一次
	createWeekPlanCronJob = cron.New()
	createWeekDisinfectionCronJob.AddFunc(spec, func() {
		AutoCreateWeekPlanJob()
	})
}

func BeginAutoCreatePlanJob() {
	createWeekPlanCronJob.Start()
}

func AutoCreateWeekPlanJob() {

	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 = "有"
				}

				//查询病人的班次
				//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)
				//			//根据床位号获取设备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 {
					//查询该病人是否有记录，无记录的则添加
					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("已关闭")
		}
	}
}
