package controllers

import (
	"fmt"
	"strings"

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

	"lc/common/models"
)

type EnvironmentController struct {
	BaseController
}

type ReqEnvironment 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"`  //型号
	State  int    `json:"state"`  //1启用，0禁用
}

func (a ReqEnvironment) 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 Environment struct {
	Code  string `json:"code"`  //设备编号，禁止修改
	GID   string `json:"gid"`   //网关ID
	Name  string `json:"name"`  //设备名称
	Brand int    `json:"brand"` //品牌
	Model int    `json:"model"` //型号
	State int    `json:"state"` //1启用，0禁用
}

func (a Environment) 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 ReqImportEnvironment struct {
	Tenant string        `json:"tenant"` //租户ID
	List   []Environment `json:"list"`   //网关列表
}

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

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

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

// DeleteEnvironment @Title 删除环境监测设备
// @Description 删除环境监测设备
// @Param   code    query   string     true "设备ID"
// @Success 0 {int} BaseResponse.Code "成功"
// @Failure 1 {int} BaseResponse.Code "失败"
// @router /v1/delete [post]
func (o *EnvironmentController) DeleteEnvironment() {
	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.DeviceEnvironment{
		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)
}

// ImportEnvironment @Title 导入环境监测设备
// @Description 导入环境监测设备
// @Param   body body controllers.ReqImportEnvironment true "数据"
// @Success 0 {int} BaseResponse.Code "成功"
// @Failure 1 {int} BaseResponse.Code "失败"
// @router /v1/import [post]
func (o *EnvironmentController) ImportEnvironment() {
	var obj ReqImportEnvironment
	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.DeviceEnvironment{
			ID:     v.Code,
			GID:    v.GID,
			Name:   v.Name,
			Tenant: obj.Tenant,
			Brand:  v.Brand,
			Model:  v.Model,
			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)
}
