package partner

import (
	"fmt"

	"git.rosy.net.cn/jx-callback/business/model"
)

const (
	ErrCodeUnknown           = 1
	ErrCodeChangePriceFailed = 100
)

type ErrorWithCode struct {
	errMsg   string
	intCode  int
	vendorID int
	storeID  int
	skuID    int
}

func NewErrorCode(errMsg string, code, vendorID int) *ErrorWithCode {
	retVal := &ErrorWithCode{
		errMsg:   errMsg,
		intCode:  code,
		vendorID: vendorID,
	}
	return retVal
}

func (e *ErrorWithCode) SetStoreID(storeID int) {
	e.storeID = storeID
}

func (e *ErrorWithCode) SetSkuID(skuID int) {
	e.skuID = skuID
}

func (e *ErrorWithCode) Error() string {
	return fmt.Sprintf("平台:%s, code:%d, %s", model.VendorChineseNames[e.VendorID()], e.intCode, e.errMsg)
}

func (e *ErrorWithCode) String() string {
	return e.Error()
}

func (e *ErrorWithCode) Code() int {
	return e.intCode
}

func (e *ErrorWithCode) ErrMsg() string {
	return e.errMsg
}

func (e *ErrorWithCode) VendorID() int {
	return e.vendorID
}

func (e *ErrorWithCode) StoreID() int {
	return e.storeID
}

func (e *ErrorWithCode) SkuID() int {
	return e.skuID
}

func IsErrChangePriceFailed(err error) *ErrorWithCode {
	if vendorErr, ok := err.(*ErrorWithCode); ok && vendorErr.Code() == ErrCodeChangePriceFailed {
		return vendorErr
	}
	return nil
}

func IsErrVendorError(err error) *ErrorWithCode {
	if vendorErr, ok := err.(*ErrorWithCode); ok {
		return vendorErr
	}
	return nil
}

func AddVendorInfo2Err(inErr error, vendorID int) (outErr error) {
	outErr = inErr
	if inErr != nil {
		if IsErrVendorError(inErr) == nil {
			outErr = NewErrorCode(inErr.Error(), ErrCodeUnknown, vendorID)
		}
	}
	return outErr
}
