package ebaiapi

import (
	"fmt"
	"strings"

	"git.rosy.net.cn/baseapi/utils"
)

const (
	ActivityTypeDirectDown   = 2 // 商品直降
	ActivityTypeFullDiscount = 8 // 品类满减

	ActivityPFBaidu = 1 // 星选
	ActivityPFELM   = 2 // 饿了么
	ActivityPFAll   = 4 // 星选&饿了么

	ActivityConflictShare    = 0 // 与全店满减等其他活动同享
	ActivityConfilictExclude = 1 // 与全店满减等其他活动互斥

	MaxActivitySkuBatchSize = 100 // 使用商品id的活动商品，与商品自定义id互斥。一批最多100个
	// 下面两个是做什么用的？
	// ActivityShowStatusEnabled  = 2
	// ActivityShowStatusDisabled = 4

	MaxActivityNameLength = 30 // 活动名称为空或者长度大于30个字符
	MaxActivityDescLength = 15 // 优惠描述限15个字符
)

var (
	ActivityTypeList = []string{
		"2",  //:单品特价,
		"8",  //:品类满减,
		"9",  //:全店满减,
		"10", //:新用户立减,
		"11", //:运费满减,
		"41", //:第N件特价,
		"32", //:N选1商品活动,
		"40", //:买N赠M商品活动,
		"33", //:下单返券活动,
		"34", //:M件X元或折,
		"35", //:N元购,
		"36", //:全店满减券(即商家代金券),
		"37", //:商品满减券,
		"38", //:跨seller商品满减券,
		"39", //:跨seller运费券
	}

	//优惠类型
	DiscountTypeMap = map[int]string{
		1: "减钱",
		2: "折扣",
		3: "一口价",
		4: "买赠",
		5: "下单返券",
	}
)

type ActivityRule struct {
	Accords int `json:"accords"` // 订单达到的金额，正整数，单位元。
	Sale    int `json:"sale"`    // 每单减价额度，正整数，单位元。
}

type ActivityInfo struct {
	ActivityID         int64           `json:"activityID,omitempty"`
	ActivityName       string          `json:"activity_name"`
	ActivityType       int             `json:"activity_type"`
	StartTime          int64           `json:"start_time"` // 活动开始时间，时间戳，需大于当前时间。
	EndTime            int64           `json:"end_time"`
	OpenTime           string          `json:"open_time,omitempty"` // "22:47"
	CloseTime          string          `json:"close_time,omitempty"`
	WeekDay            string          `json:"weekday,omitempty"` // 活动开始时间段内，每周具体星期几支持，默认活动生效时间段内全周支持。0,1,2,3,4,5,6代表周日到周六。
	ActivityPlatform   int             `json:"activity_platform,omitempty"`
	IsConflictActivity int             `json:"is_conflict_activity,omitempty"`
	DayLimit           int             `json:"day_limit,omitempty"`   // 每日限购X单，1-1000整数。
	OrderLimit         int             `json:"order_limit,omitempty"` // 每单限购商品数量。直降用到，满减没用到。1-1000整数。
	ActivityDesc       string          `json:"activity_desc,omitempty"`
	ShowCategory       string          `json:"show_category,omitempty"`
	PromotionSkuDesc   string          `json:"promotion_sku_desc,omitempty"` // 店铺页活动商品的分类名称，不超过8个字。
	Rule               []*ActivityRule `json:"rule,omitempty"`

	BaiduShopID int64 `json:"baidu_shop_id,omitempty"` // 这个用于查询时返回值，设置时这里设置的值会被忽略
	// ShowStatus  int   `json:"showStatus,omitempty"`
}

type ActivitySkuInfo4Add struct {
	SkuID string `json:"sku_id"`
	Stock int    `json:"stock"`

	StoreUserLimit int   `json:"store_user_limit"`
	SpecialPrice   int64 `json:"special_price"`
}

type ActivitySkuInfo4List struct {
	BaiduShopID int64  `json:"baidu_shop_id"`
	SkuID       string `json:"sku_id"`
	UpcName     string `json:"upc_name"`
	Stock       int    `json:"stock"`

	PromotionPrice float32 `json:"promotion_price"` // 商品活动价，单位元，品类满减活动不返回活动价。
	OriginalPrice  float32 `json:"original_price"`  // 添加商品时商品原价，单位元。
}

