package dbUtil

import (
	"encoding/json"
	"fmt"
	"os"
	"strings"

	"github.com/gomodule/redigo/redis"
	"github.com/shopspring/decimal"
)

const (
	TopicParticipate = "0xddd670a4142d06229b922c5d433d29131580e1a2952c86700b0a36ea9e8b87ee"
	FuncParticipate  = "participate"
)

//var conn redis.Conn
var pool *redis.Pool
var TopsMap map[string]string
var MethodMap map[string]string
var LvMap map[int]decimal.Decimal

func init() {
	pool = &redis.Pool{
		MaxIdle:     500,
		MaxActive:   2000,
		IdleTimeout: 120,
		Dial: func() (redis.Conn, error) {
			coon, err := redis.Dial("tcp", "127.0.0.1:6379")
			if err != nil {
				fmt.Println(err)
				os.Exit(1)
			}
			coon.Send("auth", "0x817A=7%BJ#x%H=1rK")
			return coon, err
		},
	}
	tm := make(map[string]string, 0)
	// tm["0xddd670a4142d06229b922c5d433d29131580e1a2952c86700b0a36ea9e8b87ee"] = "newDeposit"
	// tm["0x056f1f5cdd8662230b94b7f88e06d95549d18e77cb2959933db3849d36df790a"] = "newWithdraw"
	tm[TopicParticipate] = FuncParticipate
	TopsMap = tm

	mm := make(map[string]string, 0)
	mm["transferFrom"] = "Transfer"
	mm["sell"] = "SellOrder"
	MethodMap = mm

	lm := make(map[int]decimal.Decimal, 0)
	lm[1] = decimal.NewFromFloat(0.1)
	lm[2] = decimal.NewFromFloat(0.08)
	lm[3] = decimal.NewFromFloat(0.03)
	lm[4] = decimal.NewFromFloat(0.03)
	lm[5] = decimal.NewFromFloat(0.03)
	lm[6] = decimal.NewFromFloat(0.03)
	lm[7] = decimal.NewFromFloat(0.03)
	lm[8] = decimal.NewFromFloat(0.03)
	lm[9] = decimal.NewFromFloat(0.03)
	lm[10] = decimal.NewFromFloat(0.03)
	LvMap = lm
}

func GetValue(key string, t int) interface{} {
	rc := pool.Get()
	defer rc.Close()
	key = strings.ToLower(key)
	if t == 1 {
		i, e := rc.Do("get", key)
		if e != nil {
			fmt.Println("e=", e)
			return 0
		}
		reply, _ := redis.Int64(i, e)
		return reply
	} else if t == 2 {
		//fmt.Println("GetValue key=",key)
		r, e := rc.Do("GET", key)
		if e != nil {
			//fmt.Println("eeeeee=",e)
			return nil
		}
		//fmt.Println("=rrrrr==",r)
		reply, err := redis.Bytes(r, e)
		if err != nil {
			//fmt.Println("错误13331=",err)
			return nil
		}
		//fmt.Println("===",string(reply))
		var d *[]string
		err = json.Unmarshal(reply, &d)
		if err != nil {
			fmt.Println("错误11=", err)
		}
		//fmt.Printf("d2结果的原始类型%T,值为%v\n", d, *d)
		return *d
	} else if t == 3 {
		i, e := rc.Do("get", key)
		if e != nil {
			fmt.Println("e=", e)
			return 0
		}
		reply, _ := redis.String(i, e)
		return reply
	} else {
		return ""
	}
}

func SetValue(key string, value interface{}) {
	rc := pool.Get()
	defer rc.Close()
	key = strings.ToLower(key)
	rc.Do("set", key, value)
}

func SetValueTime(key string, value interface{}, t int64) {
	rc := pool.Get()
	defer rc.Close()
	key = strings.ToLower(key)
	rc.Do("set", key, value, "EX", t)
}

func DeleteValue(key string) {
	rc := pool.Get()
	defer rc.Close()
	rc.Do("DEL", key)
}
