package service

import (
	"XT_New/models"
	"fmt"
	"github.com/jinzhu/gorm"
	"strings"
	"time"
)

//////// 设备基本信息

func GetValidDevicesBy(orgID int64, deviceType int, zoneID int64) ([]*models.Device, error) {
	var devices []*models.Device
	db := readDb.Model(&models.Device{}).Where("org_id = ? AND status = 1", orgID)
	if deviceType != 0 {
		db = db.Where("device_type = ?", deviceType)
	}
	if zoneID != 0 {
		db = db.Where("device_zone_id = ?", zoneID)
	}
	err := db.Find(&devices).Error
	if err != nil {
		return nil, err
	}
	return devices, nil
}

// 根据设备关联表的 id，获取设备关联信息
func GetDeviceByID(orgID int64, deviceID int64) (*models.Device, error) {
	var device models.Device
	err := readDb.Model(&models.Device{}).Where("org_id = ? AND id = ?", orgID, deviceID).First(&device).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		} else {
			return nil, err
		}
	}
	return &device, nil
}

func GetDMDeviceByID(orgID int64, id int64) (*models.DeviceDM, error) {
	var device models.DeviceDM
	err := readDb.Model(&models.DeviceDM{}).Where("org_id = ? AND id = ?", orgID, id).First(&device).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		} else {
			return nil, err
		}
	}
	return &device, nil
}

func GetWTEDeviceByID(orgID int64, id int64) (*models.DeviceWTE, error) {
	var device models.DeviceWTE
	err := readDb.Model(&models.DeviceWTE{}).Where("org_id = ? AND id = ?", orgID, id).First(&device).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		} else {
			return nil, err
		}
	}
	return &device, nil
}

// type DeviceBaseInfoViewModel struct {
// 	DeviceType     int   `json:"device_type"`
// 	DeviceNumberID int64 `gorm:"column:device_number_id" json:"device_number_id"`

// 	ID                 int64  `gorm:"column:id" json:"id"`
// 	SerialNumber       string `json:"serial_number"`        // 序列号
// 	Name               string `json:"name"`                 // 设备名
// 	Manufacturer       string `json:"manufacturer"`         // 生产厂家
// 	RepairFactory      string `json:"repair_factory"`       // 维修厂家
// 	Model              string `json:"model"`                // 型号
// 	Department         string `json:"department"`           // 使用科室
// 	DepartmentNumber   string `json:"department_number"`    // 科室编号
// 	PurchaseDate       int64  `json:"purchase_date"`        // 购买日期
// 	InstallDate        int64  `json:"install_date"`         // 安装日期
// 	CommissioningDate  int64  `json:"commissioning_date"`   // 启用日期
// 	Maintainer         string `json:"maintainer"`           // 维修工程师
// 	MaintenanceCall    string `json:"maintenance_call"`     // 维修联系电话
// 	WarrantyPeriod     string `json:"warranty_period"`      // 保修期限
// 	DeviceStatus       int    `json:"device_status"`        // 机器状态 1.使用机 2.备用机 3.急诊机 4.报废机
// 	InitialUseTimes    int    `json:"initial_use_times"`    // 初始使用次数
// 	Mark               string `json:"mark"`                 // 备注
// 	RetirementDate     int64  `json:"retirement_date"`      // 报废日期
// 	RetirementReason   string `json:"retirement_reason"`    // 报废原因
// 	ServiceLife        int    `json:"service_life"`         // 使用年限
// 	WorkingTime        int    `json:"working_time"`         // 工作时长
// 	TreatmentMode      string `json:"treatment_mode"`       // 治疗模式  DeviceType = 1
// 	ReverseOsmosisMode int    `json:"reverse_osmosis_mode"` // 反渗模式  DeviceType = 2
// }

// // TODO
// func GetDeviceBaseInfoByDeviceID(deviceID int64) (*DeviceBaseInfoViewModel, error) {
// 	return nil, nil
// }

