package controllers

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

type FavoriteController struct {
	MainController
}

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

	body := server.Ctx.Input.RequestBody
	appRequest := models.Favorite{}
	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
	}

	checkFavorite := &models.Favorite{UserId: info.UserID, TaskTypeId: appRequest.TaskTypeId, Deleted: 0}
	err = mysql.GetMysqlInstace().Ormer.Read(checkFavorite, "user_id", "task_type_id", "deleted")
	if err == nil {
		server.respond(models.BusinessFailed, "You have already followed this model")
		return
	}
	timestamp := time.Now()
	appRequest.UserId = info.UserID
	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 *FavoriteController) Cancel() {
	info, err := server.Check()
	if err != nil {
		server.respond(http.StatusUnauthorized, err.Error())
		return
	}
	body := server.Ctx.Input.RequestBody
	appRequest := models.Favorite{}
	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
	}
	checkFavorite := &models.Favorite{UserId: info.UserID, TaskTypeId: appRequest.TaskTypeId, Deleted: 0}
	err = mysql.GetMysqlInstace().Ormer.Read(checkFavorite, "user_id", "task_type_id", "deleted")
	if err != nil {
		server.respond(models.BusinessFailed, "You have not followed this model")
		return
	}
	checkFavorite.UpdatedTime = time.Now()
	checkFavorite.Deleted = 1

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

func (server *FavoriteController) IsFavorite() {
	info, err := server.Check()
	if err != nil {
		server.respond(http.StatusUnauthorized, err.Error())
		return
	}
	body := server.Ctx.Input.RequestBody
	appRequest := models.Favorite{}
	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
	}
	responseData := struct {
		IsFavorite bool `json:"is_favorite"`
	}{
		IsFavorite: false,
	}
	checkFavorite := &models.Favorite{UserId: info.UserID, TaskTypeId: appRequest.TaskTypeId, Deleted: 0}
	err = mysql.GetMysqlInstace().Ormer.Read(checkFavorite, "user_id", "task_type_id", "deleted")
	if err != nil {
		server.respond(http.StatusOK, "", responseData)
		return
	}
	responseData.IsFavorite = true
	server.respond(http.StatusOK, "", responseData)
}

func (server *FavoriteController) Lists() {
	info, err := server.Check()
	if err != nil {
		server.respond(http.StatusUnauthorized, err.Error())
		return
	}
	body := server.Ctx.Input.RequestBody
	appRequest := models.AppRequest{}
	_ = json.Unmarshal(body, &appRequest) //解析body中数据
	logs.Debug("appRequest", appRequest, string(body))

	if appRequest.Page == 0 {
		appRequest.Page = 1
	}

	if appRequest.Size == 0 {
		appRequest.Size = 10
	}
	offset := (appRequest.Page - 1) * appRequest.Size

	type ResponseType struct {
		Id          int       `json:"id"`
		TaskTypeId  int       `json:"task_type_id,omitempty"`
		UserId      int       `json:"user_id"`
		Name        string    `json:"name"`
		CreatedTime time.Time `json:"created_time"`
	}
	var favorites []*ResponseType

	countQB, _ := orm.NewQueryBuilder("mysql")
	queryQB, _ := orm.NewQueryBuilder("mysql")

	countQB.Select("count(*) AS total").
		From("favorite").
		InnerJoin("task_type").On("favorite.task_type_id = task_type.id")

	queryQB.Select("favorite.id", "favorite.task_type_id", "favorite.user_id", "favorite.created_time",
		"task_type.name").
		From("favorite").
		InnerJoin("task_type").On("favorite.task_type_id = task_type.id")
	countQB.Where("favorite.deleted = 0")
	queryQB.Where("favorite.deleted = 0")
	if !(info.Role == 1 || info.Role == 2) {
		countQB.And(fmt.Sprintf("user_id = '%d'", info.UserID))
		queryQB.And(fmt.Sprintf("user_id = '%d'", info.UserID))
	}
	if appRequest.Keyword != "" {
		keyword := "%" + appRequest.Keyword + "%"
		countQB.And(fmt.Sprintf("name like '%s'", keyword))
		queryQB.And(fmt.Sprintf("name like '%s'", keyword))
	}
	queryQB.OrderBy("created_time").Desc().
		Limit(int(appRequest.Size)).Offset(int(offset))

	sql := countQB.String()
	var total int64
	_ = mysql.GetMysqlInstace().Ormer.Raw(sql).QueryRow(&total)

	// 导出 SQL 语句
	sql = queryQB.String()
	mysql.GetMysqlInstace().Ormer.Raw(sql).QueryRows(&favorites)

	responseData := struct {
		Total int64       `json:"total"`
		Data  interface{} `json:"data,omitempty"`
	}{
		Total: total,
		Data:  favorites,
	}
	server.respond(http.StatusOK, "", responseData)
}

func (server *FavoriteController) Times() {
	taskTypeId, err := server.GetInt("task_type_id")
	if err != nil || taskTypeId == 0 {
		type ResponseType struct {
			TaskTypeId int `json:"task_type_id,omitempty"`
		}
		body := server.Ctx.Input.RequestBody
		appRequest := ResponseType{}
		_ = json.Unmarshal(body, &appRequest) //解析body中数据
		logs.Debug("appRequest", appRequest, string(body))
		taskTypeId = appRequest.TaskTypeId
	}
	if taskTypeId == 0 {
		server.respond(models.MissingParameter, "Missing task_type_id parameter")
		return
	}

	countQB, _ := orm.NewQueryBuilder("mysql")
	countQB.Select("count(*) AS times").
		From("favorite").Where("deleted = 0").And(fmt.Sprintf("task_type_id = '%d'", taskTypeId))
	sql := countQB.String()
	var times int64
	_ = mysql.GetMysqlInstace().Ormer.Raw(sql).QueryRow(&times)
	responseData := struct {
		Times int64 `json:"times"`
	}{
		Times: times,
	}
	server.respond(http.StatusOK, "", responseData)
}
