package dao

import (
	"DataShare/global"
	"database/sql"
	"fmt"
	"github.com/sirupsen/logrus"
)

func GetMaxInt(fieldName string,tableName string,db *sql.DB)(int64,error){

	sqlstr := "select MAX(?) from ?"

	var maxId int64

	err := db.QueryRow(sqlstr,fieldName, tableName).Scan(&maxId)
	if err == sql.ErrNoRows {
		return 0,nil
	}

	return maxId,err
}

func GetMaxString(fieldName string,tableName string,db *sql.DB)(string,error){

	sqlstr := "select MAX(?) from ?"

	var maxStr string

	err := db.QueryRow(sqlstr,fieldName,tableName).Scan(&maxStr)
	if err == sql.ErrNoRows {
		return "",nil
	}

	return maxStr,err
}

func GetMaxValue(fieldName string,tableName string,db *sql.DB)(string,error){

	args := make([]interface{},0)
	//sqlstr := "select MAX(?) as maxVal from ?"
	//args = append(args,fieldName)
	//args = append(args,tableName)
	sqlstr := fmt.Sprintf("SELECT MAX(%s) as maxVal FROM %s",fieldName,tableName)

	stmt, err := db.Prepare(sqlstr)
	if err != nil {
		global.SystemLogger.Log(logrus.ErrorLevel,"Prepare(%s) failed, err:%s ",sqlstr,err.Error())
		return "", err
	}

	defer stmt.Close()
	var rows *sql.Rows
	rows, err = stmt.Query(args...)
	if err != nil {
		global.SystemLogger.Log(logrus.ErrorLevel,"query sql(%s) ,param(%v) failed, err:%s ",sqlstr,args,err.Error())
		return "", err
	}
	defer rows.Close()
	columns, err := rows.Columns()
	if err != nil {
		global.SystemLogger.Log(logrus.ErrorLevel,"rows.Columns sql(%s) ,param(%v) failed, err:%s ",sqlstr,args,err.Error())
		return "", err
	}

	tableData := make([]map[string]string, 0)
	count := len(columns)
	values := make([]interface{}, count)
	scanArgs := make([]interface{}, count)
	for i := range values {
		scanArgs[i] = &values[i]
	}

	for rows.Next() {
		err := rows.Scan(scanArgs...)
		if err != nil {
			global.SystemLogger.Log(logrus.ErrorLevel,"rows.Scan sql(%s) ,param(%v) failed, err:%s ",sqlstr,args,err.Error())
			return "", err
		}
		entry := make(map[string]string)
		for i, col := range columns {
			v := values[i]
			b, ok := v.([]byte)
			if (ok) {
				entry[col] = string(b)
			} else {
				//所有都转换成字符串输出
				strVal := fmt.Sprintf("%v",v)
				entry[col] = strVal
				//原类型输出
				//entry[col] = v
			}
		}
		tableData = append(tableData, entry)
	}
	if len(tableData)>0{
		return tableData[0]["maxVal"],nil
	}

	return "", nil
}