package jdshop

import (
	"crypto/md5"
	"fmt"
	"math"
	"time"

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

	"git.rosy.net.cn/baseapi/utils"
	"git.rosy.net.cn/jx-callback/business/jxutils/jxcontext"
	"git.rosy.net.cn/jx-callback/business/model"
	"git.rosy.net.cn/jx-callback/business/partner"
)

func (c *PurchaseHandler) AgreeOrRefuseRefund(ctx *jxcontext.Context, afsOrder *model.AfsOrder, approveType int, reason string, review map[string]interface{}) (err error) {
	var status int
	if approveType == partner.AfsApproveTypeRefused {
		status = model.AfsOrderStatusFailed
	} else {
		status = model.AfsOrderStatusFinished

	}
	orderStatus := &model.OrderStatus{
		VendorOrderID:    afsOrder.AfsOrderID, // 是售后单ID，不是订单ID，订单ID在RefVendorOrderID中
		VendorID:         afsOrder.VendorID,
		OrderType:        model.OrderTypeAfsOrder,
		RefVendorOrderID: afsOrder.VendorOrderID,
		RefVendorID:      afsOrder.VendorID,
		VendorStatus:     utils.Int2Str(status),
		Status:           status,
		StatusTime:       time.Now(),
		Remark:           reason,
	}
	partner.CurOrderManager.OnAfsOrderStatusChanged(orderStatus)
	return err
}

// 确认收到退货
func (c *PurchaseHandler) ConfirmReceivedReturnGoods(ctx *jxcontext.Context, order *model.AfsOrder) (err error) {
	err = fmt.Errorf("京东商城当前不支持ConfirmReceivedReturnGoods")
	return err
}

// 发起全款退款
func (c *PurchaseHandler) RefundOrder(ctx *jxcontext.Context, order *model.GoodsOrder, reason string) (err error) {
	err = c.PartRefundOrder(ctx, order, order.Skus, reason)
	return err
}

// 发起部分退款
func (c *PurchaseHandler) PartRefundOrder(ctx *jxcontext.Context, order *model.GoodsOrder, refundSkuList []*model.OrderSku, reason string) (err error) {
	var (
		skuMap    = make(map[int]*model.OrderSku)
		salePrice int64
		db        = dao.GetDB()
	)
	for _, sku := range order.Skus {
		skuMap[sku.SkuID] = sku
	}
	orderStatus := buildOrderStatus(ctx, order, reason)
	afsOrder := &model.AfsOrder{
		VendorID:      order.VendorID,
		AfsOrderID:    orderStatus.VendorOrderID,
		VendorOrderID: orderStatus.RefVendorOrderID,
		// VendorStoreID:    order.VendorStoreID,
		// StoreID:          jxutils.GetSaleStoreIDFromOrder(order),
		AfsCreatedAt:     time.Now(),
		VendorAppealType: "",
		AppealType:       model.AfsAppealTypeRefund,
		VendorReasonType: utils.Int2Str(model.AfsReasonNotOthers),
		ReasonType:       model.AfsReasonNotOthers,
		ReasonDesc:       utils.LimitUTF8StringLen(reason, 1024),
		ReasonImgList:    "",
		RefundType:       model.AfsTypePartRefund,

		VendorOrgCode: "",
	}
	for _, sku := range refundSkuList {
		orderSku := &model.OrderSkuFinancial{
			Count:       sku.Count,
			VendorSkuID: utils.Int2Str(sku.SkuID),
			SkuID:       sku.SkuID,
		}
		storeSkus, _ := dao.GetStoresSkusInfo(db, []int{model.JdShopMainStoreID}, []int{sku.SkuID})
		if len(storeSkus) > 0 {
			orderSku.VendorSkuID = utils.Int64ToStr(storeSkus[0].JdsID)
		}
		if skuMap[sku.SkuID] != nil {
			orderSku.Name = skuMap[sku.SkuID].SkuName
			orderSku.UserMoney = skuMap[sku.SkuID].SalePrice * int64(sku.Count)
			salePrice += skuMap[sku.SkuID].SalePrice * int64(sku.Count)
		}
		afsOrder.SkuUserMoney += orderSku.UserMoney
		afsOrder.Skus = append(afsOrder.Skus, orderSku)
	}
	err = partner.CurOrderManager.OnAfsOrderNew(afsOrder, orderStatus)
	return err
}

func buildOrderStatus(ctx *jxcontext.Context, order *model.GoodsOrder, reason string) (orderStatus *model.OrderStatus) {
	orderStatus = &model.OrderStatus{
		VendorOrderID:    utils.Int64ToStr(GenAfsOrderNo(ctx)), // 是售后单ID，不是订单ID，订单ID在RefVendorOrderID中
		VendorID:         order.VendorID,
		OrderType:        model.OrderTypeAfsOrder,
		RefVendorOrderID: order.VendorOrderID,
		RefVendorID:      order.VendorID,
		VendorStatus:     utils.Int2Str(model.AfsOrderStatusWait4Approve),
		Status:           model.AfsOrderStatusWait4Approve,
		StatusTime:       time.Now(),
		Remark:           reason,
	}
	orderStatus.Status = model.AfsOrderStatusWait4Approve
	return orderStatus
}

func GenAfsOrderNo(ctx *jxcontext.Context) (orderNo int64) {
	const prefix = 70
	const randPartNum = 100
	orderNoBeginTimestamp := utils.Str2Time("2010-01-01 00:00:00").Unix()
	orderNo = time.Now().Unix() - orderNoBeginTimestamp
	orderNo = orderNo * randPartNum
	md5Bytes := md5.Sum([]byte(utils.GetUUID()))
	randPart := 0
	for k, v := range md5Bytes {
		randPart += int(v) << ((k % 3) * 8)
	}
	orderNo += int64(randPart % randPartNum)
	orderNo += int64(math.Pow10(int(math.Log10(float64(orderNo)))+1)) * prefix
	return orderNo
}

func (c *PurchaseHandler) GetOrderAfsInfo(ctx *jxcontext.Context, vendorOrderID, afsOrderID string) (orderAfsInfo *partner.OrderAfsInfo, err error) {
	return &partner.OrderAfsInfo{}, err
}