type ActivitySkuInfo4Update struct {
	BaiduShopID int64  `json:"baidu_shop_id,omitempty"`
	ShopID      string `json:"shop_id,omitempty"`
	SkuID       string `json:"sku_id,omitempty"`
	CustomSkuID string `json:"custom_sku_id,omitempty"`
	Stock       int    `json:"stock,omitempty"`

	StoreUserLimit int   `json:"store_user_limit,omitempty"`
	SpecialPrice   int64 `json:"special_price,omitempty"`
}

type ActivitySkuListInfo struct {
	ActivityID   int64                   `json:"activity_id"`
	ActivityType int                     `json:"activity_type"`
	ActivityName string                  `json:"activity_name"`
	SkuList      []*ActivitySkuInfo4List `json:"sku_list"`
}

// 创建商品营销活动
// https://open-be.ele.me/dev/api/doc/v3/#api-Marketing-activity_create
func (a *API) ActivityCreate(shopID string, baiduShopID, supplierID int64, activity *ActivityInfo) (activityID int64, err error) {
	activity.BaiduShopID = 0
	params := utils.Struct2FlatMap(activity)
	result, err := a.AccessAPI("activity.create", utils.MergeMaps(params, a.genShopIDParams(shopID, baiduShopID, supplierID)))
	if err == nil {
		return utils.MustInterface2Int64(result.Data.(map[string]interface{})["activity_id"]), nil
	}
	return 0, err
}

// 更新活动信息
// https://open-be.ele.me/dev/api/doc/v3/#api-Marketing-activity_update
func (a *API) ActivityUpdate(activityID int64, shopID string, baiduShopID, supplierID int64, activity *ActivityInfo) (newActivityID int64, err error) {
	activity.BaiduShopID = 0
	params := utils.Struct2FlatMap(activity)
	params[KeyActivityID] = activityID
	result, err := a.AccessAPI("activity.update", utils.MergeMaps(params, a.genShopIDParams(shopID, baiduShopID, supplierID)))
	if err == nil {
		return utils.MustInterface2Int64(result.Data.(map[string]interface{})["activity_id"]), nil
	}
	return 0, err
}

// 下线商品营销活动
// https://open-be.ele.me/dev/api/doc/v3/#api-Marketing-activity_disable
func (a *API) ActivityDisable(activityID int64, shopID string, baiduShopID, supplierID int64) (err error) {
	params := a.genShopIDParams(shopID, baiduShopID, supplierID)
	params[KeyActivityID] = activityID
	_, err = a.AccessAPI("activity.disable", params)
	return err
}

// 查看活动信息
// https://open-be.ele.me/dev/api/doc/v3/#api-Marketing-activity_get
func (a *API) ActivityGet(activityID int64, shopID string, baiduShopID, supplierID int64) (activityInfo *ActivityInfo, err error) {
	params := a.genShopIDParams(shopID, baiduShopID, supplierID)
	params[KeyActivityID] = activityID
	result, err := a.AccessAPI("activity.get", params)
	if err == nil {
		activityInfo = &ActivityInfo{}
		err = utils.Map2StructByJson(result.Data, activityInfo, true)
	}
	return activityInfo, err
}

// 批量添加活动商品
// https://open-be.ele.me/dev/api/doc/v3/#api-Marketing-activity_sku_add_batch
func (a *API) ActivitySkuAddBatch(activityID int64, shopID string, baiduShopID int64, activityType int, skuList []*ActivitySkuInfo4Add, isSkuIDCustom bool) (successIDs []string, err error) {
	params := a.genShopIDParams(shopID, baiduShopID, 0)
	params[KeyActivityID] = activityID
	skusKey := "activity_skus"
	if isSkuIDCustom {
		skusKey = "activity_custom_skus"
	}
	params[skusKey] = skuList2Str(activityType, skuList, isSkuIDCustom)
	result, err := a.AccessAPI("activity.sku.add.batch", params)
	if err == nil {
		return strings.Split(utils.Interface2String(result.Data), ","), nil
	}
	return nil, err
}

