package db

import (
	"World/common"
	"World/utils"
	"common/logger"
	stat "common/statistic"
	_ "database/sql"
	_ "errors"
	"strconv"
	_ "strings"
	_ "sync"
)

func LoadPlayerTokenFromDB(uid int) (token string, err error) {
	cmd := "select token from " + user_tablename + " where id = " + strconv.Itoa(uid)
	rows, err := m_game_db.Query(cmd)
	if rows != nil {
		defer rows.Close()
	}
	if err != nil {
		logger.Notic("LoadPlayerTokenFromDB Query error:%v", err)
		return
	}
	for rows.Next() {
		var value string
		err = rows.Scan(&value)
		if err != nil {
			logger.Notic("LoadPlayerTokenFromDB scan error:%v", err)
			return
		}
		token = value
		return
	}
	err = common.ErrorsNotFoundPlayerInMysql
	return
}

func LoadPlayerFromDB(uid int) (*common.GamePlayer, error) {
	//	cmd := `select  COALESCE(id,0), COALESCE(mobile,''), COALESCE(passwd,''), COALESCE(avatar,''), COALESCE(avatar_thumb,''),
	//                COALESCE(nick_name,''), COALESCE(gender,0), COALESCE(user_marks,''), COALESCE(diamond_num,0), COALESCE(user_gold,0),
	//                COALESCE(games_max,0), COALESCE(clubs_max,0), COALESCE(current_games,0), COALESCE(current_clubs,0), COALESCE(point,0),
	//                COALESCE(reg_code,''), COALESCE(sale_code,''), COALESCE(card_type,0), COALESCE(token,''), COALESCE(device_type,0),
	//                COALESCE(reg_time,0),  COALESCE(last_login,0), COALESCE(is_online,0), COALESCE(room_id,0) from dtb_user_main `

	cmd := "select COALESCE(id,0) from dtb_user_main where id = " + strconv.Itoa(uid)
	rows, err := m_game_db.Query(cmd)
	if rows != nil {
		defer rows.Close()
	}
	if err != nil {
		logger.Info("LoadPlayerFromDB Query error:%v cmd:%v", err, cmd)
		return nil, err
	}
	for rows.Next() {
		var id int
		err = rows.Scan(&id)
		if err != nil {
			logger.Notic("LoadPlayerFromDB scan error:%v", err)
			return nil, err
		}

		logger.Info("id:%v", id)

		player := new(common.GamePlayer)
		player.UID = uid
		return player, nil
	}
	err = common.ErrorsNotFoundPlayerInMysql
	return nil, err
}

func UpdatePlayerMoney2DB(playerid uint32, money uint32) error {
	cmd := "update " + user_tablename + " set user_gold = " + strconv.Itoa(int(money)) + " where id = " + strconv.Itoa(int(playerid))
	rows, err := m_game_db.Query(cmd)
	if rows != nil {
		defer rows.Close()
	}
	if err != nil {
		logger.Notic("UpdatePlayerMoney2DB error:%v cmd:%v", err, cmd)
		return err
	}
	return nil
}

func LoadPlayerRemarksFromDB(uid int) (remarks string) {
	cmd := "select data from " + remarks_tablename + " where uid = " + strconv.Itoa(uid)
	rows, err := m_game_db.Query(cmd)
	if rows != nil {
		defer rows.Close()
	}
	if err != nil {
		logger.Notic("LoadPlayerRemarksFromDB query error:%v cmd:%d", err, cmd)
		return
	}
	for rows.Next() {
		var value string
		err = rows.Scan(&value)
		if err != nil {
			logger.Notic("LoadPlayerRemarksFromDB scan error:%v", err)
			return
		}
		remarks = value
		return
	}
	return
}

func InsertPlayerRemarks(playerID int32, data string) error {
	cmd := `INSERT INTO dtb_remarks (uid, data) VALUES (`

	cmd = cmd + strconv.Itoa(int(playerID)) + ",'" + data + "')"
	err := ExcuteCmd(cmd)

	if err != nil {
		logger.Notic("InsertPlayerRemarks ExcuteCmd error:%v cmd:%v", err, cmd)
		return err
	}

	return nil
}

