package jx

import (
	"fmt"
	"git.rosy.net.cn/jx-callback/globals"
	"strings"
	"time"

	"git.rosy.net.cn/jx-callback/business/jxutils"

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

	"git.rosy.net.cn/jx-callback/globals/api"

	"git.rosy.net.cn/jx-callback/business/partner/purchase/jx/localjx"

	"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, order *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:    order.AfsOrderID, // 是售后单ID，不是订单ID，订单ID在RefVendorOrderID中
		VendorID:         order.VendorID,
		OrderType:        model.OrderTypeAfsOrder,
		RefVendorOrderID: order.VendorOrderID,
		RefVendorID:      order.VendorID,
		VendorStatus:     utils.Int2Str(status),
		Status:           status,
		StatusTime:       time.Now(),
		Remark:           reason,
	}
	if status == model.AfsOrderStatusFinished {
		orderPays, err := dao.GetOrderPayList(dao.GetDB(), order.VendorOrderID, order.VendorID)
		if err == nil {
			if orderPays[0].PayType == model.PayTypeTL {
				_, err = localjx.RefundOrderByTL(ctx, orderPays[0], order.VendorOrderID, int(order.SkuUserMoney), reason)
			}
			if orderPays[0].PayType == model.PayTypeTicTok {
				_, err = localjx.RefundOrderByTT(ctx, orderPays[0], order.VendorOrderID, int(order.SkuUserMoney), reason)
			}
			if orderPays[0].PayType == model.PayTypeKuaiShou {
				_, err = localjx.RefundOrderByKS(ctx, orderPays[0], order.VendorOrderID, int(order.SkuUserMoney), reason)
			}
			if orderPays[0].PayType == model.PayTypeLaKaLa {
				globals.SugarLogger.Debugf("-----order- := %s", utils.Format4Output(order, false))
				_, err = localjx.RefundOrderByLaKaLa(ctx, orderPays[0], order, order.VendorOrderID, int(order.SkuUserMoney), reason)
			}
			if err != nil {
				return err
			} else {
				partner.CurOrderManager.OnAfsOrderStatusChanged(orderStatus)
			}
		}
	} else {
		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)
		appID     = ""
		salePrice int64
		db        = dao.GetDB()
	)
	if time.Now().Sub(order.OrderCreatedAt) > 24*time.Hour {
		return fmt.Errorf("已超过售后申请时间，如有疑问请联系门店！")
	}
	referer := ctx.GetRequest().Referer()
	index := strings.Index(referer, "//")
	if index > 0 {
		list := strings.Split(referer[index+2:], "/")
		if len(list) >= 2 {
			appID = list[1]
		}
	}
	for _, sku := range order.Skus {
		skuMap[sku.SkuID] = sku
	}
	orderStatus := buildOrderStatus(ctx, order, reason, isJxShop(appID))
	afsOrder := &model.AfsOrder{
		VendorID:         order.VendorID,
		AfsOrderID:       orderStatus.VendorOrderID,
		VendorOrderID:    orderStatus.RefVendorOrderID,
		VendorStoreID:    order.VendorStoreID,
		StoreID:          order.StoreID,
		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,
		}
		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)
	}

	if !isJxShop(appID) {
		orderPays, err := dao.GetOrderPayList(db, order.VendorOrderID, order.VendorID)
		if err == nil {
			if orderPays[0].PayType == model.PayTypeTL {
				_, err = localjx.RefundOrderByTL(ctx, orderPays[0], order.VendorOrderID, int(salePrice), reason)
			}
			if orderPays[0].PayType == model.PayTypeTicTok {
				_, err = localjx.RefundOrderByTT(ctx, orderPays[0], order.VendorOrderID, int(salePrice), reason)
			}
			if err != nil {
				return err
			} else {
				if afsOrder != nil {
					err = partner.CurOrderManager.OnAfsOrderNew(afsOrder, orderStatus)
				}
			}
		}
	} else {
		err = partner.CurOrderManager.OnAfsOrderNew(afsOrder, orderStatus)
	}
	return err
}

func buildOrderStatus(ctx *jxcontext.Context, order *model.GoodsOrder, reason string, isJxShop bool) (orderStatus *model.OrderStatus) {
	orderStatus = &model.OrderStatus{
		VendorOrderID:    utils.Int64ToStr(jxutils.GenAfsOrderNo()), // 是售后单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,
	}
	if isJxShop {
		orderStatus.Status = model.AfsOrderStatusWait4Approve
	} else {
		orderStatus.Status = model.AfsOrderStatusFinished
	}
	return orderStatus
}

func isJxShop(appID string) bool {
	if appID == api.WeixinMiniAppID2 {
		return true
	}
	return false
}

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

	if order, err := partner.CurOrderManager.LoadOrder(vendorOrderID, model.VendorIDJX); err == nil {
		orderAfsInfo.AfsTotalShopMoney = order.TotalShopMoney
	}
	orderAfsInfo.VendorOrderID = vendorOrderID
	return orderAfsInfo, err
}
