package controller

import (
	"enterprise/common/config"
	"enterprise/common/dao"
	"enterprise/common/model"
	"enterprise/server/service"
	"enterprise/server/session"
	"git.u8t.cn/open/gosdk/qyweixin"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
	"net/http"
)

type QyWeixin struct {
}

func NewQyWeixin() *QyWeixin {
	return &QyWeixin{}
}

func (q *QyWeixin) Approve(ctx *gin.Context) {

	sess := ctx.Keys[session.ContextSession].(*session.AdminSession)

	cid := cast.ToInt64(ctx.Param("cid"))
	corp, err := dao.NewCorpDao().Get(cid)
	session.CheckDBError(err)
	if corp == nil {
		corp, err = dao.NewCorpDao().GetByHost(sess.GetHeader().Host)
		session.CheckDBError(err)
		session.CheckNilError(corp, "企业不存在")
	}

	corpConfig := corp.GetConfig()
	approve := service.NewApprove(corp)
	reply := approve.Reply
	qyApp := qyweixin.NewApp(&qyweixin.AppConfig{
		Corpid: corpConfig.CorpId,
		Secret: corpConfig.ApproveSecret,
		Agent:  corpConfig.ApproveAgent,
		Token:  config.QyWeixinAgentToken,
		AesKey: config.QyWeixinAgentAesKey,
		Replay: reply,
	})

	qyApp.Callback(ctx)
}

func (q *QyWeixin) HandleRefund(ctx *gin.Context) {
	id := cast.ToInt64(ctx.Query("id"))
	approve, err := dao.NewApprovalRefundDao().Get(id)
	if err != nil {
		panic(config.ErrDb.New().Append(err))
	}
	if approve == nil {
		panic("没有数据")
	}
	if approve.Status == model.ApprovalRefundStatusPayed {
		panic("已支付")
	}
	corp, err := dao.NewCorpDao().Get(approve.CorpId)
	if err != nil {
		panic(config.ErrDb.New().Append(err))
	}
	if corp == nil {
		panic("没有数据")
	}
	serv := service.NewApprove(corp)
	err = serv.HandleRefundApprove(approve)
	if err != nil {
		panic(config.ErrDb.New().Append(err))
	}
	ctx.JSON(http.StatusOK, session.NewRspOk())
}