package model

import (
	"fmt"
	"sparrow/pkg/models"
	"time"

	"github.com/jinzhu/gorm"
)

// Device devices data
type Device struct {
	db *gorm.DB
}

// Init device
// TODO:增加产品ID查询，目前的查询都没有指定产品ID的查询
func (a *Device) Init(db *gorm.DB) *Device {
	a.db = db
	return a
}

// GetDeviceCount 获取vendorid下的设备激活总数
func (a *Device) GetDeviceCount(vendorid string) (count int, err error) {
	device := &models.Device{
		VendorID: vendorid,
	}
	err = a.db.Model(device).Where(device).Count(&count).Error
	return
}

// GetActiveNumberOfDate 获取某一天的设备激活数量
func (a *Device) GetActiveNumberOfDate(vendorid string, datetime string) (count int, err error) {
	device := &models.Device{
		VendorID: vendorid,
	}
	err = a.db.Model(device).
		Where("vendor_id = ? and DATE_FORMAT(created_at, '%Y-%m-%d') = ?",
			vendorid, datetime).
		Count(&count).
		Error
	return
}

// GetLivelyCountOfDate 获取某一天的设备活跃数据
func (a *Device) GetLivelyCountOfDate(vendorid string, datetime string) (count int, err error) {
	device := &models.Device{
		VendorID: vendorid,
	}
	err = a.db.Model(device).
		Where("vendor_id = ? and DATE_FORMAT(updated_at, '%Y-%m-%d') = ?",
			vendorid, datetime).Count(&count).Error
	return
}

// // GetActiveOf7Days 设备近7日的激活数据
// func (a *Device) GetActiveOf7Days(vendorid int) (datas []models.DeviceChartData, err error) {
// 	err = a.db.Model(&models.Device{}).
// 		Select("DATE_FORMAT(created_at,'%Y-%m-%d') as dt, count(id) as count").
// 		Where("DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= date(created_at) and vendor_id = ?",
// 			vendorid).
// 		Group("dt").Order("dt").Scan(&datas).Error
// 	if err != nil {
// 		return
// 	}
// 	return
// }

// // GetActiveOf14Days 设备近14日的激活数据
// func (a *Device) GetActiveOf14Days(vendorid int) (datas []models.DeviceChartData, err error) {
// 	err = a.db.Model(&models.Device{}).
// 		Select("DATE_FORMAT(created_at,'%Y-%m-%d') as dt, count(id) as count").
// 		Where("DATE_SUB(CURDATE(), INTERVAL 14 DAY) <= date(created_at) and vendor_id = ?",
// 			vendorid).
// 		Group("dt").Order("dt").Scan(&datas).Error
// 	if err != nil {
// 		return
// 	}
// 	return
// }

// // GetActiveOf30Days 设备近30日的激活数据
// func (a *Device) GetActiveOf30Days(vendorid int) (datas []models.DeviceChartData, err error) {
// 	err = a.db.Model(&models.Device{}).
// 		Select("DATE_FORMAT(created_at,'%Y-%m-%d') as dt, count(id) as count").
// 		Where("DATE_SUB(CURDATE(), INTERVAL 30 DAY) <= date(created_at) and vendor_id = ?",
// 			vendorid).
// 		Group("dt").Order("dt").Scan(&datas).Error
// 	if err != nil {
// 		return
// 	}
// 	return
// }

// GetActiveOfNumDays 查询几日内的激活趋势数据
// days参数为7则查询7日的数据
func (a *Device) GetActiveOfNumDays(vendorid string, days int) ([]map[string]interface{}, error) {
	i := 1
	datas := make([]map[string]interface{}, 0)
	for i <= days {
		day := i - days
		i = i + 1
		datetime := time.Now().AddDate(0, 0, day).Format("2006-01-02")
		count, err := a.GetActiveNumberOfDate(vendorid, datetime)
		if err != nil {
			return nil, err
		}
		data := make(map[string]interface{})
		data[datetime] = count
		datas = append(datas, data)
	}
	return datas, nil
}

// GetLivelyOfNumDays 获取设备N日内活跃趋势数据
func (a *Device) GetLivelyOfNumDays(vendorid string, days int) ([]map[string]interface{}, error) {
	i := 1
	datas := make([]map[string]interface{}, 0)
	for i <= days {
		day := i - days
		i = i + 1
		datetime := time.Now().AddDate(0, 0, day).Format("2006-01-02")
		count, err := a.GetLivelyCountOfDate(vendorid, datetime)
		if err != nil {
			return nil, err
		}
		data := make(map[string]interface{})
		data[datetime] = count
		datas = append(datas, data)
	}
	return datas, nil
}

// GetDevices 获取厂商已经激活的设备列表
func (a *Device) GetDevices(vendorid, proid string, pi, ps int, deviceid string) (datas []models.Device, total int, err error) {
	tx := a.db.Where("vendor_id = ?", vendorid)
	if proid != "" {
		tx = tx.Where("product_id = ?", proid)
	}
	if deviceid != "" {
		tx = tx.Where("device_identifier like ?", "%"+deviceid+"%")
	}
	tx = tx.Order("id DESC")
	err = tx.Limit(ps).Offset((pi - 1) * ps).Find(&datas).Error
	tx.Model(&models.Device{}).Count(&total)
	return
}

// GetDevicesByVenderId 获取用户设备
func (a *Device) GetDevicesByVenderId(vendorid string) (datas []models.Device, err error) {
	a.db.Where("vendor_id = ?", vendorid).Find(&datas)
	return
}

// Query 获取厂商已经激活的设备列表
func (a *Device) Query(vendorId, productId string, deviceIDs []string) (datas []models.Device, err error) {
	tx := a.db.Where("vendor_id = ?", vendorId)
	if productId != "" {
		tx = tx.Where("product_id = ?", productId)
	}
	if len(deviceIDs) > 0 {
		tx = tx.Where("record_id in (?)", deviceIDs)
	}
	tx = tx.Order("id DESC")
	err = tx.Find(&datas).Error

	return
}

// Get 获取数据内容
func (a *Device) Get(vendorId string, recordId string) (data models.Device, err error) {
	cache := getCache()
	key := fmt.Sprintf("OtaId:%s", recordId)
	if v, ok := cache.Get(key); ok {
		_d := v.(*models.Device)
		data = *_d
	} else {
		err = a.db.Where("vendor_id = ? and record_id = ?", vendorId, recordId).First(&data).Error
		if err == nil {
			cache.Set(key, &data)
		}
	}
	return
}

// Update update
func (a *Device) Update(Device *models.Device) (data models.Device, err error) {
	cache := getCache()
	key := fmt.Sprintf("Device:%d", Device.ID)
	if _, ok := cache.Get(key); ok {
		cache.Delete(key)
	}
	err = a.db.Model(&data).Update(Device).Error
	return
}
