package gameapi

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

var Fg_url = "https://api.ppro.98078.net"
var Fg_merchantname = "uat_kg191113" //代理商名称
var Fg_merchantcode = "196f947f9c00ee8e20af23cc0d5b5926" //代理商密码

const (
	fg_reg_uri = "/v3/players"
	fg_deposit_withdraw_uri = "/v3/player_uchips/member_code/"
	fg_balance_uri = "/v3/player_chips/member_code/"
	fg_login_uri = "/v3/launch_game/"
	VG_MAINTAIN = "207" //返回207 说明接入游戏商正在维护
)

func FG_Enter_game(guid string, gameParam []string, cash int64, isReconnect bool, res *pb.S_EnterGame) {

	if len(gameParam) != 1 {
		res.Ec = SYS_GAME_PARAM_ERROR
		return
	}
	//cash_ := fg_convertBalance(cash) //1:100

	//1.注册
	ok,obj := fg_Post(fg_reg_uri, fg_register_p(guid, Md5Encrypt(guid)))
	if !ok {
		if obj.Code == 207 {
			res.Ec = MAINTAIN
		}else{
			res.Ec = SYS_REGIST_FAILED
		}
		log.Debug("FG_Enter_game register failed")
		return
	}
	//2.登陆
	game_id,err := strconv.Atoi(gameParam[0])
	if err != nil{
		log.Debug("FG_Enter_game strconv.Atoi",zap.Error(err))
	}
	ok2, back2 := fg_Post(fg_login_uri, fg_login_p( guid, game_id,"h5","zh-cn","127.0.0.1",""))
	if !ok2 {
		res.Ec = SYS_LOGIN_FAILED
		log.Debug("FG_Enter_game login failed")
		return
	}

	if isReconnect{ //断线重连
		res.Ec = SUCCESS
		res.Url = back2.Data.Game_url+"&token="+back2.Data.Token
		return
	}

	//3.存款
	orderid := GetFormatDate()+guid
	ok3,_ := fg_Post(fg_deposit_withdraw_uri+guid,fg_deposit_withdraw_p(guid, cash, orderid))
	if !ok3{
		res.Ec = SYS_DEPOSIT_FAILED
		log.Debug("FG_Enter_game deposit failed")
		return
	}
	res.Ec = SUCCESS
	res.Url = back2.Data.Game_url+"&token="+back2.Data.Token
}

func FG_Leave_game(guid string, p_b *pb.S_Ntf_UserBalance, p_r *pb.S_LeaveGame) {

	wd_money,ok := FG_withdraw(guid)
	if ok {
		p_r.Ec = SUCCESS
		p_b.Balance = wd_money
	}else{
		p_r.Ec = SYS_WITHDRAW_FAILED
	}
}

//查询玩家余额
func FG_query_banlance(guid string)(b bool, balance int64){
	ok4,back4 := fg_Post(fg_balance_uri+guid,fg_balance_p(guid))
	return ok4, back4.Data.Balance
}


func FG_withdraw(guid string) (balance int64, b bool){
	//4.查询余额
	ok4,balance_ := FG_query_banlance(guid)
	if !ok4 {
		log.Debug("FG_withdraw 查询余额 failed")
		return 0,false
	}

	if balance_ == 0 {
		log.Debug("FG_withdraw 玩家输光")
		return 0,true
	}
	//5.取款
	orderid2 := GetFormatDate()+guid
	ok5,_ := fg_Post(fg_deposit_withdraw_uri+guid,fg_deposit_withdraw_p(guid,-balance_, orderid2))
	if !ok5 {
		log.Debug("FG_Leave_game 取款 failed")
		return 0,false
	}

	return balance_,true
}

