package pddapi

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

const (
	cthMediaID = 9180924964

	resouceTypeSecKill       = 4     //限时秒杀
	resouceTypeCharge        = 39997 //充值中心,
	resouceTypeActChangeLink = 39998 //活动转链，
	resouceTypeBYBT          = 39996 //百亿补贴，
	resouceTypeDQC           = 39999 //电器城，
	resouceTypeLQZX          = 40000 //领券中心，
	resouceTypeHCP           = 50005 //火车票
)

type GoodsOPidGenerateResult struct {
	PIDGenerateResponse struct {
		PIDList []struct {
			CreateTime int    `json:"create_time"`
			MediaID    int64  `json:"media_id"`
			PidName    string `json:"pid_name"`
			PID        string `json:"p_id"`
		} `json:"p_id_list"`
		RemainPidCount int    `json:"remain_pid_count"`
		RequestID      string `json:"request_id"`
	} `json:"p_id_generate_response"`
}

//创建推广位
func (a *API) GoodsOPidGenerate(name string) (pid string, err error) {
	result, err := a.AccessAPI("pdd.ddk.goods.pid.generate", false, map[string]interface{}{
		"number":         1,
		"p_id_name_list": []string{"\"" + name + "\""},
		"media_id":       cthMediaID,
	})
	if err == nil {
		goodsOPidGenerateResult := &GoodsOPidGenerateResult{}
		utils.Map2StructByJson(result, &goodsOPidGenerateResult, false)
		if goodsOPidGenerateResult != nil {
			pid = goodsOPidGenerateResult.PIDGenerateResponse.PIDList[0].PID
		}
	}
	return pid, err
}

