package logic

import (
	"encoding/json"
	"errors"
	"fusenapi/model/gmodel"
	"fusenapi/utils/auth"
	"fusenapi/utils/basic"
	"gorm.io/gorm"
	"strings"

	"context"

	"fusenapi/server/shopping-cart-confirmation/internal/svc"
	"fusenapi/server/shopping-cart-confirmation/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

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

func NewChangeOrderMethodLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ChangeOrderMethodLogic {
	return &ChangeOrderMethodLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ChangeOrderMethodLogic) ChangeOrderMethod(req *types.ChangeOrderMethodReq, userinfo *auth.UserInfo) (resp *basic.Response) {
	if userinfo.GetIdType() != auth.IDTYPE_User {
		return resp.SetStatusWithMessage(basic.CodeUnAuth, "please login first")
	}
	req.Sn = strings.Trim(req.Sn, " ")
	if req.Sn == "" {
		return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "param sn is required")
	}
	//查询订单信息
	orderModel := gmodel.NewFsOrderModel(l.svcCtx.MysqlConn)
	orderInfo, err := orderModel.FindOneBySn(l.ctx, userinfo.UserId, req.Sn)
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "the order is not exists")
		}
		logx.Error(err)
		return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get order info")
	}
	if *orderInfo.PayedAmount > 0 {
		return resp.SetStatusWithMessage(basic.CodeApiErr, "the order`s address cannot be changed for it is paid")
	}
	updData := &gmodel.FsOrder{Id: orderInfo.Id}
	//地址
	if req.AddressId > 0 {
		addressModel := gmodel.NewFsAddressModel(l.svcCtx.MysqlConn)
		addr, err := addressModel.GetOne(l.ctx, req.AddressId, userinfo.UserId)
		if err != nil {
			if errors.Is(err, gorm.ErrRecordNotFound) {
				return resp.SetStatusWithMessage(basic.CodeServiceErr, "address is not exists")
			}
			logx.Error(err)
			return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get address info")
		}
		infoJsonByte, _ := json.Marshal(addr)
		strInfoJson := string(infoJsonByte)
		updData.AddressInfo = &strInfoJson
	}
	updData.DeliveryMethod = &req.DeliveryMethod
	updData.AddressId = &req.AddressId
	updData.PayMethod = &req.PayMethod
	if err = orderModel.Update(l.ctx, updData); err != nil {
		logx.Error(err)
		return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to save data")
	}
	return resp.SetStatusWithMessage(basic.CodeOK, "success")
}