package controllers

import (
	"bytes"
	"git.rosy.net.cn/jx-callback/business/partner/purchase/jx/localjx"
	"io/ioutil"
	"net/http"

	"git.rosy.net.cn/jx-callback/globals/api"

	"github.com/astaxie/beego/server/web"
	"github.com/astaxie/beego/server/web/context"
)

type TicTocController struct {
	web.Controller
}

type TicktockRes struct {
	ErrNo   int    `json:"err_no"`
	ErrTips string `json:"err_tips"`
}

func MsgSuccess() *TicktockRes {
	return &TicktockRes{
		ErrNo:   0,
		ErrTips: "success",
	}
}

func MsgFail() *TicktockRes {
	return &TicktockRes{
		ErrNo:   400,
		ErrTips: "business fail",
	}
}

func (c *TicTocController) TiktokMsg() {
	call, refund, payType, err := api.TiktokApi.GetCallbackMsg(getPayInfo(c.Ctx))
	if err != nil || call == nil {
		c.Data["json"] = MsgFail()
		c.ServeJSON()
		return
	}

	if err = localjx.OnTTPayCallback(call, refund, payType); err != nil {
		c.Data["json"] = MsgFail()
		c.ServeJSON()
		return
	}
	c.Data["json"] = MsgSuccess()
	c.ServeJSON()
}

func getPayInfo(ctx *context.Context) *http.Request {
	ctx.Request.Body = ioutil.NopCloser(bytes.NewReader(ctx.Input.RequestBody))
	return ctx.Request
}
