package controllers

import (
	"errors"
	"fmt"
	"sparrow/pkg/rpcs"
	"sparrow/pkg/server"
	"sparrow/services/knowoapi/services"
	"strconv"
	"time"

	"github.com/kataras/iris"
)

// DeviceController api
type DeviceController struct {
	Ctx     iris.Context
	Service services.DeviceService
	Token
}

// Get 获取激活设备列表
// GET /device?pi=&ps=&proid=&device_id=
func (a *DeviceController) Get() {
	pi, err := a.Ctx.URLParamInt("pi")
	if err != nil {
		badRequest(a.Ctx, err)
		return
	}
	ps, err := a.Ctx.URLParamInt("ps")
	if err != nil {
		badRequest(a.Ctx, err)
		return
	}
	proid, err := a.Ctx.URLParamInt("proid")
	if err != nil {
		proid = 0
	}
	deviceid := a.Ctx.URLParam("device_id")
	vid := a.getVendorID(a.Ctx)
	datas, total, err := a.Service.GetDevices(vid, proid, pi, ps, deviceid)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, map[string]interface{}{
		"list":  datas,
		"total": total,
	})
}

//设备数量，包含在线数量，离线数量，总数量
//GET /devicecount
func (a *DeviceController) GetDevicecount() {
	vid := a.getVendorID(a.Ctx)
	data, err := a.Service.GetDevicesCountByVenderId(vid)

	if err != nil && err.Error() != "redigo: nil returned" {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}

	done(a.Ctx, data)
}

//获取设备在线状态
// GET /devicestatus?device_id=
func (a *DeviceController) GetDevicestatus() {

	deviceid := a.Ctx.URLParam("device_id")

	var status int

	onlineargs := rpcs.ArgsGetDeviceOnlineStatus{
		Id: deviceid,
	}

	onlinereply := rpcs.ReplyGetDeviceOnlineStatus{}
	err := server.RPCCallByName(nil, rpcs.DeviceManagerName, "DeviceManager.GetDeviceOnlineStatus", onlineargs, &onlinereply)
	if err != nil && err.Error() != "redigo: nil returned" {
		server.Log.Errorf("get devie online status error: %v", err)
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}

	if int(onlinereply.HeartbeatInterval) > 0 && len(onlinereply.ClientIP) > 0 {
		status = 1
	}

	done(a.Ctx, map[string]interface{}{
		"Status": status,
	})

}

// GetBannerdata 获取设备激活和活跃数据
// GET /bannerdata?proid=
func (a *DeviceController) GetBannerdata() {
	proid, err := a.Ctx.URLParamInt("proid")
	if err != nil {
		proid = 0
	}
	var (
		//今日激活
		tact = 0
		// 今日活跃
		tlive = 0
		// 昨日激活
		yact = 0
		// 昨日活跃
		ylive = 0
		// 累计激活
		totolact = 0
		// 环比昨日激活
		comparedWithYesterdayActive = 0.00
		//活跃占比
		rateOfTodayLive = 0.00
		//环比昨日活跃
		comparedWithYesterdayLive = 0.00
	)
	vendorid := a.getVendorID(a.Ctx)
	totolact, err = a.Service.GetDeviceCount(vendorid)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	today := time.Now().Format("2006-01-02")
	yestoday := time.Now().AddDate(0, 0, -1).Format("2006-01-02")
	tact, err = a.Service.GetActiveNumberOfDate(vendorid, today)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	tlive, err = a.Service.GetLivelyCountOfDate(vendorid, today)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	yact, err = a.Service.GetActiveNumberOfDate(vendorid, yestoday)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	ylive, err = a.Service.GetLivelyCountOfDate(vendorid, yestoday)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	if tact != 0 && yact != 0 {
		comparedWithYesterdayActive = (float64(tact) / float64(yact)) * 100
	}
	if tlive != 0 && ylive != 0 {
		comparedWithYesterdayLive = (float64(tlive) / float64(ylive)) * 100
		rateOfTodayLive = float64(tlive) / float64(totolact) * 100
	}
	//TODO 这里的productid要去掉
	result := map[string]interface{}{
		"todayAct":                    tact,
		"todayLive":                   tlive,
		"yestodayAct":                 yact,
		"yestodayLive":                ylive,
		"totalAct":                    totolact,
		"comparedWithYesterdayActive": fmt.Sprintf("%s%%", strconv.FormatFloat(comparedWithYesterdayActive, 'f', 2, 64)),
		"comparedWithYesterdayLive":   fmt.Sprintf("%s%%", strconv.FormatFloat(comparedWithYesterdayLive, 'f', 2, 64)),
		"rateOfTodayLive":             fmt.Sprintf("%s%%", strconv.FormatFloat(rateOfTodayLive, 'f', 2, 64)),
		"productid":                   proid,
	}
	done(a.Ctx, result)
}

// GetActivechart 获取N日的激活数据趋势
func (a *DeviceController) GetActivechart() {
	// proid, err := a.Ctx.URLParamInt("proid")
	// if err != nil {
	// 	proid = 0
	// }
	days, err := a.Ctx.URLParamInt("days")
	if err != nil {
		days = 7
	}
	if days > 30 {
		badRequest(a.Ctx, errors.New("非法参数"))
		return
	}
	vendorid := a.getVendorID(a.Ctx)
	datas, err := a.Service.GetActiveOfNumDays(vendorid, days)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, map[string]interface{}{
		"chart": datas,
	})
}

// GetLivechart 获取N日内的活跃数据
func (a *DeviceController) GetLivechart() {
	// proid, err := a.Ctx.URLParamInt("proid")
	// if err != nil {
	// 	proid = 0
	// }
	days, err := a.Ctx.URLParamInt("days")
	if err != nil {
		days = 7
	}
	if days > 30 {
		badRequest(a.Ctx, errors.New("非法参数"))
		return
	}
	vendorid := a.getVendorID(a.Ctx)
	datas, err := a.Service.GetLivelyOfNumDays(vendorid, days)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, map[string]interface{}{
		"chart": datas,
	})
}