func FG_Cronjob(guid uint64, gameId int64) bool {

	guid_ := strconv.FormatUint(guid,10)
	//查询余额
	ok4,back4 := fg_Post(fg_balance_uri + guid_, fg_balance_p(guid_))
	if !ok4{
		log.Debug("FG_Cronjob query balance failed")
		return false
	}
	//5.取款
	orderid2 := GetFormatDate() + guid_
	ok5,_ := fg_Post(fg_deposit_withdraw_uri + guid_,fg_deposit_withdraw_p(guid_,-back4.Data.Balance, orderid2))
	if !ok5{
		log.Debug("FG_Cronjob withdraw failed")
		return false
	}
	balance := back4.Data.Balance
	//2.给用户加金币
	log.Debug("FG_Cronjob redis update balance", zap.Int64("back.D.Amount", balance))
	new_balance, err := mod.AddUserBalance(guid, balance)
	log.Debug("FG_Cronjob redis update balance", zap.Int64("new_balance", new_balance))
	if err != nil {
		log.Error("FG_Cronjob falild", zap.Error(err), zap.Uint64("guid", guid), zap.Int64("balance", balance))
	}

	if new_balance >= 0 {
			//3, 断开游戏连接3分钟以后就不走断线重连,下分成功直接进大厅
		if err := mod.UpdateUserAttr(guid, "regameinfo", ""); err != nil {
			log.Error("FG_Cronjob clean regameinfo err,please check", zap.Uint64("guid", guid))
		}
	}

	//5.通知后台更新玩家金币变更
	Nats_Ntf_Balance(guid, gameId, strconv.FormatInt(new_balance, 10), false)
	log.Debug("FG_Cronjob ZZYL_DeductMoney  success", zap.Uint64("guid", guid))
	return true
}


func fg_Post(url string ,dst interface{}) (ok bool , back fg_response){

	log.Debug("fg_Post 请求参数",zap.Any("dst",dst))
	formData, err := form.EncodeToString(dst)
	if err != nil {
		return
	}
	log.Debug("fg_Post 请求链接",zap.String("url", Fg_url + url))
	req, err := http.NewRequest("POST", Fg_url + url, strings.NewReader(formData))
	if err != nil{
		log.Debug("fg_Post http.NewRequest",zap.Error(err))
		return
	}

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

	client := &http.Client{Transport: tr}
	req.Header.Set("Content-Type","application/x-www-form-urlencoded")
	req.Header.Set("Accept","application/json")
	req.Header.Set("merchantname",Fg_merchantname)
	req.Header.Set("merchantcode",Fg_merchantcode)

	resp,err := client.Do(req)
	defer resp.Body.Close()

	body,err := ioutil.ReadAll(resp.Body)
	if err != nil{
		log.Debug("fg_Post ioutil.ReadAll err",zap.Error(err))
	}

	var res fg_response
	if err := json.Unmarshal(body, &res); err != nil{
		log.Debug("fg_Post Unmarshal err",zap.Error(err),zap.String("body",string(body)))
	}

	log.Debug("fg_Post 响应",zap.Any("data", res))
	if res.Code == 0 || res.Code == 105 {
		return true, res
	}else{
		return false, res
	}
}

//注册
func fg_register_p(member_code string,password string) interface{} {
	return map[string]interface{}{"member_code": member_code, "password": password}
}

//登陆
func fg_login_p(member_code string,game_id int,game_type string,language string,ip string,return_url string) interface{} {
	return map[string]interface{}{"member_code": member_code, "game_id": game_id, "game_type": game_type,
		"language": language, "ip": ip,"return_url":return_url}
}

//存取款
func fg_deposit_withdraw_p(member_code string,amount int64, externaltransactionid string) interface{} {
	return map[string]interface{}{"member_code": member_code, "amount": amount, "externaltransactionid": externaltransactionid}
}

//查询玩家余额
func fg_balance_p(member_code string) interface{} {
	return map[string]interface{}{"member_code": member_code}
}

type fg_response struct {
	Code int `json:"code"`
	Msg string `json:"msg"`
	Data fg_data `json:"data"`
}

type fg_data struct {
	Openid string `json:"openid"`
	Balance int64 `json:"balance"`
	Currency string `json:"currency"`
	Game_url string `json:"game_url"`
	Name string `json:"name"`
	Token string `json:"token"`
}