package controllers

import (
	"fmt"
	"strings"

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

	"lc/common/models"
)

type SensorController struct {
	BaseController
}

type ReqSensor struct {
	Code   string  `json:"code"`   //设备编号，禁止修改
	GID    string  `json:"gid"`    //网关ID
	Tenant string  `json:"tenant"` //租户ID
	Name   string  `json:"name"`   //设备名称
	Brand  int     `json:"brand"`  //品牌
	Model  int     `json:"model"`  //型号
	Height float32 `json:"height"` //安装高度
	State  int     `json:"state"`  //1启用，0禁用
}

func (a ReqSensor) 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.State, validation.In(0, 1)),
	)
}

type Sensor struct {
	Code   string  `json:"code"`   //设备编号，禁止修改
	GID    string  `json:"gid"`    //网关ID
	Name   string  `json:"name"`   //设备名称
	Brand  int     `json:"brand"`  //品牌
	Model  int     `json:"model"`  //型号
	Height float32 `json:"height"` //安装高度
	State  int     `json:"state"`  //1启用，0禁用
}

func (a Sensor) 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.State, validation.In(0, 1)),
	)
}

type ReqImportSensor struct {
	Tenant string   `json:"tenant"` //租户ID
	List   []Sensor `json:"list"`   //传感器列表
}

func (a ReqImportSensor) Validate() error {
	return validation.ValidateStruct(&a,
		validation.Field(&a.Tenant, validation.Required, validation.Length(4, 32)),
		validation.Field(&a.List, validation.Required),
	)
}

// CreateSensor @Title 创建传感器设备
// @Description 创建传感器设备
// @Param   body controllers.ReqSensor true "数据"
// @Success 0 {int} BaseResponse.Code "成功"
// @Failure 1 {int} BaseResponse.Code "失败"
// @router /v1/create [post]
func (o *SensorController) CreateSensor() {
	var obj ReqSensor
	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.DeviceSensor{
		ID:     obj.Code,
		GID:    obj.GID,
		Name:   obj.Name,
		Tenant: obj.Tenant,
		Brand:  obj.Brand,
		Model:  obj.Model,
		Height: obj.Height,
		State:  obj.State,
	}
	if err := oo.SaveFromWeb(); err != nil {
		o.Response(Failure, fmt.Sprintf("数据插入失败:%s", err.Error()), nil)
		return
	}
	o.Response(Success, "成功", oo.ID)
}

// UpdateSensor @Title 更新传感器设备
// @Description 更新传感器设备
// @Param   body body controllers.ReqSensor true "数据"
// @Success 0 {int} BaseResponse.Code "成功"
// @Failure 1 {int} BaseResponse.Code "失败"
// @router /v1/update [post]
func (o *SensorController) UpdateSensor() {
	var obj ReqSensor
	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.DeviceSensor{
		ID:     obj.Code,
		GID:    obj.GID,
		Name:   obj.Name,
		Tenant: obj.Tenant,
		Brand:  obj.Brand,
		Model:  obj.Model,
		Height: obj.Height,
		State:  obj.State,
	}
	if err := oo.SaveFromWeb(); err != nil {
		o.Response(Failure, fmt.Sprintf("数据更新失败:%s", err.Error()), nil)
		return
	}
	o.Response(Success, "成功", oo.ID)
}

// DeleteSensor @Title 删除传感器设备
// @Description 删除传感器设备
// @Param   code    query   string     true "设备ID"
// @Success 0 {int} BaseResponse.Code "成功"
// @Failure 1 {int} BaseResponse.Code "失败"
// @router /v1/delete [post]
func (o *SensorController) DeleteSensor() {
	code := strings.Trim(o.GetString("code"), " ")
	if err := validation.Validate(code, validation.Required, validation.Length(4, 100)); err != nil {
		beego.Error(fmt.Sprintf("请求参数验证失败:%s", err.Error()))
		o.Response(Failure, fmt.Sprintf("请求参数验证失败:%s", err.Error()), nil)
		return
	}
	c := models.DeviceSensor{
		ID: code,
	}
	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)
}

// ImportSensor @Title 导入环境监测设备
// @Description 导入环境监测设备
// @Param   body body controllers.ReqImportEnvironment true "数据"
// @Success 0 {int} BaseResponse.Code "成功"
// @Failure 1 {int} BaseResponse.Code "失败"
// @router /v1/import [post]
func (o *SensorController) ImportSensor() {
	var obj ReqImportSensor
	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 aresp RespImport
		aresp.Code = v.Code
		oo := models.DeviceSensor{
			ID:     v.Code,
			GID:    v.GID,
			Name:   v.Name,
			Tenant: obj.Tenant,
			Brand:  v.Brand,
			Model:  v.Model,
			Height: v.Height,
			State:  v.State,
		}
		err := oo.SaveFromWeb()
		if err != nil {
			aresp.Error = err.Error()
			beego.Error(fmt.Sprintf("传感器数据导入失败,code=%s,失败原因:%s", v.Code, err.Error()))
		}
		resp = append(resp, aresp)
	}
	o.Response(Success, "成功", resp)
}
