package models

import (
	"bytes"
	"fmt"
	"time"
)

//手动控制，开灯/关灯记录表
type LampSwitchRecord struct {
	ID         uint      `gorm:"primary_key"`                         //主键，自增长
	DID        string    `gorm:"type:varchar(32)" json:"did"`         //设备编码
	SwitchOn   uint8     `gorm:"type:tinyint(1)" json:"switchon"`     //类型，1:开灯，0:关灯
	Duration   uint      `gorm:"type:int" json:"duration"`            //开灯或关灯时长，单位秒
	Brightness uint8     `gorm:"type:smallint" json:"brightness"`     //亮度，关灯时亮度为0
	TStart     time.Time `gorm:"type:datetime;not null" json:"start"` //开始时间
	TEnd       time.Time `gorm:"type:datetime;not null" json:"end"`   //结束时间
	CreatedAt  time.Time `gorm:"type:datetime;not null"`              //结束时间
}

func (LampSwitchRecord) TableName() string {
	return "device_lamp_switch_record"
}

func MultiInsertLampSwitchRecord(datas []LampSwitchRecord) error {
	if len(datas) == 0 {
		return nil
	}
	var buffer bytes.Buffer
	sql := "insert into t_device_lamp_switch_record(d_id,switch_on,duration,brightness,t_start,t_end,created_at) values"
	if _, err := buffer.WriteString(sql); err != nil {
		return err
	}
	for i, e := range datas {
		if i == len(datas)-1 {
			buffer.WriteString(fmt.Sprintf("('%s',%d,%d,%d,'%s','%s','%s');", e.DID, e.SwitchOn, e.Duration, e.Brightness,
				e.TStart.Format("2006-01-02 15:04:05"), e.TEnd.Format("2006-01-02 15:04:05"), e.CreatedAt.Format("2006-01-02 15:04:05")))
		} else {
			buffer.WriteString(fmt.Sprintf("('%s',%d,%d,%d,'%s','%s','%s'),", e.DID, e.SwitchOn, e.Duration, e.Brightness,
				e.TStart.Format("2006-01-02 15:04:05"), e.TEnd.Format("2006-01-02 15:04:05"), e.CreatedAt.Format("2006-01-02 15:04:05")))
		}
	}
	return G_db.Exec(buffer.String()).Error
}