func skuList2Str(activityType int, skuList []*ActivitySkuInfo4Add, isSkuIDCustom bool) string {
	skuList2 := []string{}
	for _, v := range skuList {
		strList := []string{
			v.SkuID,
			utils.Int2Str(v.Stock),
		}
		if activityType == ActivityTypeDirectDown {
			strList = append(strList, utils.Int64ToStr(v.SpecialPrice))
			if v.StoreUserLimit > 0 {
				strList = append(strList, utils.Int2Str(v.StoreUserLimit))
			}
		}
		skuList2 = append(skuList2, strings.Join(strList, ":"))
	}
	return strings.Join(skuList2, ";")
}

// 批量删除活动商品
// https://open-be.ele.me/dev/api/doc/v3/#api-Marketing-activity_sku_delete_batch
func (a *API) ActivitySkuDeleteBatch(activityID int64, shopID string, baiduShopID int64, skuIDs []string, isSkuIDCustom bool) (successIDs []string, err error) {
	params := a.genShopIDParams(shopID, baiduShopID, 0)
	params[KeyActivityID] = activityID
	skusKey := "sku_id"
	if isSkuIDCustom {
		skusKey = "custom_sku_id"
	}
	params[skusKey] = strings.Join(skuIDs, ",")
	result, err := a.AccessAPI("activity.sku.delete.batch", params)
	if err == nil {
		if str, ok := result.Data.(string); ok {
			return strings.Split(str, ","), nil
		} else {
			return nil, err
		}
	}
	return nil, err
}

// 批量添加活动商品
// https://open-be.ele.me/dev/api/doc/v3/#api-Marketing-activity_sku_add_batch
func (a *API) ActivitySkuList(activityID int64, shopID string, baiduShopID, supplierID int64, skuIDs []string, isSkuIDCustom bool) (activityInfo *ActivitySkuListInfo, err error) {
	params := a.genShopIDParams(shopID, baiduShopID, supplierID)
	params[KeyActivityID] = activityID
	if len(skuIDs) > 0 {
		skusKey := "sku_id"
		if isSkuIDCustom {
			skusKey = "custom_sku_id"
		}
		params[skusKey] = strings.Join(skuIDs, ",")
	}
	pageSize := 100
	page := 1
	params["page_size"] = pageSize
	for {
		var result *ResponseResult
		params["page"] = page
		result, err = a.AccessAPI("activity.sku.list", params)
		if err == nil {
			resultMap := result.Data.(map[string]interface{})
			if activityInfo == nil {
				if err = utils.Map2StructByJson(resultMap, &activityInfo, true); err != nil {
					return nil, err
				}
			} else {
				var skuList []*ActivitySkuInfo4List
				if err = utils.Map2StructByJson(resultMap["sku_list"], &skuList, true); err != nil {
					return nil, err
				}
				activityInfo.SkuList = append(activityInfo.SkuList, skuList...)
			}
			if len(activityInfo.SkuList) >= int(utils.MustInterface2Int64(resultMap["total"])) {
				break
			}
			page++
		} else {
			break
		}
	}
	return activityInfo, err
}

// 批量更新活动商品
// https://open-be.ele.me/dev/api/doc/v3/#api-Marketing-activity_sku_update_batch
func (a *API) ActivitySkuUpdateBatch(activityID int64, actSkuInfoList []*ActivitySkuInfo4Update) (faildInfoList []string, err error) {
	result, err := a.AccessAPI("activity.sku.update.batch", map[string]interface{}{
		KeyActivityID:  activityID,
		"act_sku_info": actSkuInfoList,
	})
	if err == nil {
		return strings.Split(utils.Interface2String(result.Data), ";"), nil
	}
	return nil, err
}

// 多渠道查询获取参与的活动IdList
func (a *API) ActMultiChannelQueryIDs(shopID string, baiduShopID int64, actType string) (actIDs []int64, err error) {
	params := a.genShopIDParams(shopID, baiduShopID, 0)
	params["query_activity_type"] = actType
	params["page_size"] = 100
	result, err := a.AccessAPI("act.multi.channel.queryids", params)
	if err == nil {
		if result.Data != nil {
			for _, v := range result.Data.(map[string]interface{})["activityIdList"].([]interface{}) {
				actIDs = append(actIDs, utils.MustInterface2Int64(v))
			}
			return actIDs, nil
		}
	}
	return actIDs, err
}

