package mtwm

import (
	"fmt"
	"strings"
	"sync"

	"git.rosy.net.cn/jx-callback/business/model/dao"

	"git.rosy.net.cn/baseapi/platformapi/mtwmapi"
	"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/business/partner/putils"
	"git.rosy.net.cn/jx-callback/globals"
	"git.rosy.net.cn/jx-callback/globals/api"
)

var (
	CurPurchaseHandler *PurchaseHandler
)

type PurchaseHandler struct {
	partner.BasePurchasePlatform
	putils.DefSingleStorePlatform

	storeIDs []string
	locker   sync.RWMutex
}

func init() {
	if api.MtwmAPI != nil || api.Mtwm2API != nil {
		CurPurchaseHandler = New()
		partner.RegisterPurchasePlatform(CurPurchaseHandler)
	}
}

func New() (obj *PurchaseHandler) {
	obj = new(PurchaseHandler)
	obj.ISingleStoreStoreSkuHandler = obj
	return obj
}

func (c *PurchaseHandler) GetVendorID() int {
	return model.VendorIDMTWM
}

func (p *PurchaseHandler) GetVendorCategories(ctx *jxcontext.Context) (vendorCats []*model.SkuVendorCategory, err error) {
	cats, err := api.MtwmAPI.RetailGetSpTagIds()
	if err != nil {
		return nil, err
	}
	vendorCatMapList := make([]map[string]*model.SkuVendorCategory, 3)
	manID := 10000
	for i := 0; i < 3; i++ {
		vendorCatMapList[i] = make(map[string]*model.SkuVendorCategory)
		for _, v := range cats {
			if v.Level == 3 {
				namePathList := strings.Split(strings.Trim(v.NamePath, ","), ",")
				if len(namePathList) != 3 {
					panic(fmt.Sprintf("%s没有三级结构", v.NamePath))
				}
				name := namePathList[i]
				if _, ok := vendorCatMapList[i][name]; !ok {
					cat := &model.SkuVendorCategory{
						VendorID: model.VendorIDMTWM,
						Name:     name,  //utils.Interface2String(v["name"]),
						Level:    i + 1, //int(utils.MustInterface2Int64(v["level"])),
					}
					vendorCats = append(vendorCats, cat)
					vendorCatMapList[i][name] = cat
					if i == 2 {
						cat.IsLeaf = 1
						cat.VendorCategoryID = utils.Int64ToStr(v.ID)
					} else {
						cat.VendorCategoryID = utils.Int2Str(manID) // 非叶子结点编码没有实际使用
						manID++
					}
					if i > 0 {
						cat.ParentID = vendorCatMapList[i-1][namePathList[i-1]].VendorCategoryID
					}
				}
			}
		}
	}
	return vendorCats, nil
}

func rangeMtwm2JX(areaStr string) string {
	var area []interface{}
	if err := utils.UnmarshalUseNumber([]byte(areaStr), &area); err == nil {
		if len(area) > 0 {
			coordList := make([]string, len(area))
			for k, v := range area {
				vv := v.(map[string]interface{})
				coordList[k] = fmt.Sprintf("%.6f,%.6f", jxutils.IntCoordinate2Standard(int(utils.ForceInterface2Int64(vv["x"]))), jxutils.IntCoordinate2Standard(int(utils.ForceInterface2Int64(vv["y"]))))
			}
			return strings.Join(coordList, ";")
		}
	}
	return ""
}

func rangeJX2Mtwm(coords string) string {
	pairs := strings.Split(strings.Trim(coords, ";"), ";")
	if len(pairs) > 0 {
		coordList := make([]map[string]interface{}, len(pairs))
		for k, v := range pairs {
			pair := strings.Split(v, ",")
			coordList[k] = map[string]interface{}{
				"x": jxutils.StandardCoordinate2Int(utils.Str2Float64(pair[0])),
				"y": jxutils.StandardCoordinate2Int(utils.Str2Float64(pair[1])),
			}
		}
		return string(utils.MustMarshal(coordList))
	}
	return ""
}

func openTimeMtwm2JX(vendorOpenTime string) (opTimeList []int16) {
	timePairs := strings.Split(vendorOpenTime, ",")
	for _, v := range timePairs {
		times := strings.Split(v, "-")
		if len(times) >= 2 {
			opTimeList = append(opTimeList, jxutils.StrTime2JxOperationTime(times[0]+":00", 700), jxutils.StrTime2JxOperationTime(times[1]+":00", 2000))
		}
	}
	return opTimeList
}

func openTimeJX2Mtwm(opTimeList []int16) string {
	timesLen := len(opTimeList) / 2 * 2
	var strPairs []string
	for i := 0; i < timesLen; i += 2 {
		if opTimeList[i] != 0 {
			strPairs = append(strPairs, jxutils.JxOperationTime2StrTime(opTimeList[i])+"-"+jxutils.JxOperationTime2StrTime(opTimeList[i+1]))
		} else {
			break
		}
	}
	return strings.Join(strPairs, ",")
}

