package ebaiapi

import (
	"fmt"
	"git.rosy.net.cn/baseapi/utils"
)

const (
	SysStatusAll            = -1
	SysStatusNew            = 1
	SysStatusModifiedWait   = 3
	SysStatusFailedVerify   = 4
	SysStatusOpening        = 6
	SysStatusNewWait        = 7
	SysStatusOnlineRejected = 8
	SysStatusPassQC         = 12
)

const (
	ShopBusStatusHaveRest       = 1 // 表示休息中
	ShopBusStatusCanBooking     = 2 // 表示可预订
	ShopBusStatusOpening        = 3 // 表示营业中
	ShopBusStatusSuspended      = 4 // 表示暂停营业
	ShopBusStatusBookingNextDay = 5 // 表示必须跨天预订
)

const (
	ShopCheckStatusNew             = 1 // 门店审核状态 : 新增
	ShopCheckStatusWaitCheck       = 2 // 门店审核状态 : 待审核
	ShopCheckStatusGoLiveFail      = 3 // 门店审核状态 : 上线驳回
	ShopCheckStatusCheckSuccess    = 4 // 门店审核状态 : 审核通过
	ShopCheckStatusUpdateWaitCheck = 5 // 门店审核状态 : 修改待审核
	ShopCheckStatusCheckFail       = 6 // 门店审核状态 : 审核驳回
)

const (
	PlatformFlagElm   = "1"
	PlatformFlagBaidu = "2"
)

const (
	KeyShopID      = "shop_id"
	KeyBaiduShopID = "baidu_shop_id"
	KeySupplierID  = "supplier_id"

	KeyActivityID = "activity_id"

	KeyCustomSkuID = "custom_sku_id"
	KeySkuID       = "sku_id"
	KeyUPC         = "upc"
	KeyCategoryID  = "category_id"

	KeyName  = "name"
	KeyPhone = "phone"
)

const (
	CoordTypeBaidu    = "bdll"
	CoordTypeAutonavi = "amap"
)

// https://open-be.ele.me/dev/api/doc/v3/#api-Shop-shop_get
const (
	DeliveryTypeElmNone           = 0  // 暂无
	DeliveryTypeElmXingHuoTrial   = 1  // 星火计划(试用)
	DeliveryTypeElmXingHuo        = 4  // 星火计划
	DeliveryTypeElmFengNiaoZS     = 5  // 蜂鸟专送
	DeliveryTypeElmFengNiaoZSKA   = 6  // 蜂鸟专送,KA
	DeliveryTypeElmFengNiaoKS     = 9  // 蜂鸟快送
	DeliveryTypeElmXingHuoZBTrial = 10 // 星火众包(试用)
	DeliveryTypeElmXingHuoZB      = 11 // 星火众包
	DeliveryTypeElmNewRetail      = 12 // 新零售
	DeliveryTypeElmEBase          = 13 // e基础
	DeliveryTypeElmEPeiSong       = 14 // e配送
	DeliveryTypeElmFengNiaoHybrid = 15 // 蜂鸟混合送
	DeliveryTypeElmFengNiaoNiubee = 16 // 蜂鸟质选
	DeliveryTypeElmXingHuoKA      = 17 // 星火计划KA
	DeliveryTypeElmXingHuoZBKA    = 18 // 星火众包KA
)

// https://open-be.ele.me/dev/api/doc/v3/#api-Order_Up-order_get
const (
	DeliveryPartyFengNiao     = 1 // 蜂鸟
	DeliveryPartyFengNiaoSelf = 2 // 蜂鸟自配送
	DeliveryPartyFengNiaoZB   = 3 // 蜂鸟众包
	DeliveryPartyFengElmZB    = 4 // 饿了么众包
	DeliveryPartyFengNiaoPS   = 5 // 蜂鸟配送
	DeliveryPartyFengElmSelf  = 6 // 饿了么自配送，商家自送？
	DeliveryPartyFullCity     = 7 // 全城送
	DeliveryPartyKuaiDiPS     = 8 // 快递配送
	DeliveryBusinessTypeZT    = 1 //自提单
)

type ShopInfo struct {
	ShopID          string `json:"shop_id"`
	BaiduShopID     int64  `json:"baidu_shop_id"`
	Name            string `json:"name"`
	Status          int    `json:"status"`
	SysStatus       int    `json:"sys_status"`
	OrderPush       int    `json:"order_push"`
	OrderStatusPush int    `json:"order_status_push"`
}