// 创建透析机
func CreateDMDevice(dmDevice *models.DeviceDM, deviceNumber *models.DeviceNumber) (*models.Device, error) {
	now := time.Now().Unix()
	dmDevice.Status = 1
	dmDevice.CreateTime = now
	dmDevice.ModifyTime = now
	tx := writeDb.Begin()
	createDMErr := tx.Model(&models.DeviceDM{}).Create(dmDevice).Error
	if createDMErr != nil {
		tx.Rollback()
		return nil, createDMErr
	}
	device := models.Device{
		OrgID:        dmDevice.OrgID,
		DeviceType:   1,
		DMID:         dmDevice.ID,
		SerialNumber: dmDevice.SerialNumber,
		Name:         dmDevice.Name,
		Model:        dmDevice.Model,
		Status:       1,
		CreateTime:   now,
		ModifyTime:   now,
	}
	if deviceNumber != nil {
		device.DeviceNumber = deviceNumber.Number
		device.DeviceNumberID = deviceNumber.ID
		device.DeviceZoneID = deviceNumber.ZoneID
		device.DeviceGroupID = deviceNumber.GroupID
	}
	createDeviceErr := tx.Model(&models.Device{}).Create(&device).Error
	if createDeviceErr != nil {
		tx.Rollback()
		return nil, createDeviceErr
	}
	tx.Commit()
	return &device, nil
}

// 创建水处理机
func CreateWTEDevice(wteDevice *models.DeviceWTE, deviceNumber *models.DeviceNumber) (*models.Device, error) {
	now := time.Now().Unix()
	wteDevice.Status = 1
	wteDevice.CreateTime = now
	wteDevice.ModifyTime = now
	tx := writeDb.Begin()
	createWTEErr := tx.Model(&models.DeviceWTE{}).Create(wteDevice).Error
	if createWTEErr != nil {
		tx.Rollback()
		return nil, createWTEErr
	}
	device := models.Device{
		OrgID:        wteDevice.OrgID,
		DeviceType:   2,
		WTEID:        wteDevice.ID,
		SerialNumber: wteDevice.SerialNumber,
		Name:         wteDevice.Name,
		Model:        wteDevice.Model,
		Status:       1,
		CreateTime:   now,
		ModifyTime:   now,
	}
	if deviceNumber != nil {
		device.DeviceNumber = deviceNumber.Number
		device.DeviceNumberID = deviceNumber.ID
		device.DeviceZoneID = deviceNumber.ZoneID
		device.DeviceGroupID = deviceNumber.GroupID
	}
	createDeviceErr := tx.Model(&models.Device{}).Create(&device).Error
	if createDeviceErr != nil {
		tx.Rollback()
		return nil, createDeviceErr
	}
	tx.Commit()
	return &device, nil
}

func UpdateDMDevice(dmDevice *models.DeviceDM, deviceNumber *models.DeviceNumber, device *models.Device) error {
	now := time.Now().Unix()
	tx := writeDb.Begin()
	dmDevice.ModifyTime = now
	updateDMErr := tx.Save(dmDevice).Error
	if updateDMErr != nil {
		tx.Rollback()
		return updateDMErr
	}
	device.SerialNumber = dmDevice.SerialNumber
	device.Name = dmDevice.Name
	device.Model = dmDevice.Model
	if deviceNumber != nil {
		device.DeviceNumberID = deviceNumber.ID
		device.DeviceNumber = deviceNumber.Number
		device.DeviceZoneID = deviceNumber.ZoneID
		device.DeviceGroupID = deviceNumber.GroupID

	} else {
		device.DeviceNumberID = 0
		device.DeviceNumber = ""
		device.DeviceZoneID = 0
		device.DeviceGroupID = 0
	}
	device.ModifyTime = now
	updateDeviceErr := tx.Save(device).Error
	if updateDeviceErr != nil {
		tx.Rollback()
		return updateDeviceErr
	}
	tx.Commit()
	return nil
}

