package jd

import (
	"git.rosy.net.cn/baseapi/platformapi/jdapi"
	"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/model"
	"git.rosy.net.cn/jx-callback/business/partner"
	"git.rosy.net.cn/jx-callback/globals"
)

const (
	JDDJ_BAD_COMMENTS_MAX_MODIFY_TIME = 72 // 小时
)

func (c *PurchaseHandler) onOrderComment2(a *jdapi.API, msg *jdapi.CallbackOrderMsg) (err error) {
	intOrderID := utils.Str2Int64(msg.BillID)
	result, err := a.GetCommentByOrderId2(intOrderID)
	if err == nil {
		orderCommend := &model.OrderComment{
			VendorOrderID:  utils.Int64ToStr(result.OrderID),
			VendorID:       model.VendorIDJD,
			UserCommentID:  "",
			VendorStoreID:  utils.Int64ToStr(result.StoreID),
			TagList:        string(utils.MustMarshal(result.VenderTags)),
			Score:          int8(result.Score4),
			Content:        result.Score4Content,
			ModifyDuration: JDDJ_BAD_COMMENTS_MAX_MODIFY_TIME,
			OriginalMsg:    string(utils.MustMarshal(result)),
		}
		if orderCommend.Score == 0 {
			orderCommend.Score = 1
		}
		if orderCommend.TagList == "null" {
			orderCommend.TagList = ""
		}
		if result.CreateTime != nil {
			orderCommend.CommentCreatedAt = result.CreateTime.GoTime()
		}
		if result.OrgCommentContent != "" {
			orderCommend.IsReplied = 1
		}
		if order, _ := partner.CurOrderManager.LoadOrder(orderCommend.VendorOrderID, model.VendorIDJD); order != nil {
			orderCommend.StoreID = jxutils.GetSaleStoreIDFromOrder(order)
		}
		err = partner.CurOrderManager.OnOrderComments([]*model.OrderComment{orderCommend})
	}
	if err != nil {
		globals.SugarLogger.Warnf("onOrderComment orderID:%s failed with error:%v", msg.BillID, err)
	}
	return err
}

func (c *PurchaseHandler) ReplyOrderComment(ctx *jxcontext.Context, vendorOrgCode string, orderComment *model.OrderComment, replyComment string) (err error) {
	if globals.EnableJdStoreWrite {
		err = getAPI(vendorOrgCode).OrgReplyComment(utils.Str2Int64(orderComment.VendorOrderID), orderComment.VendorStoreID, replyComment, ctx.GetUserName())
	}
	return err
}
