package controller

import (
	"github.com/gin-gonic/gin"
	"iot_manager_service/app/device/model"
	"iot_manager_service/app/device/service"
	"iot_manager_service/app/middleware"
	"iot_manager_service/util/common"
	"net/http"
	"strconv"
)

// 工具服务
var Util = new(utilCtl)

type utilCtl struct{}

// GetModelList 获取厂家/品牌/型号列表
// 查询类型 type：1-厂家,2-品牌,3-型号
//deviceType 设备类型
//0-摄像头
//1 灯控
//2 信息屏
//3 配电箱
//4  网关
//5  环境监测
//6  ZigBee
//7  一键告警终端
//8 一键告警服务端
//11 桥梁传感器
//12 ip音柱
//13 井盖
//14 垃圾桶
func (c *utilCtl) GetModelList(ctx *gin.Context) {
	t := ctx.Query("type")
	d := ctx.Query("deviceType")
	id := ctx.Query("id")
	pid := ctx.Query("pid")
	modeType, err := strconv.Atoi(t)
	if err != nil || modeType < 1 || modeType > 3 {
		ctx.JSON(http.StatusOK, common.ParamsInvalidResponse("type invalid", nil))
		return
	}
	modeType++ //前端传入的1和2，实际是2和3

	deviceType, err := strconv.Atoi(d)
	if err != nil {
		ctx.JSON(http.StatusOK, common.ParamsInvalidResponse("deviceType invalid", nil))
		return
	}
	parentId := -1
	if id != "" {
		parentId, _ = strconv.Atoi(id)
	} else if pid != "" {
		parentId, _ = strconv.Atoi(pid)
	}

	value, _ := ctx.Get(middleware.Authorization)
	claims := value.(*middleware.Claims)

	var result []model.VendorDetail
	if modeType == model.TypeVendor {
		vendors, err := service.UtilService.GetDeviceVendor(claims.TenantId, deviceType)
		if err != nil {
			ctx.JSON(http.StatusOK, common.FailResponse(err.Error(), nil))
			return
		}
		for _, vendor := range vendors {
			result = append(result, model.VendorDetail{
				Id:       vendor.ID,
				ParentId: vendor.ParentId,
				Vendor:   vendor.VendorValue,
			})
		}
	} else if modeType == model.TypeBrand {
		vendors, err := service.UtilService.GetDeviceBrand(claims.TenantId, deviceType)
		if err != nil {
			ctx.JSON(http.StatusOK, common.FailResponse(err.Error(), nil))
			return
		}
		for _, vendor := range vendors {
			result = append(result, model.VendorDetail{
				Id:       vendor.ID,
				ParentId: vendor.ParentId,
				Brand:    vendor.VendorValue,
			})
		}
	} else if modeType == model.TypeModel {
		vendors, err := service.UtilService.GetDeviceModel(claims.TenantId, deviceType, parentId)
		if err != nil {
			ctx.JSON(http.StatusOK, common.FailResponse(err.Error(), nil))
			return
		}
		for _, vendor := range vendors {
			result = append(result, model.VendorDetail{
				Id:       vendor.ID,
				ParentId: vendor.ParentId,
				Model:    vendor.VendorValue,
			})
		}
	}
	ctx.JSON(http.StatusOK, common.SuccessResponse("", result))
}

func (c *utilCtl) GetTenantCode(ctx *gin.Context) {
	value, _ := ctx.Get(middleware.Authorization)
	claims := value.(*middleware.Claims)
	id := claims.TenantId
	code, _ := service.UtilService.GetTenantCode(id)
	code.CityCode = ctx.Query("type") + code.CityCode
	ctx.JSON(http.StatusOK, common.SuccessResponse(common.Succeeded, code))
}
