package controllers

import (
	"fmt"

	"github.com/astaxie/beego"
	validation "github.com/go-ozzo/ozzo-validation/v4"
	"github.com/go-ozzo/ozzo-validation/v4/is"

	"lc/common/models"
)

type RadarController struct {
	BaseController
}

type ReqRadar struct {
	Tenant       string `json:"tenant"`       //租户ID
	Code         string `json:"code"`         //设备编号，禁止修改
	GID          string `json:"gid"`          //网关ID
	Name         string `json:"name"`         //设备名称
	Brand        int    `json:"brand"`        //品牌
	Model        int    `json:"model"`        //型号
	IP           string `json:"ip"`           //IP地址
	Port         int    `json:"port"`         //端口
	SuggestSpeed int    `json:"suggestspeed"` //建议速度，提示限速
	State        int    `json:"state"`        //1启用，0禁用
}

func (a ReqRadar) Validate() error {
	return validation.ValidateStruct(&a,
		validation.Field(&a.Code, validation.Required, validation.Length(4, 32)),
		validation.Field(&a.GID, validation.Required, validation.Length(4, 32)),
		validation.Field(&a.Tenant, validation.Required, validation.Length(4, 8)),
		validation.Field(&a.IP, validation.Required, is.IP),
		validation.Field(&a.Port, validation.Required, validation.Min(80), validation.Max(65535)),
		validation.Field(&a.SuggestSpeed, validation.Required, validation.Min(0), validation.Max(300)),
		validation.Field(&a.State, validation.In(0, 1)),
	)
}

type ReqImportRadar struct {
	Tenant string  `json:"tenant"` //租户ID
	List   []Radar `json:"list"`   //列表
}

func (a ReqImportRadar) Validate() error {
	var rules []*validation.FieldRules
	rules = append(rules, validation.Field(&a.Tenant, validation.Required, validation.Length(4, 8)))
	rules = append(rules, validation.Field(&a.List, validation.Required))
	return validation.ValidateStruct(&a, rules...)
}

type Radar struct {
	Code         string `json:"code"`         //设备编号，禁止修改
	GID          string `json:"gid"`          //网关ID
	Name         string `json:"name"`         //设备名称
	Brand        int    `json:"brand"`        //品牌
	Model        int    `json:"model"`        //型号
	IP           string `json:"ip"`           //IP地址
	Port         int    `json:"port"`         //端口
	SuggestSpeed int    `json:"suggestspeed"` //建议速度，提示限速
	State        int    `json:"state"`        //1启用，0禁用
}

func (a Radar) Validate() error {
	return validation.ValidateStruct(&a,
		validation.Field(&a.Code, validation.Required, validation.Length(4, 32)),
		validation.Field(&a.GID, validation.Required, validation.Length(4, 32)),
		validation.Field(&a.IP, validation.Required, is.IP),
		validation.Field(&a.Port, validation.Required, validation.Min(80), validation.Max(65535)),
		validation.Field(&a.SuggestSpeed, validation.Required, validation.Min(0), validation.Max(300)),
		validation.Field(&a.State, validation.In(0, 1)),
	)
}

// CreateRadar @Title 创建雷达
// @Description 创建雷达
// @Param   body controllers.ReqRadar true "数据"
// @Success 0 {int} BaseResponse.Code "成功"
// @Failure 1 {int} BaseResponse.Code "失败"
// @router /v1/create [post]
func (o *RadarController) CreateRadar() {
	var obj ReqRadar
	if err := json.Unmarshal(o.Ctx.Input.RequestBody, &obj); err != nil {
		beego.Debug(string(o.Ctx.Input.RequestBody))
		o.Response(Failure, fmt.Sprintf("数据包解析错误:%s", err.Error()), nil)
		return
	}
	if err := obj.Validate(); err != nil {
		beego.Error(fmt.Sprintf("请求参数验证失败:%s", err.Error()))
		o.Response(Failure, fmt.Sprintf("请求参数验证失败:%s", err.Error()), nil)
		return
	}
	oo := models.RadarDevice{
		ID:           obj.Code,         //设备ID，DID
		Name:         obj.Name,         //集控器名称
		GID:          obj.GID,          //网关ID
		Brand:        obj.Brand,        //品牌
		Model:        obj.Model,        //型号
		DevType:      models.Radar,     //6雷达
		IP:           obj.IP,           //雷达IP
		Port:         uint16(obj.Port), //雷达端口
		Tenant:       obj.Tenant,       //租户ID
		SuggestSpeed: obj.SuggestSpeed, //建议速度阈值
		State:        obj.State,        //1启用，0禁用
	}
	if err := oo.SaveFromWeb(); err != nil {
		o.Response(Failure, fmt.Sprintf("数据插入失败:%s", err.Error()), nil)
		return
	}
	o.Response(Success, "成功", oo.ID)
}

