package service

import (
	"fmt"
	"gin-vue-admin/global"
	"gin-vue-admin/model"
	"gin-vue-admin/utils"
)

func GetVcode(userId, mocId int) string {

	code := ""

	sqlStr := "SELECT code FROM vcode WHERE user_id = ? and moc_id = ? "

	global.GVA_DB.Raw(sqlStr, userId, mocId).Find(&code)
	if global.GVA_DB.Error != nil {
		fmt.Println(global.GVA_DB.Error)
		return code
	}

	if code != "" {
		return code
	}

	code = createCode()

	IpaddrData := model.Vcode{
		UserId: userId,
		MocId:  mocId,
		Code:   code,
	}

	global.GVA_DB.Table("vcode").Create(&IpaddrData)

	return code
}

func createCode() string {
	code := utils.GetRandStr2()

	cid := 0

	sqlStr := "SELECT count(code) as cid FROM vcode WHERE code = ? "

	global.GVA_DB.Raw(sqlStr, code).Find(&cid)
	if global.GVA_DB.Error != nil {
		fmt.Println(global.GVA_DB.Error)
		return code
	}
	if cid == 0 {
		return code
	}
	return createCode()
}

func GetIdByCode(code string) model.Vcode {
	data := new(model.Vcode)

	sqlStr := "SELECT user_id, moc_id, code FROM vcode WHERE code = ? "

	global.GVA_DB.Raw(sqlStr, code).Find(&data)
	if global.GVA_DB.Error != nil {
		fmt.Println(global.GVA_DB.Error)
		return model.Vcode{}
	}
	return *data
}

func GetVcodeList(mocId int) map[int]string {
	data := make([]model.Vcode, 0)

	sqlStr := "SELECT code, user_id FROM vcode WHERE moc_id = ? "

	global.GVA_DB.Raw(sqlStr, mocId).Find(&data)
	if global.GVA_DB.Error != nil {
		fmt.Println(global.GVA_DB.Error)
		return map[int]string{}
	}
	reply := make(map[int]string, 0)
	for _, v := range data {
		reply[v.UserId] = v.Code
	}
	return reply
}