type ActivityOperationListResult struct {
	ID             int    `json:"id"`
	Name           string `json:"name"`
	Starttime      string `json:"startTime"`
	Endtime        string `json:"endTime"`
	Description    string `json:"description"`
	Introduction   string `json:"introduction"`
	Level          int    `json:"level"`
	Goodspoolid    string `json:"goodsPoolId"`
	Duoimage       string `json:"duoImage"`
	Bannerimage    string `json:"bannerImage"`
	Filename       string `json:"fileName"`
	Fileurl        string `json:"fileUrl"`
	Activitylink   string `json:"activityLink"`
	Cpscoverage    int    `json:"cpsCoverage"`
	Activitystatus int    `json:"activityStatus"`
	Tagid          int    `json:"tagId"`
	Goodslist      []struct {
		Mallid                int           `json:"mallId"`
		Mallname              string        `json:"mallName"`
		Malllogo              interface{}   `json:"mallLogo"`
		Qrcodeimageurl        interface{}   `json:"qrCodeImageUrl"`
		Merchanttype          int           `json:"merchantType"`
		Hascltcpn             bool          `json:"hasCltCpn"`
		Goodsid               int64         `json:"goodsId"`
		Goodssign             string        `json:"goodsSign"`
		Goodsname             string        `json:"goodsName"`
		Goodsdesc             string        `json:"goodsDesc"`
		Goodsimageurl         string        `json:"goodsImageUrl"`
		Goodsthumbnailurl     string        `json:"goodsThumbnailUrl"`
		Mingroupprice         int           `json:"minGroupPrice"`
		Categoryid            int           `json:"categoryId"`
		Categoryname          string        `json:"categoryName"`
		Goodstype             int           `json:"goodsType"`
		Subsidyamount         interface{}   `json:"subsidyAmount"`
		Haspddcoupon          interface{}   `json:"hasPddCoupon"`
		Hascoupon             bool          `json:"hasCoupon"`
		Couponminorderamount  int           `json:"couponMinOrderAmount"`
		Coupondiscount        int           `json:"couponDiscount"`
		Coupontotalquantity   int           `json:"couponTotalQuantity"`
		Couponremainquantity  int           `json:"couponRemainQuantity"`
		Couponstarttime       int           `json:"couponStartTime"`
		Couponendtime         int           `json:"couponEndTime"`
		Mallclientable        bool          `json:"mallClientAble"`
		Plantype              int           `json:"planType"`
		Plantypeisbest        interface{}   `json:"planTypeIsBest"`
		Zsduoid               int           `json:"zsDuoId"`
		Plantypeall           int           `json:"planTypeAll"`
		Promotionrate         int           `json:"promotionRate"`
		Activitypromotionrate interface{}   `json:"activityPromotionRate"`
		Sharerate             int           `json:"shareRate"`
		Mallrate              int           `json:"mallRate"`
		Optid                 int           `json:"optId"`
		Collected             bool          `json:"collected"`
		Marketfee             int           `json:"marketFee"`
		Salestip              string        `json:"salesTip"`
		Desctxt               string        `json:"descTxt"`
		Servtxt               string        `json:"servTxt"`
		Lgsttxt               string        `json:"lgstTxt"`
		Issceneauth           interface{}   `json:"isSceneAuth"`
		Inbigsale             []int         `json:"inBigSale"`
		Haohuocouponlist      interface{}   `json:"haohuoCouponList"`
		Brandcouponlist       []interface{} `json:"brandCouponList"`
		Isonsale              bool          `json:"isOnsale"`
		Isbijia               bool          `json:"isBiJia"`
		Isextramissiongoods   bool          `json:"isExtraMissionGoods"`
		Unifiedtag            struct {
			Goodsid int64 `json:"goodsId"`
			Tagdtos []struct {
				Groupcode      int         `json:"groupCode"`
				Tagseries      int         `json:"tagSeries"`
				Tagid          int         `json:"tagId"`
				Text           string      `json:"text"`
				Color          string      `json:"color"`
				URL            interface{} `json:"url"`
				Prefiximageurl interface{} `json:"prefixImageUrl"`
				Link           interface{} `json:"link"`
				Width          interface{} `json:"width"`
				Height         interface{} `json:"height"`
			} `json:"tagDTOs"`
			Icondtos      []interface{} `json:"iconDTOs"`
			Highlightdtos []interface{} `json:"highLightDTOs"`
			Rankdtos      []interface{} `json:"rankDTOs"`
		} `json:"unifiedTag"`
		Matchtype              int         `json:"matchType"`
		Goodsgalleryurls       interface{} `json:"goodsGalleryUrls"`
		Hasmaterial            bool        `json:"hasMaterial"`
		Withfixedrate          bool        `json:"withFixedRate"`
		Nextlevelpromotionrate int         `json:"nextLevelPromotionRate"`
		Nextlevelmarketfee     int         `json:"nextLevelMarketFee"`
		Extrainfovo            interface{} `json:"extraInfoVO"`
	} `json:"goodsList"`
}

//获取官方活动
func (a *API) ActivityOperationList() (activityOperationListResult []*ActivityOperationListResult, err error) {
	result, err := a.AccessStorePage("https://jinbao.pinduoduo.com/network/api/activity/operation/list", map[string]interface{}{
		"inPrepare":  false,
		"pageNumber": 1,
		"pageSize":   9,
	}, true)
	if err == nil {
		utils.Map2StructByJson(result["result"].(map[string]interface{})["list"], &activityOperationListResult, false)
	}
	return activityOperationListResult, err
}

type RpPromURLGenerateResult struct {
	ResourceList []struct {
		URL  string `json:"url"`
		Desc string `json:"desc"`
	} `json:"resource_list"`
	RequestID string `json:"request_id"`
}

//生成营销工具推广链接
func (a *API) RpPromURLGenerate(pid string) (rpPromURLGenerateResult *RpPromURLGenerateResult, err error) {
	result, err := a.AccessAPI("pdd.ddk.rp.prom.url.generate", false, map[string]interface{}{
		"p_id_list":    []string{"\"" + pid + "\""},
		"channel_type": -1,
	})
	if err == nil {
		utils.Map2StructByJson(result["rp_promotion_url_generate_response"], &rpPromURLGenerateResult, false)
	}
	return rpPromURLGenerateResult, err
}