// UpdateRadar @Title 更新雷达
// @Description 更新雷达
// @Param   body controllers.ReqConcentrator true "数据"
// @Success 0 {int} BaseResponse.Code "成功"
// @Failure 1 {int} BaseResponse.Code "失败"
// @router /v1/update [post]
func (o *RadarController) UpdateRadar() {
	var obj ReqRadar
	if err := json.Unmarshal(o.Ctx.Input.RequestBody, &obj); err != nil {
		beego.Debug(string(o.Ctx.Input.RequestBody))
		o.Response(Failure, fmt.Sprintf("数据包解析错误:%s", err.Error()), nil)
		return
	}
	if err := obj.Validate(); err != nil {
		beego.Error(fmt.Sprintf("请求参数验证失败:%s", err.Error()))
		o.Response(Failure, fmt.Sprintf("请求参数验证失败:%s", err.Error()), nil)
		return
	}
	oo := models.RadarDevice{
		ID:           obj.Code,         //设备ID，DID
		Name:         obj.Name,         //设备名称
		GID:          obj.GID,          //网关ID
		Brand:        obj.Brand,        //品牌
		Model:        obj.Model,        //型号
		DevType:      models.Radar,     //6，雷达
		IP:           obj.IP,           //雷达IP
		Port:         uint16(obj.Port), //雷达端口
		Tenant:       obj.Tenant,       //租户ID
		SuggestSpeed: obj.SuggestSpeed, //建议速度阈值
		State:        obj.State,        //1启用，0禁用
	}
	if err := oo.SaveFromWeb(); err != nil {
		o.Response(Failure, fmt.Sprintf("数据更新失败:%s", err.Error()), nil)
		return
	}
	o.Response(Success, "成功", oo.ID)
}

// DeleteRadar @Title 删除雷达
// @Description 删除雷达
// @Param   id    query   int     true "设备ID"
// @Success 0 {int} BaseResponse.Code "成功"
// @Failure 1 {int} BaseResponse.Code "失败"
// @router /v1/delete [post]
func (o *RadarController) DeleteRadar() {
	id := o.GetString("code")
	if id == "" {
		beego.Error("缺查询参数id")
		o.Response(Failure, "缺查询参数id", nil)
		return
	}
	c := models.RadarDevice{ID: id}
	if err := c.Delete(); err != nil {
		beego.Error(fmt.Sprintf("删除失败:%s", err.Error()))
		o.Response(Failure, fmt.Sprintf("数据删除失败:%s", err.Error()), nil)
		return
	}
	o.Response(Success, "成功", c.ID)
}

// ImportRadar @Title 导入雷达
// @Description 导入雷达
// @Param   body controllers.ReqImportCamera true "数据"
// @Success 0 {int} BaseResponse.Code "成功"
// @Failure 1 {int} BaseResponse.Code "失败"
// @router /v1/import [post]
func (o *RadarController) ImportRadar() {
	var obj ReqImportRadar
	if err := json.Unmarshal(o.Ctx.Input.RequestBody, &obj); err != nil {
		beego.Debug(string(o.Ctx.Input.RequestBody))
		o.Response(Failure, fmt.Sprintf("数据包解析错误:%s", err.Error()), nil)
		return
	}
	if err := obj.Validate(); err != nil {
		beego.Error(fmt.Sprintf("请求参数验证失败:%s", err.Error()))
		o.Response(Failure, fmt.Sprintf("请求参数验证失败:%s", err.Error()), nil)
		return
	}

	var resp []RespImport
	for _, v := range obj.List {
		var rsp RespImport
		rsp.Code = v.Code
		oo := models.RadarDevice{
			ID:           v.Code,         //设备ID，DID
			Name:         v.Name,         //设备名称
			GID:          v.GID,          //网关ID
			Brand:        v.Brand,        //品牌
			Model:        v.Model,        //型号
			DevType:      models.Radar,   //6，雷达
			IP:           v.IP,           //雷达IP
			Port:         uint16(v.Port), //雷达端口
			SuggestSpeed: v.SuggestSpeed, //建议速度阈值
			Tenant:       obj.Tenant,
			State:        v.State, //1启用，0禁用
		}
		err := oo.SaveFromWeb()
		if err != nil {
			rsp.Error = err.Error()
			beego.Error(fmt.Sprintf("数据导入失败,code=%s,失败原因:%s", v.Code, err.Error()))
		}
		resp = append(resp, rsp)
	}
	o.Response(Success, "成功", resp)
}
