package mgt

import (
	"context"
	"errors"
	"time"

	"bsm/full/module/ec/order/internal/models"
	pb "bsm/full/module/ec/order/pb"
	"git.apinb.com/bsm-sdk/core/errcode"
	"git.apinb.com/bsm-sdk/core/printer"
	"git.apinb.com/bsm-sdk/core/service"
)

// OrderReturnable 订单申请售后
func OrderReturnable(ctx context.Context, in *pb.IdentRequest) (reply *pb.StatusReply, err error) {
	_, err = service.ParseMetaCtx(ctx, &service.ParseOptions{RoleValue: "Mall_Admin"})
	if err != nil {
		return nil, err
	}
	// 验证订单的approve审核状态：状态：-2：未通过，0：默认 1:申请退款 2:申请退货 3：申请退款退货 4：申请通过
	if in.GetApprove() != 1 && in.GetApprove() != 2 && in.GetApprove() != 3 {
		return nil, errcode.ErrInvalidArgument
	}
	// 验证输入参数是否有效。
	if in.GetIdentity() == "" {
		return nil, errcode.ErrInvalidArgument
	}

	// 获取当前订单信息
	order := models.OrderSummary{}
	if err := models.DBService.Preload("OrderDetails").Where("identity=?", in.Identity).First(&order).Error; err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}

	// 订单状态判断是否允许申请退款退货
	if order.Status == -1 || order.Status == 6 || order.Status == 7 || order.Status == 8 || order.Approve != 0 {
		return nil, errors.New("订单状态异常")
	}

	// 订单状态更新
	summaryModel := models.OrderSummary{
		Approve: int8(in.GetApprove()),
		Reason:  in.GetReason(),
	}
	err = models.DBService.Model(&models.OrderSummary{}).Where("identity = ?", in.Identity).Updates(&summaryModel).Error
	if err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}

	return &pb.StatusReply{
		Code:     0,
		Message:  "OK",
		Identity: in.GetIdentity(),
		Reason:   in.GetReason(),
		Timeseq:  time.Now().UnixNano(),
	}, nil

}