type ResourceURLGenResult struct {
	SingleURLList struct {
		WeAppPagePath        string `json:"we_app_page_path"`
		MobileURL            string `json:"mobile_url"`
		MobileShortURL       string `json:"mobile_short_url"`
		WeAppWebViewURL      string `json:"we_app_web_view_url"`
		URL                  string `json:"url"`
		ShortURL             string `json:"short_url"`
		WeAppWebViewShortURL string `json:"we_app_web_view_short_url"`
	} `json:"single_url_list"`
	Sign      string `json:"sign"`
	WeAppInfo struct {
		WeAppIconURL      string `json:"we_app_icon_url"`
		UserName          string `json:"user_name"`
		PagePath          string `json:"page_path"`
		SourceDisplayName string `json:"source_display_name"`
		Title             string `json:"title"`
		AppID             string `json:"app_id"`
		Desc              string `json:"desc"`
	} `json:"we_app_info"`
	RequestID string `json:"request_id"`
}

//生成频道推广链接
func (a *API) ResourceURLGen(pid string, resourceType int) (resourceURLGenResult *ResourceURLGenResult, err error) {
	result, err := a.AccessAPI("pdd.ddk.resource.url.gen", false, map[string]interface{}{
		"pid":           pid,
		"resource_type": resourceType,
	})
	if err == nil {
		utils.Map2StructByJson(result["resource_url_response"], &resourceURLGenResult, false)
	}
	return resourceURLGenResult, err
}

type GoodsPromotionURLGenResult struct {
	MobileURL string `json:"mobile_url"`
	WeAppInfo struct {
		WeAppIconURL      string `json:"we_app_icon_url"`
		UserName          string `json:"user_name"`
		PagePath          string `json:"page_path"`
		SourceDisplayName string `json:"source_display_name"`
		Title             string `json:"title"`
		AppID             string `json:"app_id"`
		Desc              string `json:"desc"`
	} `json:"we_app_info"`
	MobileShortURL       string `json:"mobile_short_url"`
	WeAppWebViewURL      string `json:"we_app_web_view_url"`
	URL                  string `json:"url"`
	ShortURL             string `json:"short_url"`
	WeAppWebViewShortURL string `json:"we_app_web_view_short_url"`
}

//生成商品推广链接
func (a *API) GoodsPromotionURLGen(pid string, goodsID string, isAuth bool) (resourceURLGenResult *GoodsPromotionURLGenResult, err error) {
	var resourceURLGenResults []*GoodsPromotionURLGenResult
	params := map[string]interface{}{
		"p_id":               pid,
		"generate_short_url": true,
		"goods_sign_list":    []string{"\"" + goodsID + "\""},
		//"generate_authority_url": true,
		"generate_we_app": true,
	}
	if isAuth {
		params["generate_authority_url"] = true
	}
	result, err := a.AccessAPI("pdd.ddk.goods.promotion.url.generate", false, params)
	if err == nil {
		utils.Map2StructByJson(result["goods_promotion_url_generate_response"].(map[string]interface{})["goods_promotion_url_list"], &resourceURLGenResults, false)
		if len(resourceURLGenResults) > 0 {
			return resourceURLGenResults[0], err
		}
	}
	return resourceURLGenResult, err
}

//查询是否绑定备案
func (a *API) MemberAuthorityQuery(pid string) (bool bool, err error) {
	result, err := a.AccessAPI("pdd.ddk.member.authority.query", false, map[string]interface{}{
		"pid": pid,
	})
	if err == nil {
		if utils.MustInterface2Int64(result["authority_query_response"].(map[string]interface{})["bind"]) == 0 {
			return false, err
		} else {
			return true, err
		}
	}
	return false, err
}