func bizStatusMtwm2JX(openLevel, online int) int {
	if online != mtwmapi.PoiStatusOnline {
		return model.StoreStatusDisabled
	} else {
		if openLevel == mtwmapi.PoiOpenLevelHaveRest {
			return model.StoreStatusClosed
		}
	}
	return model.StoreStatusOpened
}

func bizStatusJX2Mtwm(status int) (openLevel, online int) {
	if status == model.StoreStatusDisabled {
		return mtwmapi.PoiOpenLevelHaveRest, mtwmapi.PoiStatusOffline //mtwmapi.PoiStatusOffline
	} else if status == model.StoreStatusHaveRest || status == model.StoreStatusClosed {
		return mtwmapi.PoiOpenLevelHaveRest, mtwmapi.PoiStatusOnline
	}
	return mtwmapi.PoiOpenLevelNormal, mtwmapi.PoiStatusOnline
}

func skuStatusJX2Mtwm(status int) int {
	if status == model.SkuStatusNormal {
		return mtwmapi.SellStatusOnline
	}
	return mtwmapi.SellStatusOffline
}

func (p *PurchaseHandler) UploadImg(ctx *jxcontext.Context, vendorOrgCode, imgURL string, imgData []byte, imgName string, imgType int) (imgHint string, err error) {
	poiCode4UploadImg := p.getUploadImgPoiCode()
	if poiCode4UploadImg == "" {
		return "", fmt.Errorf("找不到一个美团门店来上传图片")
	}
	if globals.EnableMtwmStoreWrite {
		if imgType > model.ImgTypeLocal {
			if imgData != nil {
				imgHint, err = api.MtwmAPI.ImageUpload(poiCode4UploadImg, imgName, imgData)
			} else {
				imgHint, err = api.MtwmAPI.ImageUploadByURL(poiCode4UploadImg, imgName, imgURL)
			}
		}
	} else {
		imgHint = utils.GetUpperUUID()
	}
	return imgHint, err
}

func getStoreIDFromList(storeIDs []string) (poiCode string) {
	if len(storeIDs) > 0 {
		poiCode = storeIDs[0]
	}
	return poiCode
}

func (p *PurchaseHandler) getUploadImgPoiCode() (poiCode string) {
	var storeIDs []string
	p.locker.RLock()
	storeIDs = p.storeIDs
	p.locker.RUnlock()
	if len(storeIDs) > 0 {
		return getStoreIDFromList(storeIDs)
	}

	p.locker.Lock()
	storeIDs = p.storeIDs
	if len(storeIDs) > 0 {
		p.locker.Unlock()
		return getStoreIDFromList(storeIDs)
	}

	defer p.locker.Unlock()
	storeIDs, err := api.MtwmAPI.PoiGetIDs()
	if err == nil {
		if len(storeIDs) > 0 {
			p.storeIDs = storeIDs
			poiCode = getStoreIDFromList(storeIDs)
		} else {
			// p.storeIDs = []string{""}
		}
	}
	return poiCode
}

func GetAPI(appOrgCode string, storeID int, vendorStoreID string) (apiObj *mtwmapi.API) {
	if appOrgCode == "" {
		globals.SugarLogger.Debugf("getAPI appOrgCode is empty")
	}
	apiObj = partner.CurAPIManager.GetAPI(model.VendorIDMTWM, appOrgCode).(*mtwmapi.API)
	if appOrgCode == globals.Mtwm2Code {
		var storeDetail *dao.StoreDetail
		if storeID != 0 {
			storeDetail, _ = dao.GetStoreDetail(dao.GetDB(), storeID, model.VendorIDMTWM, appOrgCode)
		} else if vendorStoreID != "" {
			storeDetail, _ = dao.GetStoreDetailByVendorStoreID(dao.GetDB(), vendorStoreID, model.VendorIDMTWM, appOrgCode)
		}
		if storeDetail != nil {
			apiObj.SetToken(storeDetail.MtwmToken)
		}
	}
	return apiObj
}

func getAPI(appOrgCode string, storeID int, vendorStoreID string) (apiObj *mtwmapi.API) {
	if appOrgCode == "" {
		globals.SugarLogger.Debugf("getAPI appOrgCode is empty")
	}
	apiObj = partner.CurAPIManager.GetAPI(model.VendorIDMTWM, appOrgCode).(*mtwmapi.API)
	if appOrgCode == globals.Mtwm2Code {
		var storeDetail *dao.StoreDetail
		if storeID != 0 {
			storeDetail, _ = dao.GetStoreDetail(dao.GetDB(), storeID, model.VendorIDMTWM, appOrgCode)
		} else if vendorStoreID != "" {
			storeDetail, _ = dao.GetStoreDetailByVendorStoreID(dao.GetDB(), vendorStoreID, model.VendorIDMTWM, appOrgCode)
		}
		if storeDetail != nil {
			apiObj.SetToken(storeDetail.MtwmToken)
		}
	}
	return apiObj
}

func getAPIWithoutToken(appOrgCode string) (apiObj *mtwmapi.API) {
	if appOrgCode == "" {
		globals.SugarLogger.Warnf("getAPI appOrgCode is empty")
	}
	return partner.CurAPIManager.GetAPI(model.VendorIDMTWM, appOrgCode).(*mtwmapi.API)
}
