package cs

import (
	"git.rosy.net.cn/baseapi/platformapi/weimobapi"
	"git.rosy.net.cn/baseapi/utils"
	"git.rosy.net.cn/jx-callback/business/authz/autils"
	"git.rosy.net.cn/jx-callback/business/jxstore/cms"
	"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/model/dao"
	"git.rosy.net.cn/jx-callback/globals"
	"git.rosy.net.cn/jx-callback/globals/api"
)

const (
	minCSOrderPayment = 0    // 供货订单的最小金额（单位为元）
	maxUnitPrice      = 3000 // 为防止误填单价，限制单价最高（单位为分）
)

func OnCallbackMsg(msg *weimobapi.CallbackMsg) (response *weimobapi.CallbackResponse) {
	orderID := utils.Int64ToStr(msg.OrderNo)
	jxutils.CallMsgHandler(func() {
		response = onOrderMsg(msg)
	}, jxutils.ComposeUniversalOrderID(orderID, model.VendorIDWSC))
	return response
}

func onOrderMsg(msg *weimobapi.CallbackMsg) (response *weimobapi.CallbackResponse) {
	if msg.Event == weimobapi.MsgEventOrderStatusChange {
		if utils.ForceInterface2Int64(msg.MsgBody["orderStatus"]) == weimobapi.MsgOrderStatusFinished {
			if orderDetail, err := api.WeimobAPI.QueryOrderDetail2(msg.OrderNo, false); err == nil {
				if orderDetail.OrderStatus == weimobapi.OrderStatusFinished && orderDetail.PaymentAmount >= minCSOrderPayment {
					changeStoreSkusByOrder(orderDetail)
				}
			} else {
				response = weimobapi.Err2CallbackResponse(err, "")
			}
		}
	}
	return response
}

func changeStoreSkusByOrder(order *weimobapi.OrderDetail) {
	receiverMobile := order.DeliveryDetail.LogisticsDeliveryDetail.ReceiverMobile
	ctx := jxcontext.NewWithUserName(nil, utils.LimitStringLen(utils.Int64ToStr(order.OrderNo), 32), nil, nil)
	if storeList, err := GetStoreList4Mobile(dao.GetDB(), []string{receiverMobile}); err == nil {
		if len(storeList) >= 1 {
			var skuBindInfos []*cms.StoreSkuBindInfo
			storeID := storeList[0].ID
			for _, v := range order.ItemList {
				nameID := int(utils.Str2Int64WithDefault(v.SkuCode, 0))
				unitPrice := v.CostPrice
				if nameID > 0 && (unitPrice > 0 && unitPrice < maxUnitPrice) {
					skuBindInfos = append(skuBindInfos, &cms.StoreSkuBindInfo{
						StoreID:   storeID,
						NameID:    nameID,
						UnitPrice: int(jxutils.StandardPrice2Int(unitPrice)),
						IsFocus:   1,
						IsSale:    1,
					})
				} else {
					globals.SugarLogger.Infof("[运营]，微商城订单:%d，商品:%s没有设置正确的SkuName编码或单价，当前商家编码:%s，市场价:%s", order.OrderNo, v.SkuNum, v.SkuCode, jxutils.IntPrice2StandardString(jxutils.StandardPrice2Int(unitPrice)))
				}
			}
			if len(skuBindInfos) > 0 {
				var nameIDs []int
				for _, v := range skuBindInfos {
					nameIDs = append(nameIDs, v.NameID)
				}
				if skuNamesInfo, err := cms.GetSkuNames(ctx, "", false, false, map[string]interface{}{
					"nameIDs": string(utils.MustMarshal(nameIDs)),
				}, 0, 0); err == nil {
					for _, skuName := range skuNamesInfo.SkuNames {
						if skuName.Status != model.SkuStatusNormal {
							cms.UpdateSkuName(ctx, skuName.ID, map[string]interface{}{
								"status": model.SkuStatusNormal,
							}, false)
						}
						for _, sku := range skuName.Skus {
							if sku.Status != model.SkuStatusNormal {
								cms.UpdateSku(ctx, sku.ID, map[string]interface{}{
									"status": model.SkuStatusNormal,
								})
							}
						}
					}
				}
				cms.UpdateStoreSkus(ctx, 0, storeID, skuBindInfos, true, true)
			} else {
				globals.SugarLogger.Debugf("changeStoreSkusByOrder orderID:%d, storeID:%d is empty", order.OrderNo, storeID)
			}
		} else {
			globals.SugarLogger.Infof("[运营]，微商城订单:%d，手机:%s找不到唯一一个本地门店%d", order.OrderNo, receiverMobile, len(storeList))
		}
	} else {
		globals.SugarLogger.Warnf("changeStoreSkusByOrder orderNo:%d, receiverMobile:%s failed with err:%v", order.OrderNo, receiverMobile, err)
	}
}

func GetStoreList4Mobile(db *dao.DaoDB, mobileList []string) (storeList []*model.Store, err error) {
	sql := `
	SELECT t1.*
	FROM store t1
	WHERE t1.deleted_at = ? /*AND t1.change_price_type = ?*/`
	sqlParams := []interface{}{
		utils.DefaultTimeValue,
		// model.StoreChangePriceTypeBossDisabled,
	}
	if len(mobileList) > 0 {
		questionMarks := dao.GenQuestionMarks(len(mobileList))
		sql += " AND (t1.tel1 IN (" + questionMarks + ") OR t1.tel2 IN (" + questionMarks + `)
		OR (SELECT
			COUNT(*)
			FROM casbin_rule t2
			JOIN user t3 ON t3.user_id = t2.v0 AND t3.mobile IN (` + questionMarks + `)
			WHERE t2.v1 = CONCAT(?, t1.id)
		) > 0)
		`
		sqlParams = append(sqlParams, mobileList, mobileList, mobileList, autils.NewStoreBossRole(-1).GetFullName())
	}
	err = dao.GetRows(db, &storeList, sql, sqlParams...)
	return storeList, err
}
