package push

import (
	"fmt"
	"strings"

	"git.rosy.net.cn/baseapi/platformapi/unipushapi"
	"git.rosy.net.cn/baseapi/utils"
	"git.rosy.net.cn/jx-callback/business/jxutils"
	"git.rosy.net.cn/jx-callback/business/model"
	"git.rosy.net.cn/jx-callback/business/model/dao"
	"git.rosy.net.cn/jx-callback/globals"
	"git.rosy.net.cn/jx-callback/globals/api"
	beego "github.com/astaxie/beego/server/web"
)

func pushToSingle(content, title string, storeID int) {
	var (
		db = dao.GetDB()
	)
	if !globals.IsProductEnv() {
		return
	}
	if storeID == 0 {
		return
	}
	storePushs, err := dao.GetStorePushClient(db, storeID, "")
	if err != nil {
		return
	}
	for _, v := range storePushs {

		status, err2 := api.PushAPI.PushToSingle(v.ClientID, false, &unipushapi.Notification{
			Title: title,
			Body:  content,
		})
		if err = err2; err != nil {
			globals.SugarLogger.Debugf("NotifyNewOrder push error: [%v]", err)
			continue
		}
		if status == unipushapi.SuccessOffLine {
			_, err = api.PushAPI.PushToSingle(v.ClientID, true, &unipushapi.Notification{
				Body: content,
			})
			if err != nil {
				globals.SugarLogger.Debugf("NotifyNewOrder push2 error: [%v]", err)
				continue
			}
		}

	}
}

func NotifyNewOrder(order *model.GoodsOrder) {
	globals.SugarLogger.Debugf("NotifyNewOrder push begin orderID :[%v]", order.VendorOrderID)
	if order == nil || len(order.Skus) == 0 {
		return
	}
	sb := new(strings.Builder)
	sb.WriteString("老板，")
	sb.WriteString(order.ConsigneeName)
	sb.WriteString("购买了商品")
	sb.WriteString(getOrderDetailBrief(order))
	pushToSingle(sb.String(), "京西菜市新订单推送", jxutils.GetSaleStoreIDFromOrder(order))
}

func getOrderDetailBrief(order *model.GoodsOrder) (brief string) {
	sb := new(strings.Builder)
	sb.WriteString(order.Skus[0].SkuName)
	sb.WriteString("等共")
	sb.WriteString(utils.Int2Str(order.Skus[0].Count))
	sb.WriteString("份（")
	sb.WriteString(jxutils.IntPrice2StandardString(order.Skus[0].SalePrice))
	sb.WriteString("元/份）等，预计收入")
	//TODO 2020-07-20 果园和菜市不同
	var price int64
	if beego.BConfig.RunMode == "jxgy" {
		price = order.EarningPrice
	} else {
		if order.EarningType == model.EarningTypePoints {
			price = order.ActualPayPrice
		} else {
			price = order.EarningPrice
		}
	}
	sb.WriteString(jxutils.IntPrice2StandardString(price))
	sb.WriteString("元")
	return sb.String()
}

func NotifyAfsOrder(afsOrder *model.AfsOrder) (err error) {
	globals.SugarLogger.Debugf("NotifyAfsOrder push begin orderID :[%v]", afsOrder.VendorOrderID)
	pushToSingle("老板，您有新的售后单，请尽快处理！", "京西菜市售后单推送", jxutils.GetSaleStoreIDFromAfsOrder(afsOrder))
	return err
}

func NotifyOrderCanceled(order *model.GoodsOrder) (err error) {
	title := fmt.Sprintf("老板，您的订单%s第%d号订单, %s被取消了！", model.VendorChineseNames[order.VendorID], order.OrderSeq, order.VendorOrderID)
	pushToSingle(title, "京西菜市取消单推送", jxutils.GetSaleStoreIDFromOrder(order))
	return err
}
