package summary

import (
	"context"
	"errors"
	"strings"
	"time"

	"bsm/full/module/ec/order/internal/logic/common"
	"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"
	"git.apinb.com/bsm-sdk/core/utils"
)

// 快速创建一个店铺订单
func QuickCreateByProduct(ctx context.Context, in *pb.QuickCreateByProductRequest) (reply *pb.StatusReply, err error) {
	// parse authorization meta.
	auth, err := service.ParseMetaCtx(ctx, &service.ParseOptions{RoleValue: "Mall_Admin"})
	if err != nil {
		return nil, err
	}

	// 验证输入参数是否有效。
	if in.GetProductIdentity() == "" || in.GetNumber() == 0 || in.GetStoreIdentity() == "" || in.GetAddressIdentity() == "" {
		return nil, errcode.ErrInvalidArgument
	}

	// 查询商店信息以确保其存在且状态为启用。
	store := map[string]any{}
	err = models.DBService.Table("mall_store").Take(&store, "identity=?", in.StoreIdentity).Error
	if err != nil {
		printer.Error(err.Error())
		if errors.Is(err, models.ErrNotFound) {
			return nil, errcode.ErrRecordNotFound
		}
		return nil, errcode.ErrDB
	}
	if store["status"].(int16) != 1 {
		return nil, errcode.ErrUnknown
	}

	// 查询产品信息以确保其存在且状态为启用。
	product := map[string]any{}
	var pi string = strings.ToLower(in.ProductIdentity)
	if pi == "gas_by_kg" || pi == "gas_by_bottle" {
		err = models.DBService.Table("mall_product").Take(&product, "store_identity=? and serial_id=?", in.StoreIdentity, pi).Error
	} else {
		err = models.DBService.Table("mall_product").Take(&product, "identity=?", in.ProductIdentity).Error
	}
	if err != nil {
		printer.Error(err.Error())
		if errors.Is(err, models.ErrNotFound) {
			return nil, errcode.ErrRecordNotFound
		}
		return nil, errcode.ErrDB
	}
	if product["status"].(int32) != 1 {
		return nil, errcode.ErrUnknown
	}

	// 查询产品规格信息
	spec := map[string]any{}
	err = models.DBService.Table("mall_product_spec").Take(&spec, "product_identity=?", in.ProductIdentity).Error
	if err != nil {
		printer.Error(err.Error())
		if errors.Is(err, models.ErrNotFound) {
			return nil, errcode.ErrRecordNotFound
		}
		return nil, errcode.ErrDB
	}

	// 查询地址信息以确保其存在。
	address := map[string]any{}
	err = models.DBService.Table("address_library").Take(&address, "identity=?", in.AddressIdentity).Error
	if err != nil {
		printer.Error(err.Error())
		if errors.Is(err, models.ErrNotFound) {
			return nil, errcode.ErrRecordNotFound
		}
		return nil, errcode.ErrDB
	}

	// // 查询配送员信息
	// member := map[string]any{}
	// err = models.DBService.Table("delivery_member").Take(&member, "identity=?", in.MemberIdentity).Error
	// if err != nil {
	// 	printer.Error(err.Error())
	// 	if errors.Is(err, models.ErrNotFound) {
	// 		return nil, errcode.ErrRecordNotFound
	// 	}
	// 	return nil, errcode.ErrDB
	// }

	// 生成订单号。
	orderNo := common.CreateOrderNo()
	// 计算交易价格并构建订单摘要对象。
	TransPrice := (int64(in.Number) * spec["price"].(int64))
	summary := &models.OrderSummary{
		StoreID:         uint(store["id"].(int64)),
		StoreIdentity:   in.StoreIdentity,
		OrderNo:         orderNo,
		PartnerID:       in.PartnerId,
		TransPrice:      TransPrice,
		TotalPrice:      TransPrice,
		Args:            in.Args,
		AddressIdentity: in.AddressIdentity,
		Province:        address["province"].(string),
		City:            address["city"].(string),
		Area:            address["area"].(string),
		Address:         address["detail"].(string),
		Contact:         address["contact"].(string),
		Phone:           address["phone"].(string),
		DeliveryTime:    in.GetDeliveryTime(),
		// DeliveryIdentity: member["identity"].(string),
		DeliveryAddress: in.DeliveryAddress,
	}
	summary.Identity = utils.UUID()
	summary.PassportID = auth.ID
	summary.PassportIdentity = auth.Identity
	summary.Status = 1

	// 从产品信息中提取单价、ID等详情，并构建订单详情对象。
	unit_price := product["sales_price"].(int64)
	productID := product["id"].(int64)
	details := &models.OrderDetails{
		Type:            1,
		ProductID:       productID,
		ProductIdentity: product["identity"].(string),
		SpecID:          spec["id"].(int64),
		OrderNo:         orderNo,
		Title:           product["title"].(string),
		CoverImage:      product["cover_image"].(string),
		UnitPrice:       unit_price,
		Number:          in.Number,
		ProductArgs:     product["args"].(string),
		SummaryIdentity: summary.Identity,
		SpecTitle:       spec["title"].(string),
		SpecNo:          spec["serial_number"].(string),
		GasType:         product["gas_types"].(int32),
		SupplyId:        product["supply_id"].(int64),
	}

	// 将订单摘要和订单详情记录到数据库。
	err = models.DBService.Create(summary).Error
	if err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}

	err = models.DBService.Create(details).Error
	if err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}

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

}