type ActMultiChannelQueryInfosResult struct {
	Activityplatform      int `json:"activityPlatform"`
	Childtype             int `json:"childType"`
	Periodsandruleapilist []struct {
		Periods []struct {
			Weekday   string `json:"weekday"`
			Closetime string `json:"closeTime"`
			Opentime  string `json:"openTime"`
		} `json:"periods"`
	} `json:"periodsAndRuleApiList"`
	Skulist         []*ActMultiChannelQueryInfosSkuList `json:"skuList"`
	Deliverychannel int                                 `json:"deliveryChannel"`
	Limitruleapi    struct {
		Usertotalcountlimit int `json:"userTotalCountLimit"`
		Userdaycountlimit   int `json:"userDayCountLimit"`
	} `json:"limitRuleApi"`
	Activityname string `json:"activityName"`
	Activityid   int64  `json:"activityId"`
	Createtime   int64  `json:"createTime"`
	Starttime    int64  `json:"startTime"`
	Endtime      int64  `json:"endTime"`
	Skutotal     int    `json:"skuTotal"`
	Activitytype int    `json:"activityType"`
	Status       int    `json:"status"`
}

type ActMultiChannelQueryInfosSkuList struct {
	Itemid                int64 `json:"itemId"`
	Periodsandruleapilist []struct {
		Ruleapi struct {
			Subsidyapi struct {
				Agentsubsidy int `json:"agentSubsidy"`
				Elemesubsidy int `json:"elemeSubsidy"`
				Shopsubsidy  int `json:"shopSubsidy"`
			} `json:"subsidyApi"`
			Discount     int `json:"discount"`
			Discounttype int `json:"discountType"`
		} `json:"ruleApi"`
	} `json:"periodsAndRuleApiList"`
	Wid          int64 `json:"wid"`
	Limitruleapi struct {
		Usertotalcountlimit int `json:"userTotalCountLimit"`
		Detaildaycountlimit int `json:"detailDayCountLimit"`
		Detailcountlimit    int `json:"detailCountLimit"`
		Userdaycountlimit   int `json:"userDayCountLimit"`
	} `json:"limitRuleApi"`
	Realstock    int    `json:"realStock"`
	Dayrealstock int    `json:"dayRealStock"`
	Storeid      int    `json:"storeId"`
	Upcname      string `json:"upcName"`
	Skuid        string `json:"skuId"`
}

// 多渠道查询活动详情(此接口成功率不达标,原因是上一个接口获取门店活动id时,把门店结束活动id查询出来了,但是此接口查询结束活动时,失效了)
func (a *API) ActMultiChannelQueryInfos(activityID, shopID string, baiduShopID int64) (actMultiChannelQueryInfosResult *ActMultiChannelQueryInfosResult, err error) {
	pageSize := 100
	params := a.genShopIDParams(shopID, baiduShopID, 0)
	params["activity_id"] = activityID
	params["page_size"] = pageSize
	result, err := a.AccessAPI("act.multi.channel.queryinfos", params)
	fmt.Println(err)
	if err == nil {
		if result.Data != nil {
			utils.Map2StructByJson(result.Data.(map[string]interface{}), &actMultiChannelQueryInfosResult, false)
			if actMultiChannelQueryInfosResult.Skutotal > pageSize {
				for page := 2; page < actMultiChannelQueryInfosResult.Skutotal/pageSize+2; page++ {
					actMultiChannelQueryInfosResult.Skulist = append(actMultiChannelQueryInfosResult.Skulist, a.ActMultiChannelQueryInfosPage(activityID, shopID, baiduShopID, page)...)
				}
			} else {
				return actMultiChannelQueryInfosResult, err
			}
		}
	}
	return actMultiChannelQueryInfosResult, err
}

// 多渠道查询活动详情
func (a *API) ActMultiChannelQueryInfosPage(activityID, shopID string, baiduShopID int64, page int) (actMultiChannelQueryInfosSkuList []*ActMultiChannelQueryInfosSkuList) {
	pageSize := 100
	params := a.genShopIDParams(shopID, baiduShopID, 0)
	params["activity_id"] = activityID
	params["page_size"] = pageSize
	params["page"] = page
	result, err := a.AccessAPI("act.multi.channel.queryinfos", params)
	if err == nil {
		if result.Data != nil {
			utils.Map2StructByJson(result.Data.(map[string]interface{})["skuList"], &actMultiChannelQueryInfosSkuList, false)
		}
	}
	return actMultiChannelQueryInfosSkuList
}