func UpdateWTEDevice(wteDevice *models.DeviceWTE, deviceNumber *models.DeviceNumber, device *models.Device) error {
	now := time.Now().Unix()
	tx := writeDb.Begin()
	wteDevice.ModifyTime = now
	updateWTEErr := tx.Save(wteDevice).Error
	if updateWTEErr != nil {
		tx.Rollback()
		return updateWTEErr
	}
	device.SerialNumber = wteDevice.SerialNumber
	device.Name = wteDevice.Name
	device.Model = wteDevice.Model
	device.DeviceNumberID = deviceNumber.ID
	device.DeviceNumber = deviceNumber.Number
	device.ModifyTime = now
	updateDeviceErr := tx.Save(device).Error
	if updateDeviceErr != nil {
		tx.Rollback()
		return updateDeviceErr
	}
	tx.Commit()
	return nil
}

func UpdateDevice(device *models.Device) error {
	err := writeDb.Save(device).Error
	return err
}

func GetDeviceCountForDeviceNumberID(orgID int64, deviceNumberID int64) (int, error) {
	var count int
	err := readDb.Model(&models.Device{}).Where("device_number_id = ? AND org_id = ? AND status = 1", deviceNumberID, orgID).Count(&count).Error
	if err != nil {
		return 0, err
	}
	return count, nil
}

//////// 分区 Zone

func GetAllValidDeviceZones(orgID int64) ([]*models.DeviceZone, error) {
	var zones []*models.DeviceZone
	err := readDb.Model(&models.DeviceZone{}).Where("org_id = ? AND status = 1", orgID).Find(&zones).Error
	if err != nil {
		return nil, err
	}
	return zones, nil
}

func GetDeviceZoneByID(orgID int64, zoneID int64) (*models.DeviceZone, error) {
	var zone models.DeviceZone
	err := readDb.Model(&models.DeviceZone{}).Where("org_id = ? AND id = ?", orgID, zoneID).First(&zone).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		} else {
			return nil, err
		}
	}
	return &zone, nil
}

func CreateDeviceZone(orgID int64, name string, type_ int) (*models.DeviceZone, error) {
	now := time.Now().Unix()
	zone := models.DeviceZone{
		OrgID:      orgID,
		Name:       name,
		Type:       type_,
		Status:     1,
		CreateTime: now,
		ModifyTime: now,
	}
	err := writeDb.Model(&models.DeviceZone{}).Create(&zone).Error
	if err != nil {
		return nil, err
	}
	return &zone, nil
}

func UpdateDeviceZone(zone *models.DeviceZone) error {
	err := writeDb.Save(zone).Error
	return err
}

//////// 分组 Group

func GetAllValidDeviceGroups(orgID int64) ([]*models.DeviceGroup, error) {
	var groups []*models.DeviceGroup
	err := readDb.Model(&models.DeviceGroup{}).Where("org_id = ? AND status = 1", orgID).Find(&groups).Error
	if err != nil {
		return nil, err
	}
	return groups, nil
}

func GetDeviceGroupByID(orgID int64, groupID int64) (*models.DeviceGroup, error) {
	var group models.DeviceGroup
	err := readDb.Model(&models.DeviceGroup{}).Where("org_id = ? AND id = ?", orgID, groupID).First(&group).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		} else {
			return nil, err
		}
	}
	return &group, nil
}

func CreateDeviceGroup(orgID int64, name string) (*models.DeviceGroup, error) {
	now := time.Now().Unix()
	group := models.DeviceGroup{
		OrgID:      orgID,
		Name:       name,
		Status:     1,
		CreateTime: now,
		ModifyTime: now,
	}
	err := writeDb.Model(&models.DeviceGroup{}).Create(&group).Error
	if err != nil {
		return nil, err
	}
	return &group, nil
}

func UpdateDeviceGroup(group *models.DeviceGroup) error {
	err := writeDb.Save(group).Error
	return err
}

//////// 机号 Number

type DeviceNumberViewModel struct {
	models.DeviceNumber
	ZoneName  string `gorm:"column:zone_name" json:"zone_name"`
	GroupName string `gorm:"column:group_name" json:"group_name"`
}

