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"
	"sort"
	"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))
}

type vendorList struct {
	Records          []vendorListNew `json:"records"`
	Total            int             `json:"total"`
	Size             int             `json:"size"`
	Current          int             `json:"current"`
	Orders           []interface{}   `json:"orders"`
	OptimizeCountSQL bool            `json:"optimizeCountSql"`
	HitCount         bool            `json:"hitCount"`
	SearchCount      bool            `json:"searchCount"`
	Pages            int             `json:"pages"`
}
type vendorListNew struct {
	ID         int    `json:"id"`
	Vender     string `json:"vender"`
	Brand      string `json:"brand"`
	Model      string `json:"model"`
	Pid        int
	DeviceType int `json:"deviceType"`
}

func (c *utilCtl) GetVenderList(ctx *gin.Context) {
	var result vendorList
	deviceType := ctx.Query("deviceType")
	if deviceType == "" {
		deviceType = "-1"
	}
	venderValue := ctx.Query("venderValue")
	current := ctx.Query("current")
	size := ctx.Query("size")
	offset, _ := strconv.Atoi(current)
	limit, _ := strconv.Atoi(size)
	if offset == 0 {
		offset = 1
		limit = 10
	}
	value, _ := ctx.Get(middleware.Authorization)
	claims := value.(*middleware.Claims)
	deviceTypeInt, _ := strconv.Atoi(deviceType)
	vendors, _, err := service.UtilService.GetDeviceVendorList(claims.TenantId, venderValue, deviceTypeInt, offset, limit)
	vendorsMap := make(map[int]vendorListNew)
	vendorListNews1 := make(map[int]vendorListNew)
	vendorListNews2 := make(map[int]vendorListNew)
	vendorListNews3 := make(map[int]vendorListNew)
	for _, vendor := range vendors {
		vendorsMap[vendor.ID] = vendorListNew{
			ID:         vendor.ID,
			Vender:     vendor.VendorValue,
			DeviceType: vendor.DeviceType,
			Pid:        vendor.ParentId,
		}
		if vendor.VendorType == 3 {
			vendorListNews3[vendor.ID] = vendorsMap[vendor.ID]
		}
		if vendor.VendorType == 2 {
			vendorListNews2[vendor.ID] = vendorsMap[vendor.ID]
		}
		if vendor.VendorType == 1 {
			vendorListNews1[vendor.ID] = vendorsMap[vendor.ID]
		}
	}
	var vendorListNews []vendorListNew
	for _, listNew := range vendorListNews3 {
		vendorListNews = append(vendorListNews, vendorListNew{
			ID:         listNew.ID,
			Vender:     vendorListNews1[vendorListNews2[listNew.Pid].Pid].Vender,
			Brand:      vendorListNews2[listNew.Pid].Vender,
			Model:      listNew.Vender,
			DeviceType: listNew.DeviceType,
			Pid:        listNew.Pid,
		})
	}
	sort.Slice(vendorListNews, func(i, j int) bool {
		return vendorListNews[i].ID > vendorListNews[j].ID
	})

	if err != nil {
		ctx.JSON(http.StatusOK, common.FailResponse(err.Error(), nil))
		return
	}
	result.Records = vendorListNews
	result.Total = len(vendorListNews)
	ctx.JSON(http.StatusOK, common.SuccessResponse("", result))
}

func (c *utilCtl) GetVenderDetail(ctx *gin.Context) {
	//idStr := ctx.Query("id")
	//var vendorListNew vendorListNew
	//id, _ := strconv.Atoi(idStr)
	ctx.JSON(http.StatusOK, common.SuccessResponse("", nil))
}

func (c *utilCtl) GetVenderRemove(ctx *gin.Context) {
	idStr := ctx.Query("id")
	id, _ := strconv.Atoi(idStr)
	err := service.UtilService.GetRemoveVendor(id)
	if err != nil {
		ctx.JSON(http.StatusOK, common.FailResponse(err.Error(), nil))
		return
	}
	ctx.JSON(http.StatusOK, common.SuccessResponse("", nil))
}

func (c *utilCtl) GetVenderSubmit(ctx *gin.Context) {
	ctx.JSON(http.StatusOK, common.SuccessResponse("", nil))
}
