package db

import (
	"World/common"
	"common/beegomap"
	"common/logger"
	"encoding/json"
	"fmt"
	"strconv"
	"sync"
	"time"
)

var (
	m_clubIncome      *beegomap.BeeMap //make(map[int]*common.ClubCreaterIncomeInfo)
	ClubIncome_locker sync.Mutex
)

func CheckAndLoadClubIncome(uid uint32) error {
	if m_clubIncome.Check(uint32(uid)) {
		return nil
	}
	return LoadClubIncome(int(uid))
}

func LoadClubIncome(uid int) error {
	cmd := fmt.Sprintf("select data from t_club_income where uid = %d", uid)
	rows, err := m_game_db.Query(cmd)
	if rows != nil {
		defer rows.Close()
	}
	if err != nil {
		//glog.Info("mysql select error:", err)
		return err
	}

	for rows.Next() {
		var value string
		err = rows.Scan(&value)
		if err != nil {
			logger.Notic("mysql handle result error:%v", err)
			return err
		}
		var data common.ClubCreaterIncomeInfo
		err = json.Unmarshal([]byte(value), &data)
		if err != nil {
			logger.Notic("unmarshal json failed:%v", err)
			return err
		}
		m_clubIncome.Set(uint32(uid), &data)

		break
	}
	return nil
}

func GetClubIncome(uid int) (*common.ClubCreaterIncomeInfo, error) {
	vv := m_clubIncome.Get(uint32(uid))
	if vv != nil {
		v := vv.(*common.ClubCreaterIncomeInfo)
		return v, nil
	}
	return nil, nil
}

func UpdateClubIncome(uid int, user *common.ClubCreaterIncomeInfo) {
	m_clubIncome.Set(uint32(uid), user)
	return
}

func SyncClubIncomeToDB(uid int) error {
	var err error = nil
	vv := m_clubIncome.Get(uint32(uid))
	if vv != nil {
		data := vv.(*common.ClubCreaterIncomeInfo)
		tmp, _ := json.Marshal(data)
		cmd := "replace into t_club_income values(?, ?)"
		rows, er := m_game_db.Query(cmd, uid, string(tmp))
		if rows != nil {
			defer rows.Close()
		}
		err = er
		if er != nil {
			logger.Info("mysql update error:%v", err, " for sql:%v", cmd)
		} else {
			logger.Info("mysql update success for sql:%v", cmd)
		}
	}
	return err
}

func RecordClubIncomeTransfer(uid uint32, amount int64) error {
	var err error
	logger.Info("RecordClubIncomeTransfer uid:%v amount:%v", uid, amount)

	//insert into t_club_income_transfer(uid, amount, time) values (2, 100, 0);
	cmd := "insert into t_club_income_transfer(uid, amount, time) values (" + strconv.Itoa(int(uid)) + "," + strconv.Itoa(int(amount)) + "," +
		strconv.Itoa(int(time.Now().Unix())) + ")"

	err = ExcuteCmd(cmd)

	return err
}