func GetAllValidDeviceNumbers(orgID int64) ([]*DeviceNumberViewModel, error) {
	var vms []*DeviceNumberViewModel = make([]*DeviceNumberViewModel, 0)
	rows, err := readDb.Raw("SELECT n.*, z.name as zone_name, g.name as group_name FROM xt_device_number as n join xt_device_zone as z on z.id = n.zone_id AND z.status = 1 join xt_device_group as g on g.id = n.group_id WHERE (n.org_id = ? AND n.status = 1)", orgID).Rows()
	defer rows.Close()
	if err != nil {
		return nil, err
	}
	for rows.Next() {
		var vm DeviceNumberViewModel
		readDb.ScanRows(rows, &vm)
		vms = append(vms, &vm)
	}
	return vms, nil
}

func GetAllBedNumber(orgId int64) (devicenumber []*models.XtDeviceNumber, err error) {

	err = XTReadDB().Raw("select id as bed_id,org_id,number as bed_number,group_id,zone_id from xt_device_number as n Where NOT EXISTS (select id,bed_id from sgj_users.xt_device_addmacher as a where a.bed_id = n.id and a.status = 1) AND n.org_id = ? AND n.status = 1 ", orgId).Scan(&devicenumber).Error
	return devicenumber, err
}

func GetAllBedNumberTwo(orgId int64, id int64) (devicenumber []*models.XtDeviceNumber, err error) {

	err = XTReadDB().Raw("select id as bed_id,org_id,number as bed_number,group_id,zone_id from xt_device_number as n Where NOT EXISTS (select id,bed_id from sgj_users.xt_device_addmacher as a where a.bed_id = n.id and a.status = 1 and a.id <> ?) AND n.org_id = ? AND n.status = 1 ", id, orgId).Scan(&devicenumber).Error
	return devicenumber, err
}

func GetAllMachineByOrgId(orgid int64) (addmacher []*models.DeviceAddmacher, err error) {

	err = UserReadDB().Where("user_org_id = ? AND status = 1", orgid).Find(&addmacher).Error
	return addmacher, err
}

func GetAllDeviceNumbers(orgID int64, record_date int64, schedule_type int64) ([]*DeviceNumberViewModel, error) {
	var vms []*DeviceNumberViewModel = make([]*DeviceNumberViewModel, 0)
	rows, err := readDb.Raw("SELECT n.*, z.name as zone_name, g.name as group_name FROM xt_device_number as n join xt_device_zone as z on z.id = n.zone_id join xt_device_group as g on g.id = n.group_id  WHERE (n.org_id = ? AND n.status = 1) AND NOT EXISTS (Select * FROM xt_schedule as s, `xt_dialysis_order` as d Where d.`dialysis_date` = ? AND d.`status` = 1 AND d.`patient_id` = s.`patient_id` AND   s.user_org_id = n.org_id AND s.`bed_id` = n.id AND s.`schedule_date` = ? AND s.`schedule_type` = ? AND s.status = 1 )", orgID, record_date, record_date, schedule_type).Rows()
	defer rows.Close()
	if err != nil {
		return nil, err
	}
	for rows.Next() {
		var vm DeviceNumberViewModel
		readDb.ScanRows(rows, &vm)
		vms = append(vms, &vm)
	}
	return vms, nil
}

func GetDeviceNumberByID(orgID int64, numberID int64) (*models.DeviceNumber, error) {
	var number models.DeviceNumber
	err := readDb.Model(&models.DeviceNumber{}).Where("org_id = ? AND id = ?", orgID, numberID).First(&number).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		} else {
			return nil, err
		}
	}
	return &number, nil
}

func CreateDeviceNumber(orgID int64, number string, zoneID int64, groupID int64) (*models.DeviceNumber, error) {
	now := time.Now().Unix()
	numberModel := models.DeviceNumber{
		OrgID:      orgID,
		Number:     number,
		ZoneID:     zoneID,
		GroupID:    groupID,
		Status:     1,
		CreateTime: now,
		ModifyTime: now,
	}
	err := writeDb.Model(&models.DeviceNumber{}).Create(&numberModel).Error
	if err != nil {
		return nil, err
	}
	return &numberModel, nil
}

