package repoimpl

import (
	"context"
	"errors"
	"gorm.io/gorm"
	"time"
	"unicode/utf8"
	err2 "voucher/api/err"
	"voucher/internal/biz/bo"
	"voucher/internal/biz/repo"
	"voucher/internal/biz/vo"
	"voucher/internal/data"
	"voucher/internal/data/model"
)

// WechatNotifyRegisterTagRepoImpl .
type WechatNotifyRegisterTagRepoImpl struct {
	Base[model.WechatNotifyRegisterTag, bo.WechatNotifyRegisterTagBo]
	db *data.Db
}

// NewWechatNotifyRegisterTagRepoImpl .
func NewWechatNotifyRegisterTagRepoImpl(db *data.Db) repo.WechatNotifyRegisterTagRepo {
	return &WechatNotifyRegisterTagRepoImpl{db: db}
}

func (p *WechatNotifyRegisterTagRepoImpl) DB(ctx context.Context) *gorm.DB {
	return p.db.DB(ctx).Model(model.WechatNotifyRegisterTag{})
}

func (p *WechatNotifyRegisterTagRepoImpl) GetByStockIdAndMchId(ctx context.Context, stockCreatorMchID, stockId string) (*bo.WechatNotifyRegisterTagBo, error) {
	info := &model.WechatNotifyRegisterTag{}

	tx := p.DB(ctx).Where(model.WechatNotifyRegisterTag{StockCreatorMchID: stockCreatorMchID, StockID: stockId}).First(&info)

	if tx.Error != nil {
		if errors.Is(tx.Error, gorm.ErrRecordNotFound) {
			return nil, err2.ErrorDbNotFound("notifyTag数据不存在")
		}
		return nil, tx.Error
	}

	if tx.RowsAffected == 0 {
		return nil, err2.ErrorDbNotFound("微信回调注册tag数据不存在")
	}

	return p.ToBo(info), nil
}

func (p *WechatNotifyRegisterTagRepoImpl) Create(ctx context.Context, req *bo.WechatNotifyRegisterTagBo) (*bo.WechatNotifyRegisterTagBo, error) {
	now := time.Now()

	info := &model.WechatNotifyRegisterTag{
		StockID:           req.StockID,
		StockCreatorMchID: req.StockCreatorMchID,
		Tag:               req.Tag,
		Status:            vo.WechatNotifyRegisterTagStatusWait.GetValue(),
		CreateTime:        &now,
	}

	if err := p.DB(ctx).Create(info).Error; err != nil {
		return nil, err
	}

	return p.ToBo(info), nil
}

func (p *WechatNotifyRegisterTagRepoImpl) Success(ctx context.Context, id int32) error {
	now := time.Now()

	res := p.DB(ctx).
		Where(model.WechatNotifyRegisterTag{
			ID: id,
		}).
		Updates(model.WechatNotifyRegisterTag{
			Status:     vo.WechatNotifyRegisterTagStatusSuccess.GetValue(),
			UpdateTime: &now,
		})

	if res.Error != nil {
		return res.Error
	}

	return nil
}

func (p *WechatNotifyRegisterTagRepoImpl) Fail(ctx context.Context, id int32, remark string) error {

	if utf8.RuneCountInString(remark) > 100 {
		runes := []rune(remark)
		if len(runes) > 100 {
			remark = string(runes[:100])
		}
	}

	now := time.Now()

	res := p.DB(ctx).
		Where(model.WechatNotifyRegisterTag{
			ID: id,
		}).
		Updates(model.WechatNotifyRegisterTag{
			Status:     vo.WechatNotifyRegisterTagStatusFail.GetValue(),
			Remark:     remark,
			UpdateTime: &now,
		})

	if res.Error != nil {
		return res.Error
	}

	return nil
}
