package db

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

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

func CheckAndLoadAlliIncome(uid uint32) error {
	if m_alliIncome.Check(uint32(uid)) {
		return nil
	}
	return LoadAlliIncome(int(uid))
}

func LoadAlliIncome(uid int) error {
	cmd := fmt.Sprintf("select data from t_alli_income where uid = %d", uid)

	rows, err := m_game_db.Query(cmd)
	if rows != nil {
		defer rows.Close()
	}
	if err != nil {
		logger.Notic("mysql select cmd:%v error:%v", cmd, 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.AlliCreaterIncomeInfo
		err = json.Unmarshal([]byte(value), &data)
		if err != nil {
			logger.Notic("unmarshal json failed:%v for:%v", err, value)
			return err
		}
		m_alliIncome.Set(uint32(uid), &data)

		break
	}
	return nil
}

func GetAlliIncome(uid int) (*common.AlliCreaterIncomeInfo, error) {
	vv := m_alliIncome.Get(uint32(uid))
	if vv != nil {
		v := vv.(*common.AlliCreaterIncomeInfo)
		return v, nil
	}
	return nil, nil
}

func UpdateAlliIncome(uid int, user *common.AlliCreaterIncomeInfo) {
	m_alliIncome.Set(uint32(uid), user)
	return
}

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

func RecordAlliIncomeTransfer(uid uint32, amount int64) error {
	var err error
	//insert into t_alli_income_transfer(uid, amount, time) values (2, 100, 0);
	cmd := "insert into t_alli_income_transfer(uid, amount, time) values (" + strconv.Itoa(int(uid)) + "," + strconv.Itoa(int(amount)) + "," +
		strconv.Itoa(int(time.Now().Unix())) + ")"

	if err = ExcuteCmd(cmd); err != nil {
		logger.Notic("RecordAlliIncomeTransfer failed! err:%v", err)
	}

	return err
}
