package new_mobile_api_controllers

import (
	"Xcx_New/controllers/mobile_api_controllers"
	"Xcx_New/enums"
	"Xcx_New/models"
	"Xcx_New/service"
	"Xcx_New/utils"
	"fmt"
	"github.com/jinzhu/gorm"
	"strconv"
	"time"
)

type NewManageApiController struct {
	mobile_api_controllers.MobileBaseAPIAuthController
}

func (this *NewManageApiController) GetEquitAutoInfo() {

	adminUser := this.GetMobileAdminUserInfo()
	orgid := adminUser.Org.Id
	remander, err := service.GetRemanderData(orgid)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"remander": remander,
	})
}

func (this *NewManageApiController) GetDisInfectionTime() {
	adminUser := this.GetMobileAdminUserInfo()
	orgid := adminUser.Org.Id
	bedid, _ := this.GetInt64("bed_id")
	scheduletype, _ := this.GetInt64("schedule_type")
	scheduleweek, _ := this.GetInt64("schedule_week")
	fmt.Println(scheduleweek)
	scheduledate, _ := this.GetInt64("schedule_date")

	//根据床位号获取设备型号
	unitType, _ := service.GetUnitType(bedid, orgid)
	//查询使用登记最后一条消毒记录
	infomation, err := service.GetLaseDeviceInfomation(orgid, bedid, scheduledate, scheduletype)
	fmt.Println("err", err)
	if err == gorm.ErrRecordNotFound {
		//查询改设备是否有消毒计划
		plan, errcode := service.GetDisInfectionTime(orgid, unitType.UnitType, scheduletype, scheduleweek)
		//如果没有消毒计划，去查询该设备的上次消毒时间
		if errcode == gorm.ErrRecordNotFound {
			infor, errco := service.GetLaseDeviceInfomationTwo(orgid, bedid, scheduletype)
			if errco != nil {
				this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
				return
			}
			this.ServeSuccessJSON(map[string]interface{}{
				"plan": infor.LongTime,
			})
		} else if errcode == nil {
			this.ServeSuccessJSON(map[string]interface{}{
				"plan": plan.DisinfecTime,
			})
		}
	} else if err == nil {
		this.ServeSuccessJSON(map[string]interface{}{
			"plan":       infomation.LongTime,
			"infomation": infomation,
		})
	}
	//查询改设备是否有消毒计划
	//plan, err := service.GetDisInfectionTime(orgid, bedid, scheduletype, scheduleweek)
	//if err == gorm.ErrRecordNotFound {
	//	//去查询使用登记最后一条数据
	//	infomation, err := service.GetLaseDeviceInfomation(orgid, bedid)
	//	if err != nil {
	//		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	//		return
	//	}
	//	this.ServeSuccessJSON(map[string]interface{}{
	//		"plan": infomation.LongTime,
	//	})
	//} else if err == nil {
	//	if err != nil {
	//		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	//		return
	//	}
	//	this.ServeSuccessJSON(map[string]interface{}{
	//		"plan": plan.DisinfecTime,
	//	})
	//} else {
	//
	//}

}