func UpdatePlayerRemarks(playerID int32, data string) error {
	cmd := "UPDATE dtb_remarks SET data='" + data + "'" + " WHERE uid=" + strconv.Itoa(int(playerID))
	err := ExcuteCmd(cmd)

	if err != nil {
		logger.Notic("UpdatePlayerRemarks error:%v", err)
		return err
	}

	return nil
}

func UpdatePlayLeftGold(playerID uint32, num int32, roomid uint32) error {

	cmd := "INSERT into t_user_buyin_gold(user_id,left_gold,room_id) values(" + strconv.Itoa(int(playerID)) +
		"," + strconv.Itoa(int(num)) + "," + strconv.Itoa(int(roomid)) + ") on duplicate key update left_gold=" + strconv.Itoa(int(num))

	if num == 0 {
		cmd = "DELETE FROM t_user_buyin_gold where user_id = " + strconv.Itoa(int(playerID)) + " and " + "room_id = " + strconv.Itoa(int(roomid))
	}

	err := ExcuteCmd(cmd)

	if err != nil {
		logger.Notic("UpdatePlayLeftGold error:%v", err)
		return err
	}

	return nil
}

//如果宕机恢复玩家的金币
func RecoverPlayerGold() error {
	logger.Info("DO RecoverPlayerGold!")
	cmd := "SELECT user_id from t_user_buyin_gold group by(user_id)"
	rows, err := m_game_db.Query(cmd)

	userleftMap := map[int]int{}
	if rows != nil {
		defer rows.Close()
	}
	if err != nil {
		logger.Notic("RecoverPlayerGold query error:%v cmd:%d", err, cmd)
		return err
	}
	for rows.Next() {
		var id int
		err = rows.Scan(&id)
		if err != nil {
			logger.Notic("RecoverPlayerGold scan error:%v", err)
			continue
		}

		cmd1 := "SELECT sum(left_gold) from t_user_buyin_gold where user_id = " + strconv.Itoa(int(id))
		left_num, err1 := GetSingleIntValue(cmd1)
		if err1 != nil {
			logger.Notic("RecoverPlayerGold query1 error:%v cmd:%d", err, cmd)
			continue
		}
		userleftMap[id] = left_num
		logger.Info("get playerid:%v,left_value:%v", id, left_num)
	}

	for playerID, goldNum := range userleftMap {
		cmd := "select COALESCE(user_gold,0) from dtb_user_main where id =" + strconv.Itoa(int(playerID))
		origin, err := GetSingleIntValue(cmd)
		if err != nil {
			continue
		}

		var current int
		current = origin + (int(goldNum))
		//加上金币
		cmd = "UPDATE dtb_user_main SET user_gold = '" + strconv.Itoa(current) + "'where id =" + strconv.Itoa(int(playerID))
		err = ExcuteCmd(cmd)
		if err != nil {
			logger.Notic("RecoverPlayerGold query1 error:%v cmd:%d", err, cmd)
			continue
		}
		logger.Info("do return playerid:%v gold:%v", playerID, goldNum)

		utils.SendCurrencyReport(uint32(playerID), 0,
			stat.Currency_Channel_ReturnGold, stat.Currency_Type_Money,
			int(goldNum), int(origin), int(current), 0, "return player gold")

		//需要删除记录
		cmd = "delete from t_user_buyin_gold where user_id = " + strconv.Itoa(int(playerID))
		err = ExcuteCmd(cmd)
		if err != nil {
			logger.Notic("RecoverPlayerGold query1 error:%v cmd:%d", err, cmd)
			continue
		}

		logger.Info("return and delete playerid:%v gold:%v", playerID, goldNum)
	}

	logger.Info("RecoverPlayerGold finished!!")

	return nil
}