type BussinessTimeInfo struct {
	End   string `json:"end"`
	Start string `json:"start"`
}

type ShopDetail struct {
	Address        string               `json:"address"`
	BaiduShopID    int64                `json:"baidu_shop_id"`
	BookAheadTime  int                  `json:"book_ahead_time"`
	Brand          string               `json:"brand"`
	BusinessFormID string               `json:"business_form_id"`
	BusinessTime   []*BussinessTimeInfo `json:"business_time"`
	Category1      string               `json:"category1"`
	Category2      string               `json:"category2"`
	Category3      string               `json:"category3"`
	Categorys      []struct {
		Category1 string `json:"category1"`
		Category2 string `json:"category2"`
	} `json:"categorys"`
	City            string        `json:"city"`
	CoordType       string        `json:"coord_type"`
	County          string        `json:"county"`
	DeliveryParty   int           `json:"delivery_party"`
	DeliveryRegion  []interface{} `json:"delivery_region"`
	DeliveryType    string        `json:"delivery_type"`
	InvoiceSupport  string        `json:"invoice_support"`
	IvrPhone        string        `json:"ivr_phone"`
	Latitude        float64       `json:"latitude"`
	Longitude       float64       `json:"longitude"`
	MinOrderPrice   string        `json:"min_order_price"`
	Name            string        `json:"name"`
	OrderPush       int           `json:"order_push"`
	OrderStatusPush int           `json:"order_status_push"`
	PackageBoxPrice int           `json:"package_box_price"`
	Phone           string        `json:"phone"`
	PickTime        string        `json:"pick_time"`
	Province        string        `json:"province"`
	ServicePhone    string        `json:"service_phone"`
	ServicePhones   []string      `json:"service_phones"`
	ShopID          string        `json:"shop_id"`
	ShopLogo        string        `json:"shop_logo"`
	Status          string        `json:"status"`
	SupplierID      int64         `json:"supplier_id"`
	SupplierName    string        `json:"supplier_name"`
}

func (a *API) genShopIDParams(shopID string, baiduShopID, supplierID int64) map[string]interface{} {
	// if shopID == "" && baiduShopID == 0 || shopID != "" && baiduShopID != 0 {
	// 	panic("shopID and baiduShopID can not all be empty or all not be empty")
	// }
	params := map[string]interface{}{}
	if shopID != "" {
		params[KeyShopID] = shopID
	} else if baiduShopID != 0 {
		params[KeyBaiduShopID] = baiduShopID
	} else if supplierID != 0 {
		params[KeySupplierID] = supplierID
	}
	return params
}

func (a *API) ShopList( /*orderPush, orderStatusPush, status, */ sysStatus int) (shopList []*ShopInfo, err error) {
	body := map[string]interface{}{}
	// if orderPush >= 0 {
	// 	body["order_push"] = orderPush
	// }
	// if orderStatusPush >= 0 {
	// 	body["order_status_push"] = orderStatusPush
	// }
	// if status >= 0 {
	// 	body["status"] = status
	// }
	if sysStatus >= 0 {
		body["sys_status"] = sysStatus
	}
	result, err := a.AccessAPI("shop.list", body)
	if err == nil {
		list := result.Data.([]interface{})
		shopList = make([]*ShopInfo, len(list))
		for k, v := range list {
			mapData := v.(map[string]interface{})
			shopList[k] = &ShopInfo{
				ShopID:      utils.Interface2String(mapData[KeyShopID]),
				BaiduShopID: utils.Str2Int64(utils.Interface2String(mapData[KeyBaiduShopID])),
			}
		}
		return shopList, nil
	}
	return nil, err
}

func (a *API) ShopCreate(params map[string]interface{}) (baiduShopID int64, err error) {
	result, err := a.AccessAPI("shop.create", params)
	if err == nil {
		if result.Data != nil {
			return utils.MustInterface2Int64(result.Data.(map[string]interface{})[KeyBaiduShopID]), nil
		} else {
			return 0, fmt.Errorf(result.Error)
		}
	}
	return 0, err
}

func (a *API) ShopGet(shopID string, baiduShopID int64) (shop map[string]interface{}, err error) {
	params := a.genShopIDParams(shopID, baiduShopID, 0)
	result, err := a.AccessAPI("shop.get", params)
	if err == nil {
		return result.Data.(map[string]interface{}), nil
	}
	return nil, err
}

