package orderman

import (
	"fmt"
	"strings"

	"git.rosy.net.cn/baseapi/utils"
	"git.rosy.net.cn/jx-callback/business/jxutils"
	"git.rosy.net.cn/jx-callback/business/jxutils/jxcontext"
	"git.rosy.net.cn/jx-callback/business/jxutils/netprinter"
	"git.rosy.net.cn/jx-callback/business/jxutils/weixinmsg"
	"git.rosy.net.cn/jx-callback/business/model"
	"git.rosy.net.cn/jx-callback/business/model/dao"
	"git.rosy.net.cn/jx-callback/business/partner/purchase/jd"
	"git.rosy.net.cn/jx-callback/globals"
	"git.rosy.net.cn/jx-callback/globals/api"
)

func (c *OrderManager) OnNewFakeJdOrder(vendorOrderID string) (err error) {
	utils.CallFuncAsync(func() {
		orderInfo, err := api.FakeJdAPI.FakeQuerySingleOrderRaw(vendorOrderID)
		if err == nil {
			order := jd.Map2Order(orderInfo)
			jxutils.RefreshOrderSkuRelated(order)
			err = c.notifyNewFakeJdOrder(order)
		}
		if err != nil {
			globals.SugarLogger.Warnf("OnNewFakeJdOrder failed with err:%v", err)
		}
	})
	return err
}

func (c *OrderManager) notifyNewFakeJdOrder(order *model.GoodsOrder) (err error) {
	db := dao.GetDB()
	storeDetail, err := dao.GetStoreDetailByVendorStoreID(db, order.VendorStoreID, model.VendorIDJD, "")
	if err != nil {
		return err
	}
	realStoreID := storeDetail.ID
	if storeDetail.LinkStoreID != 0 {
		realStoreID = storeDetail.LinkStoreID
	}
	notifyWxNewFakeJdOrder(order, realStoreID)
	netprinter.PrintOrderByOrder4Store(jxcontext.AdminCtx, order, realStoreID, "", nil)
	return err
}

func notifyWxNewFakeJdOrder(order *model.GoodsOrder, storeID int) (err error) {
	sb := new(strings.Builder)
	sb.WriteString("老板，你有新订单了\n")
	sb.WriteString(fmt.Sprintf("订单号:%s\n", order.VendorOrderID))
	sb.WriteString("送达时间：")
	if order.BusinessType == model.BusinessTypeDingshida {
		sb.WriteString(utils.Time2Str(order.ExpectedDeliveredTime))
	} else {
		sb.WriteString("立即达")
	}
	sb.WriteString("\n")
	sb.WriteString(fmt.Sprintf("买家:%s\n", order.ConsigneeName))
	sb.WriteString(fmt.Sprintf("电话:%s\n", order.ConsigneeMobile))
	sb.WriteString(fmt.Sprintf("收货地址:%s\n", order.ConsigneeAddress))
	sb.WriteString("商品详情:\n")
	for _, sku := range order.Skus {
		sb.WriteString(fmt.Sprintf("\t%s*%d\n", sku.SkuName, sku.Count))
	}
	title := fmt.Sprintf("你有到家菜市新订单%d", order.OrderSeq)
	content := sb.String()
	_, err = weixinmsg.SendStoreMessage(jxcontext.AdminCtx, title, content, []int{storeID}, nil, "", model.MessageTypeStore, true, true)
	return err
}