func UpdateDeviceNumber(number *models.DeviceNumber) error {
	now := time.Now().Unix()
	number.ModifyTime = now
	tx := writeDb.Begin()
	updateNumberErr := tx.Save(number).Error
	if updateNumberErr != nil {
		tx.Rollback()
		return updateNumberErr
	}
	updateDeviceErr := tx.Model(&models.Device{}).Where("org_id = ? AND device_number_id = ?", number.OrgID, number.ID).Updates(map[string]interface{}{"device_number": number.Number}).Error
	if updateDeviceErr != nil {
		tx.Rollback()
		return updateDeviceErr
	}
	tx.Commit()
	return nil
}

func GetDeviceNumberCountForZoneID(orgID int64, zoneID int64) (int, error) {
	var count int
	err := readDb.Model(&models.DeviceNumber{}).Where("zone_id = ? AND org_id = ? AND status = 1", zoneID, orgID).Count(&count).Error
	if err != nil {
		return 0, err
	}
	return count, nil
}

func GetDeviceNumberCountForGroupID(orgID int64, groupID int64) (int, error) {
	var count int
	err := readDb.Model(&models.DeviceNumber{}).Where("group_id = ? AND org_id = ? AND status = 1", groupID, orgID).Count(&count).Error
	if err != nil {
		return 0, err
	}
	return count, nil
}

func GetScheduleCountForDeviceNumber(orgID int64, deviceNumberID int64, beginDate int64) (int, error) {
	var count int
	err := readDb.Model(&models.Schedule{}).Where("bed_id = ? AND user_org_id = ? AND schedule_date >= ? AND status = 1", deviceNumberID, orgID, beginDate).Count(&count).Error
	if err != nil {
		return 0, err
	}
	return count, nil
}

func GetScheduleTemplateItemCountForDeviceNumber(orgID int64, deviceNumberID int64) (int, error) {
	var count int
	err := readDb.Model(&models.PatientScheduleTemplateItem{}).Where("device_number_id = ? AND org_id = ? AND status = 1", deviceNumberID, orgID).Count(&count).Error
	if err != nil {
		return 0, err
	}
	return count, nil
}

func GetZoneId(bednumber int64, orgid int64) (models.DeviceNumber, error) {

	number := models.DeviceNumber{}
	err := XTReadDB().Model(&number).Where("id = ? AND org_id = ?", bednumber, orgid).Find(&number).Error
	return number, err
}

//func AddMacher(deviceaddmacher *models.DeviceAddmacher) error{
//	fmt.Println("进来了没哟")
//	tx := writeDb.Begin()
//	err := tx.Model(&models.DeviceAddmachers{}).Create(&deviceaddmacher).Error
//	fmt.Println("错误是什么",err)
//	if err !=nil{
//		tx.Rollback()
//	}
//	tx.Commit()
//	return err
//}

// func CreateMacher(machers *models.DeviceAddmacher) error {
//      fmt.Println("进来了米有")
// 	begin := writeDb.Begin()
// 	fmt.Println("hhhhhhhh",begin)
// 	err := begin.Model(&models.DeviceAddmacher{}).Create(machers).Error
// 	fmt.Println("err",err)
// 	if err !=nil{
// 		begin.Rollback()
// 	}
// 	begin.Commit()
// 	fmt.Println("执行了没有")
// 	return err
// }

func GetLastMacherData(orgid int64) (models.DeviceAddmacher, error) {
	addmacher := models.DeviceAddmacher{}
	err := UserReadDB().Model(&addmacher).Where("user_org_id = ? AND status = ?", orgid, 1).Last(&addmacher).Error
	return addmacher, err
}

