package utils

import (
	"encoding/json"
	"exam_system/result"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/jmoiron/sqlx"
	"sort"
	"strconv"
	"strings"
)

const (
	StudentPath        = "./file/考生信息导出.xlsx"
	ScorePath          = "./file/成绩导出.xlsx"
	SubTemplatePath    = "./file/试题模板.zip"
	StuTemplatePath    = "./file/考生模板.zip"
	SingelChoicePath   = "./file/单选题.xlsx"
	CompletionPath     = "./file/填空题.xlsx"
	MultipleChoicePath = "./file/多选题.xlsx"
	JudgementPath      = "./file/判断题.xlsx"
)

// Page 分页解析
func Page(c *gin.Context) (page, size int, sort string, query map[string]interface{}, err error) {
	sizeStr := c.Query("size")
	pageStr := c.Query("page")
	queryStr := c.Query("query")
	sort = c.Query("sort")

	size, err = strconv.Atoi(sizeStr)
	if err != nil {
		return
	}
	page, err = strconv.Atoi(pageStr)
	if err != nil {
		return
	}

	query = make(map[string]interface{})
	if queryStr != "" {
		err = json.Unmarshal([]byte(queryStr), &query)
		if err != nil {
			return
		}
	}

	return
}

func PostionSize(page, size int) int {
	position := (page - 1) * size
	return position
}

// Transation 事务
func Transation(tx *sqlx.Tx, err error, fn func(tx *sqlx.Tx) *result.Result) *result.Result {
	defer func() {
		if p := recover(); p != nil {
			tx.Rollback()
			panic(p) // re-throw panic after Rollback
		} else if err != nil {
			fmt.Println("rollback")
			tx.Rollback() // err is non-nil; don't change it
		} else {
			err = tx.Commit() // err is nil; if Commit returns error update err
			fmt.Println("commit")
		}
	}()
	return fn(tx)
}

// SubjectFormat A转0
func SubjectFormat(answer string) string {

	answer = strings.ToUpper(answer)
	answer = strings.Replace(answer, "A", "1", 1)
	answer = strings.Replace(answer, "B", "2", 1)
	answer = strings.Replace(answer, "C", "3", 1)
	answer = strings.Replace(answer, "D", "4", 1)
	// 排序
	return SubjectSort(answer)
}

func SubjectSort(answer string) string{
	slice := strings.Split(answer, "")
	sort.Strings(slice)
	answer = strings.Join(slice,"")
	return answer
}

// SubjectParse 0转A
func SubjectParse(answer string)string{

	answer = strings.Replace(answer, "1", "A", 1)
	answer = strings.Replace(answer, "2","B" , 1)
	answer = strings.Replace(answer, "3", "C", 1)
	answer = strings.Replace(answer, "4", "D", 1)

	return answer
}