func (a *API) ShopGet2(shopID string, baiduShopID int64) (shopDetail *ShopDetail, err error) {
	result, err := a.ShopGet(shopID, baiduShopID)
	if err == nil {
		err = utils.Map2StructByJson(result, &shopDetail, true)
	}
	return shopDetail, err
}

func (a *API) ShopUpdate(params map[string]interface{}) (err error) {
	_, err = a.AccessAPI("shop.update", params)
	return err
}

func (a *API) ShopBusStatusGet(shopID string, baiduShopID int64, platformFlag string) (busStatus int, err error) {
	params := a.genShopIDParams(shopID, baiduShopID, 0)
	params["platformFlag"] = platformFlag
	result, err := a.AccessAPI("shop.busstatus.get", params)
	if err == nil {
		return int(utils.MustInterface2Int64(result.Data.(map[string]interface{})["shop_busstatus"])), nil
	}
	return 0, err
}

// ShopStatusGet 获取门店审核状态
func (a *API) ShopStatusGet(shopID string, baiduShopID int64) (status int, err error) {
	params := a.genShopIDParams(shopID, baiduShopID, 0)
	result, err := a.AccessAPI("shop.status.get", params)
	if err == nil {
		return int(utils.Str2Int64(utils.Interface2String(result.Data.(map[string]interface{})["sys_status"]))), nil
	}
	return 0, err
}

// 相同值再次重复映射会出错
func (a *API) ShopIDBatchUpdate(baiduShopIDs []string, shopIDs []string) (err error) {
	//_, err = a.AccessAPI("shop.id.batchupdate", params)
	_, err = a.AccessAPI("shop.id.batchupdate", utils.Params2Map("baidu_shop_ids", baiduShopIDs, "shop_ids", shopIDs))
	if err == nil {
		return nil
	}
	return err
}

func (a *API) ShopOpen(shopID string, baiduShopID int64) (err error) {
	params := a.genShopIDParams(shopID, baiduShopID, 0)
	_, err = a.AccessAPI("shop.open", params)
	if err == nil {
		return nil
	}
	return err
}

func (a *API) ShopOffline(shopID string, baiduShopID int64) (err error) {
	params := a.genShopIDParams(shopID, baiduShopID, 0)
	_, err = a.AccessAPI("shop.offline", params)
	if err == nil {
		return nil
	}
	return err
}

func (a *API) ShopClose(shopID string, baiduShopID int64) (err error) {
	status, err := a.ShopBusStatusGet(shopID, baiduShopID, PlatformFlagElm)
	if status == ShopBusStatusOpening || status == ShopBusStatusCanBooking {
		params := a.genShopIDParams(shopID, baiduShopID, 0)
		_, err = a.AccessAPI("shop.close", params)
		return err
	}
	return err
}

func (a *API) SupplierList() (supplierInfo map[string]interface{}, err error) {
	result, err := a.AccessAPI("supplier.list", nil)
	if err == nil {
		return result.Data.(map[string]interface{}), nil
	}
	return nil, err
}

func (a *API) ShopAptitudeGet(shopID string, baiduShopID int64) (shopInfoList []map[string]interface{}, err error) {
	params := a.genShopIDParams(shopID, baiduShopID, 0)
	result, err := a.AccessAPI("shop.aptitude.get", params)
	if err == nil {
		return utils.Slice2MapSlice(result.Data.([]interface{})), nil
	}
	return nil, err
}

func (a *API) ShopAnnouncementSet(shopID string, baiduShopID int64, content string) (err error) {
	params := a.genShopIDParams(shopID, baiduShopID, 0)
	params["content"] = content
	_, err = a.AccessAPI("shop.announcement.set", params)
	if err == nil {
		return nil
	}
	return err
}

func (a *API) ShopAptitudeUpload(shopID string, baiduShopID int64, params map[string]interface{}) (err error) {
	params2 := a.genShopIDParams(shopID, baiduShopID, 0)
	_, err = a.AccessAPI("shop.aptitude.upload", utils.MergeMaps(params, params2))
	if err == nil {
		return nil
	}
	return err
}

//查询自配送物流信息
func (a *API) ShopDeliveryinfoGet(shopID string, baiduShopID int64) (shopInfoList []map[string]interface{}, err error) {
	params := a.genShopIDParams(shopID, baiduShopID, 0)
	result, err := a.AccessAPI("shop.deliveryinfo.get", params)
	if err == nil {
		return utils.Slice2MapSlice(result.Data.([]interface{})), nil
	}
	return shopInfoList, err
}
