package mk_qr

import (
	"context"
	"encoding/json"
	"fmt"
	"git.i2edu.net/i2/i2-bill-api/model"
	"io/ioutil"
	"net/http"
	"strings"
	"time"

	"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 MktQrAddLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *MktQrAddLogic) MktQrAdd(r *http.Request) (*types.Response, error) {
	// todo: add your logic here and delete this line
	type Mk struct {
		MkId string `json:"mk_id"`
	}
	body, err := ioutil.ReadAll(r.Body)
	defer r.Body.Close()
	if err != nil {
		return &types.Response{500, err.Error(), nil}, nil
	}
	var mk = new(Mk)
	err = json.Unmarshal(body, mk)
	if err != nil {
		return &types.Response{500, err.Error(), nil}, nil
	}
	mk_id := mk.MkId
	if mk_id == "" {
		return &types.Response{500, "mk_id 不能为空", nil}, nil
	}
	erpRes, err := model.GetErpUser("", mk_id, l.svcCtx.Transformer, l.ctx)
	if err != nil {
		logx.Error(err.Error())
		return &types.Response{Code: 500, Msg: err.Error(), Data: nil}, nil
	}
	if erpRes == nil {
		return &types.Response{500, "权限不足", nil}, nil
	}
	bean := new(model.I2billMktQr)
	_, err = l.svcCtx.DB.Where("mk_id = ? and del_flag = 0", mk_id).Get(bean)
	if err != nil {
		return &types.Response{500, err.Error(), nil}, nil
	}
	bean.MkId = mk_id
	mk_id = strings.ReplaceAll(mk_id, "-", "")
	if len(mk_id) > 32 {
		return &types.Response{500, "mk_id 格式错误", nil}, nil
	}
	sceneStr := fmt.Sprintf("%s", mk_id)
	atr, err := l.svcCtx.Wechat.GenQrCode(sceneStr, l.svcCtx.Config.Weixin.SharePtPage)
	if err != nil {
		logx.Error(err.Error())
		return &types.Response{500, err.Error(), nil}, nil
	}
	if atr == nil || atr.Url == "" {
		return &types.Response{500, "二维码生成失败", nil}, nil
	}
	_, err = l.svcCtx.DB.Insert(atr)
	if err != nil {
		logx.Error(err.Error())
		return &types.Response{500, err.Error(), nil}, nil
	}
	if bean.Id != 0 {
		bean.Qr = atr.Url
		_, err = l.svcCtx.DB.ID(bean.Id).Cols("qr").Update(bean)
		if err != nil {
			logx.Error(err.Error())
			return &types.Response{500, err.Error(), nil}, nil
		}
	} else {
		bean.Qr = atr.Url
		bean.CreateTime = time.Now()
		bean.DelFlag = 0
		_, err = l.svcCtx.DB.Insert(bean)
		if err != nil {
			logx.Error(err.Error())
			return &types.Response{500, err.Error(), nil}, nil
		}
	}
	bean.Qr = strings.TrimLeft(bean.Qr, "/")
	domain := strings.TrimRight(l.svcCtx.Config.AliYunOss.FileUrl, "/")
	bean.Qr = domain + "/" + bean.Qr
	return &types.Response{200, "", bean}, nil
}
