package dao

import (
	"iot_manager_service/app/record/edge_service"
	"time"
)

type AkeyAlarmRecord struct {
	ID             int       `gorm:"column:id;type:int(11);primary_key;AUTO_INCREMENT" json:"id" :"ID"`
	ServeId        int       `gorm:"column:serve_id;type:int(11);comment:管理端ID" json:"serveId" :"serveId"`
	ServeName      string    `gorm:"column:serve_name;type:varchar(60);comment:管理端名称" json:"serveName" :"serveName"`
	ServeSn        string    `gorm:"column:serve_sn;type:varchar(60);comment:管理端编码" json:"serveSn" :"serveSn"`
	TerminalId     int       `gorm:"column:terminal_id;type:int(11);comment:客户端ID" json:"terminalId" :"terminalId"`
	TerminalName   string    `gorm:"column:terminal_name;type:varchar(60);comment:客户端名称" json:"terminalName" :"terminalName"`
	TerminalSn     string    `gorm:"column:terminal_sn;type:varchar(60);comment:客户端编码" json:"terminalSn"`
	LocalAddress   string    `gorm:"column:local_address;type:varchar(255);comment:灯杆地址" json:"localAddress"`
	AlarmStartTime time.Time `gorm:"column:alarm_start_time;type:datetime;comment:报警开始时间" json:"alarmStartTime"`
	AlarmEndTime   time.Time `gorm:"column:alarm_end_time;type:datetime;comment:报警结束时间" json:"alarmEndTime"`
	AlarmCountTime int       `gorm:"column:alarm_count_time;type:int(11);default:0;comment:报警时长(秒)" json:"alarmCountTime"`
	IsDispose      int       `gorm:"column:is_dispose;type:int(11);default:0;comment:是否处理:0-未处理，1-已处理" json:"isDispose"`
	Remark         string    `gorm:"column:remark;type:varchar(1000);comment:备注" json:"remark"`
	TenantId       string    `gorm:"column:tenant_id;type:varchar(12);comment:租户ID" json:"tenantId"`
	CreateTime     time.Time `gorm:"column:create_time;type:datetime;comment:创建时间" json:"createTime"`
	UpdateTime     time.Time `gorm:"column:update_time;type:timestamp;comment:更新时间" json:"updateTime"`
	UpdateUser     string    `gorm:"column:update_user;type:varchar(255);comment:修改用户ID" json:"updateUser"`
	IsDeleted      int       `gorm:"column:is_deleted;type:int(11);default:0;comment:是否删除：0-否-1删除" json:"isDeleted"`
}

func (a AkeyAlarmRecord) TableName() string {
	return "device_a_key_alarm_record_his"
}

func (a AkeyAlarmRecord) GetRecords(offset int, limit int, start string, end string, searchValue string, serveId int) ([]AkeyAlarmRecord, error) {
	var records []AkeyAlarmRecord
	db := Db.Debug().Model(&a)
	if serveId > 0 {
		db.Where("serve_id=?", serveId)
	}
	if searchValue != "" {
		db = db.Where("terminal_sn like ? or terminal_name like ?", "%"+searchValue+"%", "%"+searchValue+"%")
	}
	if start != "" {
		start = start + " 00:00:00"
		end = end + " 23:59:59"
		db = db.Where("alarm_start_time >=? and  alarm_end_time <= ?", start, end)
	}
	err := db.Where("is_deleted = 0").Offset(offset).Limit(limit).Find(&records).Error
	return records, err
}

func (a AkeyAlarmRecord) GetMaxIdAndUpDateTime() (int64, string) {
	var record AkeyAlarmRecord
	err := Db.Debug().Order("id desc").First(&record).Error
	if err != nil {
		return 0, "2020-01-01 00:00:00"
	}
	return int64(record.ID), record.CreateTime.Format("2006-01-02 15:04:05")
}

func (a AkeyAlarmRecord) BatchCreate(record []edge_service.RecordAlarmSosData) error {
	his, err := a.assembleRecordHis(record)
	//fmt.Printf("his = %v", his)
	if err != nil {
		return err
	}
	return Db.Debug().CreateInBatches(his, 1000).Error
}

func (a AkeyAlarmRecord) assembleRecordHis(records []edge_service.RecordAlarmSosData) ([]AkeyAlarmRecord, error) {
	var temRecords []AkeyAlarmRecord
	Db.Debug().Raw("select a.tenant_id,a.id terminal_id,a.terminal_name,a.terminal_sn, a.lamp_pole_location local_address,a.serve_id, b.serve_name,b.serve_sn FROM device_a_key_alarm_terminal a LEFT JOIN device_a_key_alarm_serve b ON a.serve_id=b.id WHERE a.is_deleted=0").
		Scan(&temRecords)

	m := make(map[string]AkeyAlarmRecord)
	for _, temSosRecord := range temRecords {
		m[temSosRecord.TerminalSn] = temSosRecord
	}
	var realLightRecords []AkeyAlarmRecord
	for _, record := range records {
		lightRecord := m[record.Code]
		if lightRecord.ServeId == 0 {
			continue
		}
		lightRecord.ID = record.ID
		lightRecord.AlarmStartTime, _ = time.ParseInLocation("2006-01-02 15:04:05", record.Tstart, time.Local)
		lightRecord.AlarmEndTime, _ = time.ParseInLocation("2006-01-02 15:04:05", record.Tend, time.Local)
		lightRecord.AlarmCountTime = int(record.Duration)
		lightRecord.IsDeleted = 0
		lightRecord.IsDispose = 0
		lightRecord.TerminalSn = record.Code
		lightRecord.CreateTime = time.Now()
		lightRecord.UpdateTime = time.Now()
		realLightRecords = append(realLightRecords, lightRecord)
	}
	return realLightRecords, nil
}

func (a AkeyAlarmRecord) Get() (*AkeyAlarmRecord, error) {
	var record AkeyAlarmRecord
	err := Db.Debug().Model(&a).First(&record).Error
	return &record, err
}

func (a AkeyAlarmRecord) Update() error {
	err := Db.Debug().Model(&a).Updates(&a).Error
	return err
}