func (this *NewManageApiController) SaveDisInfectionInfo() {
	adminUser := this.GetMobileAdminUserInfo()
	orgid := adminUser.Org.Id
	bedid, _ := this.GetInt64("bed_id")
	start_time := this.GetString("start_time")
	startdate, _ := utils.ParseTimeStringToTime("2006-01-02 15:04", start_time)
	startdateunix := startdate.Unix()
	disinfectime, _ := this.GetInt64("disinfec_time")
	endtime := this.GetString("end_time")
	enddate, _ := utils.ParseTimeStringToTime("2006-01-02 15:04", endtime)
	enddateunix := enddate.Unix()
	scheduledate, _ := this.GetInt64("schedule_date")
	zoneid, _ := this.GetInt64("zone_id")
	patientid, _ := this.GetInt64("patient_id")
	modeid, _ := this.GetInt64("mode_id")
	scheduletype, _ := this.GetInt64("schedule_type")

	//查询病人信息
	patients, _ := service.GetPatientInfoMation(patientid)
	var con = ""
	if patients.IsInfectious == 0 {
		con = ""
	}
	if patients.IsInfectious == 1 {
		con = "无"
	}
	if patients.IsInfectious == 2 {
		con = "有"
	}
	//查询病人上机信息
	order, _ := service.GetPatientOrderInfo(scheduledate, patientid, orgid)
	//查询病人今日透后评估数据
	dislysis, _ := service.GetAssessmentAfterDissDataTwo(patientid, orgid, scheduledate)
	fmt.Println("透析减少", dislysis.WeightLoss)
	//			//根据床位号获取设备id
	addmacher, _ := service.GetEquimentIDTwo(bedid, orgid)
	//unitype, _ := strconv.ParseInt(addmacher.UnitType, 10, 64)
	//fmt.Println(unitype)
	plan, errplan := service.GetDisinfectionTwo(addmacher.UnitType, scheduletype, orgid)
	//counts, errplan := service.GetUserTotalCount(orgid, bedid)
	//var usertoal  int64
	//fmt.Println(usertoal)
	//for index, count := range counts {
	//   if(index == 0){
	//      usertoal = count.Total
	//   }
	//}
	//usertotalint, errplan := strconv.ParseInt(addmacher.UserTotal, 10, 64)
	//var total = usertoal + usertotalint
	//totals := strconv.FormatInt(total, 10)
	if errplan == gorm.ErrRecordNotFound {
		returnData := make(map[string]interface{}, 0)
		returnData["msstatus"] = "2"
		this.ServeSuccessJSON(returnData)
		return
	} else {
		_, errcode := service.GetInforTwo(patientid, scheduledate, orgid, scheduletype)
		if errcode == gorm.ErrRecordNotFound {
			information := models.DeviceInformation{
				Date:                  scheduledate,
				Zone:                  zoneid,
				Class:                 scheduletype,
				BedNumber:             bedid,
				PatientId:             patientid,
				DialysisMode:          modeid,
				LongTime:              strconv.FormatInt(disinfectime, 10),
				Disinfection:          1,
				DialysisConcentration: 1,
				DisinfectionStatus:    1,
				Move:                  1,
				UserOrgId:             orgid,
				DisinfectType:         plan.Way,
				DisinfectantType:      plan.MachineDisinfectant,
				FluidPath:             plan.DisinfectanWay, //液路消毒方式
				Disinfectant:          plan.Disinfectant,
				Ctime:                 time.Now().Unix(),
				Status:                1,
				SignName:              order.FinishNurse,
				EquimentId:            addmacher.ID,
				DisinfectionResidue:   2,
				Bed:                   addmacher.BedNumber,
				StartTime:             order.StartTime,
				EndTime:               order.EndTime,
				Contagion:             con,
				WeightLoss:            dislysis.WeightLoss,
				Hyperfiltratio:        dislysis.ActualUltrafiltration,
				DialysisHour:          strconv.FormatInt(dislysis.ActualTreatmentHour, 10),
				MachineRun:            1,
				DisinfecStartime:      startdateunix,
				DisinfecEndtime:       enddateunix,
			}
			err := service.CreateInformationTwo(&information)
			fmt.Println("报错", err)
			if err != nil {
				this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
				return
			}
			this.ServeSuccessJSON(map[string]interface{}{
				"information": information,
			})
		} else if errcode == nil {
			information := models.DeviceInformation{
				DisinfecStartime: startdateunix,
				DisinfecEndtime:  enddateunix,
				LongTime:         strconv.FormatInt(disinfectime, 10),
			}

			errcode := service.UpdateInformation(&information, scheduledate, bedid, scheduletype)
			if errcode != nil {
				this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
				return
			}
			this.ServeSuccessJSON(map[string]interface{}{
				"information": information,
			})
		} else {
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
			return
		}
	}
}

func (this *NewManageApiController) GetDeviceInformation() {

	adminUser := this.GetMobileAdminUserInfo()
	orgid := adminUser.Org.Id

	scheduleDate := this.GetString("schedule_date")
	recordDate, parseErr := utils.ParseTimeStringToTime("2006-01-02", scheduleDate)
	if parseErr != nil {
		this.ErrorLog("时间解析失败:%v", parseErr)
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	fmt.Println("recordDate2222222", recordDate.Unix())
	//查询今日所有设备使用登记
	information, err := service.GetDeviceInfomation(orgid, recordDate.Unix())
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"information": information,
	})
}
