package acquirer_mkt_qr

import (
	"context"
	"encoding/json"
	"git.i2edu.net/i2/i2-bill-api/internal/utils"
	"git.i2edu.net/i2/i2-bill-api/model"
	"net/http"
	"strings"

	"git.i2edu.net/i2/i2-bill-api/internal/svc"
	"git.i2edu.net/i2/i2-bill-api/internal/types"

	"git.i2edu.net/i2/go-zero/core/logx"
)

type AcquirerMktQrGetLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAcquirerMktQrGetLogic(ctx context.Context, svcCtx *svc.ServiceContext) AcquirerMktQrGetLogic {
	return AcquirerMktQrGetLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AcquirerMktQrGetLogic) AcquirerMktQrGet(r *http.Request) (*types.Response, error) {
	// todo: add your logic here and delete this line
	userId := l.svcCtx.GetUserIdByJwt(l.ctx)
	erpUser, err := model.GetAcquirePermInfo(userId, l.svcCtx.Transformer, l.svcCtx.DB, l.ctx)
	if err != nil {
		logx.Error(err.Error())
		return &types.Response{500, err.Error(), nil}, nil
	}
	if erpUser == nil || erpUser.UserId == "" {
		return &types.Response{500, "请先申请成为兼职", nil}, nil
	}
	qr, err := model.GetAcquirerMktQr(userId, l.svcCtx.DB)
	if err != nil {
		logx.Error(err.Error())
		return &types.Response{500, err.Error(), nil}, nil
	}
	if qr.Id == 0 {
		return &types.Response{200, "请先编辑收单二维码信息", nil}, nil
	}

	if erpUser.Role != qr.Role {
		return &types.Response{200, "请先重新编辑收单二维码信息", nil}, nil
	}

	qr.Qr = strings.TrimLeft(qr.Qr, "/")
	domain := strings.TrimRight(l.svcCtx.Config.AliYunOss.FileUrl, "/")
	qr.Qr = domain + "/" + qr.Qr
	//渠道
	networkNodes, err := l.svcCtx.GetErpNetworkDetailTree(l.ctx)
	if err != nil {
		logx.Error(err.Error())
		return &types.Response{500, err.Error(), nil}, nil
	}
	var networkId, networkName string
	utils.TreePath(networkNodes, qr.NetworkDetailId, &networkId, &networkName)
	qrByte, _ := json.Marshal(qr)
	var qrMap = make(map[string]interface{})
	json.Unmarshal(qrByte, &qrMap)
	qrMap["qudao_name"] = networkName
	qrMap["qudao_path"] = networkId
	//活动
	active, err := l.svcCtx.GetErpActivity(l.ctx)
	if err != nil {
		logx.Error(err.Error())
		return &types.Response{500, err.Error(), nil}, nil
	}
	qrMap["activity_name"] = utils.GetErpActiveName(qr.ActivityId, active)
	//校区
	schools, err := l.svcCtx.GetErpOrganSchool(l.ctx)
	if err != nil {
		logx.Error(err.Error())
		return &types.Response{500, err.Error(), nil}, nil
	}

	qrMap["school_name"] = utils.GetErpSchoolName(qr.SchoolId, schools)

	return &types.Response{200, "", qrMap}, nil
}