func AddTreatMode(machineid int64, orgid int64, treatmodes []int64) (err error) {
	utx := XTWriteDB().Begin()
	if len(treatmodes) > 0 {
		thisSQL := "INSERT INTO xt_device_treatmentmode(machine_id,treate_mode,status,ctime,user_org_id) VALUES "
		insertParams := make([]string, 0)
		insertData := make([]interface{}, 0)
		for _, contagion := range treatmodes {
			insertParams = append(insertParams, "(?, ?, ?, ?, ?)")
			insertData = append(insertData, machineid)
			insertData = append(insertData, contagion)
			insertData = append(insertData, 1)
			insertData = append(insertData, time.Now().Unix())
			insertData = append(insertData, orgid)
		}
		thisSQL += strings.Join(insertParams, ",")
		err = utx.Exec(thisSQL, insertData...).Error
		if err != nil {
			utx.Rollback()
			return
		}
	}
	utx.Commit()
	return
}

//func DeleteBedNumber(id int64,orgid int64)(error){
//	//err := writeDb.Model(&models.DeviceNumber{}).Where("id = ? AND org_id = ?", id, orgid).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
//	err := writeDb.Model(&models.DeviceNumber{}).Where("id = ? AND org_id = ?", id, orgid).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
//
//
//	fmt.Println("错误是什么",err)
//	return  err
//
//}
//
//func DeleteZoneId(id int64,orgid int64)(error)  {
//	err := writeDb.Model(&models.DeviceZone{}).Where("id = ? AND org_id = ?", id, orgid).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
//	return  err
//}

func GetAllMachineInfo(page int64, limit int64, keyword string, zoneid int64, equimentid int64, statusid int64, orgid int64) (addmahcer []*models.DeviceAddmachers, total int64, err error) {

	//db := readUserDb().Table("xt_device_addmacher as a").Where("a.status = 1")
	db := readUserDb.Table("xt_device_addmacher as a").Where("a.status = 1")
	table := XTReadDB().Table("xt_device_zone as x")
	d := readUserDb.Table("xt_device_mode as m")
	d2 := XTReadDB().Table("xt_device_number as n")
	fmt.Print("d", d)
	fmt.Println("table", table)
	fmt.Print("d2", d2)
	if orgid > 0 {
		db = db.Where("a.user_org_id = ?", orgid)
	}
	if zoneid > 0 {
		db = db.Where("a.zone_id = ?", zoneid)
	}
	if equimentid > 0 {
		db = db.Where("a.device_type = ?", equimentid)
	}
	if statusid > 0 {
		db = db.Where("a.machine_status = ?", statusid)
	}

	if len(keyword) > 0 {
		keyword = "%" + keyword + "%"
		db = db.Where("a.serial_number LIKE ? OR a.device_name LIKE ? OR a.unit_type LIKE ?", keyword, keyword, keyword)
	}

	offset := (page - 1) * limit

	err = db.Order("a.ctime asc").Select("a.id,a.serial_number,a.device_type,a.bed_number,a.device_name,a.manufacture_factory,a.service_manufacturer,a.unit_type,a.use_section,a.section_number,a.buy_date,a.install_date,a.start_date,a.maintenace_engineer,a.telephone,a.guarantee_date,a.machine_status,a.user_total,a.disinfection_mode,a.remarks,a.rubbish_date,a.rubbish_reason,a.user_year,a.work_time,a.revers_mode,a.user_org_id,a.status,a.ctime,a.mtime,a.bed_id,x.name,m.device_mode,n.number").Count(&total).
		Joins("Left JOIN xt_device_mode as m on m.id = a.unit_type ").Joins("left join sgj_xt.xt_device_number as n on n.id = a.bed_id").Joins("Left JOIN sgj_xt.xt_device_zone as x On x.id = n.zone_id").Offset(offset).Limit(limit).Scan(&addmahcer).Error

	if err != nil {

		return
	}
	return
}

