package apimanager

import (
	"encoding/json"
	"git.rosy.net.cn/baseapi/platformapi/jdapi"
	"git.rosy.net.cn/baseapi/platformapi/tao_vegetable"
	"git.rosy.net.cn/baseapi/platformapi/tiktok_shop/tiktok_api"
	"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/business/partner"
	"git.rosy.net.cn/jx-callback/globals"
	"git.rosy.net.cn/jx-callback/globals/api"
	beego "github.com/astaxie/beego/server/web"
	"time"
)

const (
	FakeJdOrgCode = "fakejd"
)

type VendorOrgCodePair struct {
	VendorID   int
	AppOrgCode string
}

type APIManager struct {
}

var (
	CurAPIManager *APIManager
)

func init() {
	CurAPIManager = &APIManager{}
	partner.InitAPIManager(CurAPIManager)
}

func (a *APIManager) GetAPI(vendorID int, appOrgCode string) (pfAPI interface{}) {
	var (
		db = dao.GetDB()
	)
	switch vendorID {
	case model.VendorIDJD:
		if appOrgCode == FakeJdOrgCode {
			pfAPI = api.FakeJdAPI
		} else {
			codes, _ := dao.GetVendorOrgCode(db, vendorID, appOrgCode, "platform")
			if len(codes) == 0 {
				return nil
			}
			code := codes[0]
			api.JdAPI = jdapi.New(code.Token, code.AppKey, code.AppSecret)
			pfAPI = api.JdAPI
			if configs, err := dao.QueryConfigs(dao.GetDB(), "jdStorePageCookie", model.ConfigTypeCookie, ""); err == nil {
				api.JdAPI.SetCookieWithStr(configs[0].Value)
			}
			if configs, err := dao.QueryConfigs(dao.GetDB(), "jdStorePageEarning", model.ConfigTypeCookie, ""); err == nil {
				api.JdAPI.SetCookie("user", configs[0].Value)
			}
		}
	case model.VendorIDMTWM:
		pfAPI = api.MtwmAPI
		if appOrgCode == globals.Mtwm2Code {
			pfAPI = api.Mtwm2API
		}
	case model.VendorIDTaoVegetable:
		api2 := api.TaoVegetableApi
		codes, _ := dao.GetVendorOrgCode(db, vendorID, appOrgCode, "platform")
		if len(codes) == 0 {
			return nil
		}
		code := codes[0]
		api2 = tao_vegetable.NewTaoVegetable(code.AppKey, code.AppSecret, beego.AppConfig.DefaultString("taoVegetableServerUrl", ""))
		if code.Token != "" {
			var tokenInfo *tao_vegetable.StoreTokenInfo
			if err := json.Unmarshal([]byte(code.Token), &tokenInfo); err != nil {
				return nil
			}
			if tokenInfo.AccessToken != "" && tokenInfo.ExpireTime > time.Now().UnixNano()/1e6 {
				api2.SetToken(tokenInfo.AccessToken)
				api2.SetVendorOrgCode(code.VendorOrgCode)
			}
		}
		pfAPI = api2
	case model.VendorIDEBAI:
		pfAPI = api.EbaiAPI
	case model.VendorIDJDShop:
		pfAPI = api.JdShopAPI
	case model.VendorIDTT:
		pfAPI = api.TiktokApi
	case model.VendorIDDD:
		codes, _ := dao.GetVendorOrgCode(db, vendorID, appOrgCode, "platform")
		if len(codes) == 0 {
			return nil
		}
		pfAPI = tiktok_api.New(beego.AppConfig.DefaultString("tiktokShopAppId", ""), beego.AppConfig.DefaultString("tiktokShopAppSecret", ""), codes[0].Token)
	}
	return pfAPI
}

// TODO
func (a *APIManager) GetAppOrgCodeList(vendorID int) (appOrgCodeList []string) {
	switch vendorID {
	case model.VendorIDJD:
		vendorOrgCodes, _ := dao.GetVendorOrgCode(dao.GetDB(), model.VendorIDJD, "", model.VendorOrgTypePlatform)
		for _, v := range vendorOrgCodes {
			appOrgCodeList = append(appOrgCodeList, v.VendorOrgCode)
		}
	case model.VendorIDDD:
		vendorOrgCodes, _ := dao.GetVendorOrgCode(dao.GetDB(), model.VendorIDDD, "", model.VendorOrgTypePlatform)
		for _, v := range vendorOrgCodes {
			appOrgCodeList = append(appOrgCodeList, v.VendorOrgCode)
		}
	case model.VendorIDTaoVegetable:
		vendorOrgCodes, _ := dao.GetVendorOrgCode(dao.GetDB(), model.VendorIDTaoVegetable, "", model.VendorOrgTypePlatform)
		for _, v := range vendorOrgCodes {
			appOrgCodeList = append(appOrgCodeList, v.VendorOrgCode)
		}
	case model.VendorIDMTWM:
		appOrgCodeList = []string{api.MtwmAPI.GetAppID(), api.Mtwm2API.GetAppID()}
	case model.VendorIDEBAI:
		appOrgCodeList = []string{api.EbaiAPI.GetSource()}
	case model.VendorIDJDShop:
		appOrgCodeList = []string{"2"}
	}
	return appOrgCodeList
}

func (a *APIManager) GetVendorOrgCodeList(vendorIDs []int, appOrgCodes []string) (vendorOrgCodeList []*VendorOrgCodePair) {
	if len(vendorIDs) == 0 {
		vendorIDs = partner.GetMultiStoreVendorIDs()
	}
	appOrgCodeMap := jxutils.StringList2Map(appOrgCodes)
	for _, vendorID := range vendorIDs {
		tmpOrgCodeList := a.GetAppOrgCodeList(vendorID)
		for _, v := range tmpOrgCodeList {
			if len(appOrgCodes) == 0 || appOrgCodeMap[v] == 1 {
				vendorOrgCodeList = append(vendorOrgCodeList, &VendorOrgCodePair{
					VendorID:   vendorID,
					AppOrgCode: v,
				})
			}
		}
	}
	return vendorOrgCodeList
}

func GetVendorOrgCodeMap(ctx *jxcontext.Context) (vendorOrgCodeMap map[int][]string) {
	vendorOrgCodeMap = make(map[int][]string)
	for _, vendorID := range partner.GetPurchasePlatformVendorIDs() {
		vendorOrgCodeMap[vendorID] = CurAPIManager.GetAppOrgCodeList(vendorID)
	}
	return vendorOrgCodeMap
}
