package gameapi

import (
	"../log"
	"../mod"
	pb "../protos"
	"bytes"
	"crypto/tls"
	"encoding/json"
	"go.uber.org/zap"
	"io/ioutil"
	"net/http"
	"strconv"
	"strings"
	"time"
)

const (
	ACCOUNT_EXISTED = 116 //已注册
)

var (
	Agent_Name = "HB05010101"
	HB_addr    = "https://api.hbo118.com"           //域名
	HB_key     = "27d64cc5834d4af881f3d2affe344980" //密钥

	hb_reg           = "/hbo/signup/" + Agent_Name + "/"  //注册路径
	hb_login         = "/hbo/login/" + Agent_Name + "/"   //登陆路径
	hb_balance       = "/hbo/getBalance/" + Agent_Name    //用户余额
	hb_add_deduct    = "/hbo/transfer/" + Agent_Name      //用户存取款
	hb_add_deduct_ok = "/hbo/checkTransfer/" + Agent_Name //检查存取款操作是否成功
	hb_kick_out      = "/hbo/offline/" + Agent_Name       //踢人
	hb_low_bet       = "/hbo/minBetLimit/" + Agent_Name   //设置余额最低下注额度
	hb_online_user   = "/hbo/online/" + Agent_Name        //获取在线会员列表
)

func Hongbo_update_var() {
	hb_reg = "/hbo/signup/" + Agent_Name + "/"            //注册路径
	hb_login = "/hbo/login/" + Agent_Name + "/"           //登陆路径
	hb_balance = "/hbo/getBalance/" + Agent_Name          //用户余额
	hb_add_deduct = "/hbo/transfer/" + Agent_Name         //用户存取款
	hb_add_deduct_ok = "/hbo/checkTransfer/" + Agent_Name //检查存取款操作是否成功
	hb_kick_out = "/hbo/offline/" + Agent_Name            //踢人
	hb_low_bet = "/hbo/minBetLimit/" + Agent_Name         //设置余额最低下注额度
	hb_online_user = "/hbo/online/" + Agent_Name          //获取在线会员列表
}

func Hongbo_Enter_game(guid string, gameParam []string, res *pb.S_EnterGame) {

	if len(gameParam) != 1 {
		res.Ec = SYS_GAME_PARAM_ERROR
		return
	}
	kindId := gameParam[0]
	reg_p := hb_reg_param{guid, Md5Encrypt(salt + guid), "CNY", 0.00}
	reg := hb_reg_header{time.Now().UnixNano() / 1e6, reg_p}

	var response hb_response_header
	if Hongbo_Request(hb_reg, reg, &response) { //尝试注册
		limit := limitP{20, 1000}
		login_p := hb_login_param{guid} //暂时不用登陆密码
		login := hb_login_header{time.Now().UnixNano() / 1e6, GenIpaddr(),limit, login_p}
		if Hongbo_Request(hb_login, login, &response) { //登陆成功
			res.Url = response.Url + "&gameId=" + kindId + "&runType=1&vertical="+strings.Split(response.List[0],"?")[0] //runType 0 纯粹浏览器 1 内嵌app
			res.GameParam = gameParam
			res.Ec = SUCCESS
			log.Debug("Hongbo login success", zap.String("guid", guid), zap.String("gamId", kindId))
		} else {
			log.Debug("Hongbo login faild", zap.String("guid", guid), zap.String("gamId", kindId), zap.Int("codeId", response.CodeId))
			res.Ec = SYS_LOGIN_FAILED
		}
	} else {
		log.Debug("Hongbo register faild", zap.String("guid", guid), zap.String("gamId", kindId), zap.Int("codeId", response.CodeId))
		res.Ec = SYS_REGIST_FAILED
	}
}

func Hongbo_Leave_game(guid string, balance *pb.S_Ntf_UserBalance, res *pb.S_LeaveGame) {

	res.Ec = SUCCESS
	// 取得余额
	guid_, err := strconv.ParseUint(guid, 10, 64)
	if err != nil {
		log.Debug("ParseUint err", zap.Error(err))
		balance.Balance = 0
		return
	}

	sbalance, err := mod.GetUserAttr(guid_, "balance")
	if err != nil {
		log.Debug("Hongbo_Leave_game GetUserAttr balance err", zap.Error(err))
		balance.Balance = 0
		return
	}
	balance.Balance, err = strconv.ParseInt(sbalance, 10, 64)
	if err != nil {
		balance.Balance = 0
		log.Error("ParseUint err", zap.Error(err))
		return
	}

	log.Debug("Hongbo getBalance success", zap.String("guid", guid), zap.Int64("Balance", balance.Balance))
}

func Hongbo_Request(path string, param interface{}, res *hb_response_header) bool {

	log.Debug("Hongbo_Request param", zap.Any("param", param))
	bytesData, err := json.Marshal(param)
	if err != nil {
		log.Debug("Hongbo_Request json.Marshal err", zap.Error(err))
		res.Ec = -1
		return false
	}

	reader := bytes.NewReader(bytesData)
	req, err := http.NewRequest("POST", HB_addr+path, reader)
	if err != nil {
		log.Debug("Hongbo_NewRequest err", zap.Error(err))
		res.Ec = -1
		return false
	}

	tr := &http.Transport{
		TLSClientConfig: &tls.Config{
			InsecureSkipVerify: true,
		},
	}

	client := &http.Client{Transport: tr}
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("token", Md5Encrypt(HB_key+string(bytesData)))

	resp, err := client.Do(req)
	if err != nil {
		log.Debug("Hongbo_Request client.Do", zap.Error(err))
		return false
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Debug("Hongbo_NewRequest ioutil.ReadAll err", zap.Error(err))
		res.Ec = -1
		return false
	}

	if err := json.Unmarshal(body, res); err != nil {
		log.Debug("Hongbo_Request json.Marshal err", zap.Error(err))
		res.Ec = -1
		return false
	}

	switch path {
	case hb_reg:
		if res.CodeId == SUCCESS || res.CodeId == ACCOUNT_EXISTED {
			res.Ec = 0
			log.Debug("Hongbo_Request reg success", zap.Int("CodeId", res.CodeId))
			return true
		}
	case hb_login:
		if res.CodeId == SUCCESS {
			res.Ec = 0
			res.Url = res.List[1] + res.Token
			log.Debug("Hongbo_Request login success", zap.String("Url", res.Url))
			return true
		}
	case hb_balance:
		if res.CodeId == SUCCESS {
			res.Ec = 0
			log.Debug("Hongbo_Request get balance success")
			return true
		}
	}
	res.Ec = -1
	return false
}