func GetAllMachine(zoneid int64, classid int64, deviceid int64, timenow int64, orgid int64) (addmahcer []*models.DeviceAddmachers, err error) {
	fmt.Println("timenow", timenow)
	db := readUserDb.Table("xt_device_addmacher as a").Where("a.status = 1")
	//db := XTReadDB().Table("xt_device_addmacher as a").Where("a.status = 1")
	tab := XTReadDB().Table("xt_schedule as x")
	fmt.Println("tab", tab)
	d := readUserDb.Table("xt_device_mode as m")
	fmt.Print("d", d)
	table := XTReadDB().Table("xt_device_number as n")
	fmt.Print("table", table)
	if orgid > 0 {
		db = db.Where("a.user_org_id = ?", orgid)
	}
	if zoneid > 0 {
		db = db.Where("a.zone_id = ?", zoneid)
	}

	if deviceid > 0 {
		db = db.Where("a.device_type = ?", deviceid)
	}
	if classid > 0 {
		error := db.Joins("LEFT JOIN sgj_xt.xt_schedule as x On x.bed_id = a.bed_id").Joins("LEFT JOIN xt_device_mode as d on d.id = a.unit_type").Joins("lefj join sgj_xt.xt_device_number as n on n.id = a.bed_id").Where("x.user_org_id = ? AND x.schedule_date = ? AND x.schedule_type = ? AND x.status = ?", orgid, timenow, classid, 1).Order("a.ctime desc").Select("a.id,a.serial_number,a.device_type,a.bed_number,a.device_name,a.manufacture_factory,a.service_manufacturer,a.unit_type,a.use_section,a.section_number,a.buy_date,a.install_date,a.start_date,a.maintenace_engineer,a.telephone,a.guarantee_date,a.machine_status,a.user_total,a.disinfection_mode,a.remarks,a.rubbish_date,a.rubbish_reason,a.user_year,a.work_time,a.revers_mode,a.user_org_id,a.status,a.ctime,a.mtime,d.device_mode,n.number").Find(&addmahcer).Error
		fmt.Println("err", error)
	} else {
		err = db.Order("a.ctime asc").Select("a.id,a.serial_number,a.device_type,a.bed_number,a.device_name,a.manufacture_factory,a.service_manufacturer,a.unit_type,a.use_section,a.section_number,a.buy_date,a.install_date,a.start_date,a.maintenace_engineer,a.telephone,a.guarantee_date,a.machine_status,a.user_total,a.disinfection_mode,a.remarks,a.rubbish_date,a.rubbish_reason,a.user_year,a.work_time,a.revers_mode,a.user_org_id,a.status,a.ctime,a.mtime,a.bed_id,d.device_mode,n.number").Joins("LEFT JOIN xt_device_mode as d on d.id = a.unit_type").Joins("left join sgj_xt.xt_device_number as n on n.id = a.bed_id").Find(&addmahcer).Error
		fmt.Println("错误是什么", err)
		if err != nil {

			return
		}
	}
	return
}

func GetMachineDetail(id int64, orgid int64) (models.DeviceAddmachers, error) {
	addmacher := models.DeviceAddmachers{}
	//  //	//err := readUserDb.Model(&addmacher).Where("id = ? AND user_org_id = ? AND status = 1", id, orgid).Find(&addmacher).Error
	db := readUserDb.Table("xt_device_addmacher as a").Where("a.status =1")
	d := readUserDb.Table("xt_device_mode as d")
	fmt.Print("d", d)
	err := db.Select("a.id,a.serial_number,a.device_type,a.bed_number,a.device_name,a.manufacture_factory,a.service_manufacturer,a.unit_type as device_mode,a.use_section,a.section_number,a.buy_date,a.install_date,a.start_date,a.maintenace_engineer,a.telephone,a.guarantee_date,a.machine_status,a.user_total,a.disinfection_mode,a.remarks,a.rubbish_date,a.rubbish_reason,a.user_year,a.work_time,a.revers_mode,a.user_org_id,a.status,a.ctime,a.mtime,a.zone_id,a.bed_id").Joins("left join xt_device_mode as d on d.id = a.unit_type ").Where("a.id = ? and a.user_org_id = ?", id, orgid).Find(&addmacher).Error
	return addmacher, err
}

func GetTreatModel(id int64, orgid int64) (mode []*models.DeviceTreatmentmode, err error) {
	err = XTReadDB().Model(&mode).Where("machine_id = ? AND user_org_id = ? AND status = 1 ", id, orgid).Find(&mode).Error

	return mode, err
}
