package models

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

//网关下挂载的设备串口设备，如485接口的设备，数据来自设备上报
type CameraDevice struct {
	ID         string `gorm:"type:varchar(32);primary_key"` //设备ID，DID
	Name       string `gorm:"type:varchar(64)"`             //设备名称
	GID        string `gorm:"type:varchar(32)"`             //网关ID
	IP         string `gorm:"type:varchar(40)"`             //ip
	SN         string `gorm:"type:varchar(64)"`             //设备序列号
	Brand      string `gorm:"type:varchar(24)"`             //设备品牌
	Model      string `gorm:"type:varchar(32)"`             //设备型号
	DevType    int    `gorm:"type:int"`                     //3摄象机，4一键报警(带视频)
	User       string `gorm:"-"`                            //onvif用户名
	Password   string `gorm:"-"`                            //onvif密码
	RtmpServer string `gorm:"-"`                            //流地址
	WebServer  string `gorm:"-"`                            //web地址
	Event      string `gorm:"-"`                            //需要订阅的事件主题
	Gb28181    bool   `gorm:"-"`                            //国标28181，是否已开启GB28181
	Tenant     string `gorm:"type:varchar(8)"`              //租户ID
	State      int    `gorm:"type:int"`                     //1启用，0禁用
	//LcModel
}

func (CameraDevice) TableName() string {
	return "t_device_camera"
}

func (o CameraDevice) Delete() error {
	return G_db.Model(&o).Updates(map[string]interface{}{"state": 0}).Error
}

func (o CameraDevice) IsExistedByCode() (bool, error) {
	var count int = 0
	err := G_db.Model(&o).Where(" id = ? ", o.ID).Count(&count).Error
	return count > 0, err
}

func (o CameraDevice) SaveFromWeb() error {
	has, err := o.IsExistedByCode()
	if err != nil {
		return err
	}
	if has { //更新
		return G_db.Model(&o).Updates(map[string]interface{}{"name": o.Name, "g_id": o.GID,
			"dev_type": o.DevType, "tenant": o.Tenant, "state": o.State}).Error
	} else { //插入
		return G_db.Create(&o).Error
	}
}

func (o CameraDevice) SaveFromGateway() error {
	return nil
	has, err := o.IsExistedByCode()
	if err != nil {
		return err
	}
	if has { //更新
		return G_db.Model(&o).Updates(map[string]interface{}{"name": o.Name, "g_id": o.GID, "ip": o.IP, "sn": o.SN,
			"brand": o.Brand, "model": o.Model, "dev_type": o.DevType, "user": o.User, "password": o.Password,
			"rtmp_server": o.RtmpServer, "web_server": o.WebServer, "event": o.Event, "gb28181": o.Gb28181}).Error
	} else { //插入
		return G_db.Create(&o).Error
	}
}

func CameraDeviceUpdateState(id string, state int) error {
	return G_db.Model(CameraDevice{}).Where("id = ?", id).Updates(map[string]interface{}{"state": state}).Error
}

type CameraInfo struct {
	GID     string
	Tenant  string
	Gb28181 bool
}

func GetCameraInfoByID(id string) (*CameraInfo, error) {
	var ci CameraInfo
	err := G_db.Model(&CameraDevice{}).Select([]string{"id", "g_id", "tenant", "gb28181"}).Where("id = ? ", id).Scan(&ci).Error
	return &ci, err
}

//IPC Preset
type IpcPresets struct {
	ID        string  `gorm:"type:varchar(32);primary_key"`
	Token     string  `gorm:"type:varchar(16);primary_key"`
	Name      string  `gorm:"type:varchar(40)"`
	X         float32 `gorm:"type:decimal(8,5)"`
	Y         float32 `gorm:"type:decimal(8,5)"`
	Z         float32 `gorm:"type:decimal(8,5)"`
	File      string  `gorm:"type:varchar(64)"`  //预置位快照
	Mark      string  `gorm:"type:varchar(128)"` //备注
	CreatedAt time.Time
	UpdatedAt time.Time
}

func (IpcPresets) TableName() string {
	return "t_device_ipc_presets"
}

func MultiInsertIpcPresets(datas []IpcPresets) error {
	if len(datas) == 0 {
		return nil
	}
	var buffer bytes.Buffer
	sql := "insert into t_device_ipc_presets (id,token,name,x,y,z,file,mark,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','%s','%s',%f,%f,%f,'%s','%s','%s');",
				e.ID, e.Token, e.Name, e.X, e.Y, e.Z, e.File, e.Mark, e.CreatedAt.Format("2006-01-02 15:04:05")))
		} else {
			buffer.WriteString(fmt.Sprintf("('%s','%s','%s',%f,%f,%f,'%s','%s','%s'),",
				e.ID, e.Token, e.Name, e.X, e.Y, e.Z, e.File, e.Mark, e.CreatedAt.Format("2006-01-02 15:04:05")))
		}
	}
	return G_db.Exec(buffer.String()).Error
}

func GetPresetsByID(id string) ([]IpcPresets, error) {
	var arr []IpcPresets
	err := G_db.Model(&IpcPresets{}).Where("id = ? ", id).Find(&arr).Error
	return arr, err
}

func (o IpcPresets) IsExistedByCode() (bool, error) {
	var count int = 0
	err := G_db.Model(&IpcPresets{}).Where("id = ? AND token = ? ", o.ID, o.Token).Count(&count).Error
	return count > 0, err
}

func (o IpcPresets) SaveFromGateway() error {
	has, err := o.IsExistedByCode()
	if err != nil {
		return err
	}
	if has { //更新
		return G_db.Model(&o).Updates(map[string]interface{}{"name": o.Name, "x": o.X, "y": o.Y, "z": o.Z}).Error
	} else { //插入
		return G_db.Create(&o).Error
	}
}

func (o IpcPresets) SaveFromGateway2() error {
	has, err := o.IsExistedByCode()
	if err != nil {
		return err
	}
	if has { //更新
		return G_db.Model(&o).Updates(map[string]interface{}{"name": o.Name, "x": o.X, "y": o.Y, "z": o.Z, "file": o.File}).Error
	} else { //插入
		return G_db.Create(&o).Error
	}
}
