package controller

import (
	"enterprise/common/config"
	"enterprise/common/dao"
	"enterprise/common/global"
	"enterprise/common/model"
	"enterprise/server/service"
	"enterprise/server/session"
	"fmt"
	"git.u8t.cn/open/gosdk/qyweixin"
	"github.com/gin-gonic/gin"
	log "github.com/sirupsen/logrus"
	"github.com/smbrave/goutil"
	"github.com/spf13/cast"
	"net/http"
	"strings"
	"time"
)

type QyWeixin struct {
}

func (q *QyWeixin) Approve(ctx *gin.Context) {
	cid := cast.ToInt64(ctx.Param("cid"))
	corp, err := dao.NewCorpDao().Get(cid)
	if err != nil || corp == nil {
		panic(config.ErrParam.New().Append(err))
	}

	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())
}

func (q *QyWeixin) Pay(ctx *gin.Context) {
	cid := cast.ToInt64(ctx.Param("cid"))
	userid := ctx.Query("userid")
	amount := cast.ToInt64(ctx.Query("amount"))
	title := ctx.Query("title")
	pass := ctx.Query("pass")
	if pass != "1c9dea1fb85cf06ab0b4d946d49aa92f" {
		panic("password error")
	}

	corp, err := dao.NewCorpDao().Get(cid)
	if err != nil {
		panic(config.ErrDb.New().Append(err))
	}
	if corp == nil {
		panic(config.ErrInternal.New())
	}
	cfg := corp.GetConfig()

	// 获取openid
	approve := qyweixin.NewAppApprove(&qyweixin.AppConfig{
		Corpid: cfg.CorpId,
		Secret: cfg.EnterpriseSecret,
		Agent:  cfg.EnterpriseAgent,
	})
	openid, err := approve.GetOpenid(userid)
	if err != nil {
		panic(err)
	}

	// 支付费用
	var req qyweixin.PayReq
	req.BillNo = fmt.Sprintf("API%s%s", time.Now().Format("20060102150405"), userid)
	req.Title = title
	req.Openid = openid
	req.TotalAmount = amount
	qyPay := qyweixin.NewAppPay(&qyweixin.PayConfig{
		Corpid:       cfg.CorpId,
		Secret:       cfg.PaySecret,
		Agent:        cfg.PayAgent,
		SerialNumber: config.GetConfig().WxPay.PaySerialNumber,
		ApiKey:       config.GetConfig().WxPay.PayApiKeyV2,
		MchId:        config.GetConfig().WxPay.PayMchId,
		CertPem:      config.GetConfig().WxPay.PayCertPem,
		KeyPem:       config.GetConfig().WxPay.PayKeyPem,
	})

	if err = qyPay.PayMoney(&req); err != nil {
		log.Errorf("pay req[%s] error :%s", goutil.EncodeJSON(req), err.Error())
		panic(err)
	}

	message := make([]string, 0)

	message = append(message, fmt.Sprintf("【红包发放】[%s]", userid))
	message = append(message, fmt.Sprintf("发放金额:%s", goutil.FormatMoney(amount)))
	message = append(message, fmt.Sprintf("员工名称:%s", userid))
	message = append(message, fmt.Sprintf("费用说明:%s", title))

	if err := global.SendMessage([]string{"jiangyong"}, strings.Join(message, "\n")); err != nil {
		log.Errorf("send message error :%s", err.Error())
	}
	ctx.JSON(http.StatusOK, session.NewRspOk())
}