package controllers

import (
	"ai_developer_admin/libs/mysql"
	"ai_developer_admin/models"
	"encoding/json"
	"fmt"
	"github.com/beego/beego/v2/core/logs"
	"net/http"
	"sort"
	"strings"
	"time"
)

type VersionController struct {
	MainController
}

func (server *VersionController) Add() {
	_, err := server.Check()
	if err != nil {
		server.respond(http.StatusUnauthorized, err.Error())
		return
	}

	body := server.Ctx.Input.RequestBody
	appRequest := models.TaskTypeVersion{}
	err = json.Unmarshal(body, &appRequest) //解析body中数据
	logs.Debug("appRequest", appRequest)
	if err != nil {
		server.respond(models.NoRequestBody, err.Error())
		return
	}
	if appRequest.TaskTypeId == 0 {
		server.respond(models.MissingParameter, "Missing task_type_id parameter")
		return
	}

	timestamp := time.Now()
	appRequest.CreatedTime = timestamp
	appRequest.UpdatedTime = timestamp
	appRequest.Deleted = 0

	_, err = mysql.GetMysqlInstace().Ormer.Insert(&appRequest)
	if err != nil {
		server.respond(models.BusinessFailed, err.Error())
		return
	}
	server.respond(http.StatusOK, "success")
}

func (server *VersionController) Update() {
	_, err := server.Check()
	if err != nil {
		server.respond(http.StatusUnauthorized, err.Error())
		return
	}

	body := server.Ctx.Input.RequestBody
	appRequest := models.TaskTypeVersion{}
	err = json.Unmarshal(body, &appRequest) //解析body中数据
	logs.Debug("appRequest", appRequest)
	if err != nil {
		server.respond(models.NoRequestBody, err.Error())
		return
	}
	if appRequest.Id == 0 {
		server.respond(models.MissingParameter, "Missing id parameter")
		return
	}
	//if appRequest.TaskTypeId == 0 {
	//	server.respond(models.MissingParameter, "Missing task_type_id parameter")
	//	return
	//}

	checkVersion := &models.TaskTypeVersion{Id: appRequest.Id}
	err = mysql.GetMysqlInstace().Ormer.Read(checkVersion)
	if err != nil {
		server.respond(models.BusinessFailed, err.Error())
		return
	}

	timestamp := time.Now()
	appRequest.CreatedTime = checkVersion.CreatedTime
	appRequest.UpdatedTime = timestamp

	_, err = mysql.GetMysqlInstace().Ormer.Update(&appRequest)
	if err != nil {
		server.respond(models.BusinessFailed, err.Error())
		return
	}
	server.respond(http.StatusOK, "success")
}

func (server *VersionController) Delete() {
	_, err := server.Check()
	if err != nil {
		server.respond(http.StatusUnauthorized, err.Error())
		return
	}

	body := server.Ctx.Input.RequestBody
	appRequest := models.TaskTypeVersion{}
	err = json.Unmarshal(body, &appRequest) //解析body中数据
	logs.Debug("appRequest", appRequest)
	if err != nil {
		server.respond(models.NoRequestBody, err.Error())
		return
	}
	if appRequest.Id == 0 {
		server.respond(models.MissingParameter, "Missing id parameter")
		return
	}
	//if appRequest.TaskTypeId == 0 {
	//	server.respond(models.MissingParameter, "Missing task_type_id parameter")
	//	return
	//}

	checkVersion := &models.TaskTypeVersion{Id: appRequest.Id}
	err = mysql.GetMysqlInstace().Ormer.Read(checkVersion)
	if err != nil {
		server.respond(models.BusinessFailed, err.Error())
		return
	}

	timestamp := time.Now()
	checkVersion.UpdatedTime = timestamp
	checkVersion.Deleted = 1

	_, err = mysql.GetMysqlInstace().Ormer.Update(&appRequest)
	if err != nil {
		server.respond(models.BusinessFailed, err.Error())
		return
	}
	server.respond(http.StatusOK, "success")
}

func (server *VersionController) Lists() {
	body := server.Ctx.Input.RequestBody
	appRequest := models.TaskTypeVersion{}
	err := json.Unmarshal(body, &appRequest) //解析body中数据
	logs.Debug("appRequest", appRequest)
	if err != nil {
		server.respond(models.NoRequestBody, err.Error())
		return
	}

	if appRequest.TaskTypeId == 0 {
		server.respond(models.MissingParameter, "Missing task_type_id parameter")
		return
	}

	qs := mysql.GetMysqlInstace().Ormer.QueryTable("task_type_version").
		Filter("deleted", 0).Filter("task_type_id", appRequest.TaskTypeId).OrderBy("-created_time")
	count, err := qs.Count()
	var lists []*models.TaskTypeVersion
	if count > 0 {
		qs.All(&lists)
	}
	temp := make(map[string][]*models.TaskTypeVersion)
	for _, value := range lists {
		temp[value.Version] = append(temp[value.Version], value)
	}
	keys := make([]string, 0, len(temp))
	for key := range temp {
		keys = append(keys, key)
	}
	sort.Slice(keys, func(i, j int) bool {
		return compareVersion(keys[i], keys[j]) > 0
	})
	group := make(map[string][]*models.TaskTypeVersion)
	for _, value := range keys {
		group[value] = temp[value]
	}
	server.respond(http.StatusOK, "", group)
}

func compareVersion(v1, v2 string) int {
	// 将版本号字符串按 "." 分割为切片
	v1Parts := strings.Split(v1, ".")
	v2Parts := strings.Split(v2, ".")

	// 比较每个部分的数字大小
	for i := 0; i < len(v1Parts) && i < len(v2Parts); i++ {
		part1 := v1Parts[i]
		part2 := v2Parts[i]

		num1 := parseInt(part1)
		num2 := parseInt(part2)

		if num1 < num2 {
			return -1
		} else if num1 > num2 {
			return 1
		}
	}

	// 如果两个版本号相同，但长度不同，则长度较长的版本号更大
	if len(v1Parts) < len(v2Parts) {
		return -1
	} else if len(v1Parts) > len(v2Parts) {
		return 1
	}

	// 版本号相同
	return 0
}

func parseInt(s string) int {
	var result int
	fmt.Sscanf(s, "%d", &result)
	return result
}
