package fnpsapi

import (
	"fmt"
	"strings"

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

const (
	StoreNotExist = "门店信息不存在"
	StoreExist    = "该门店已存在"
)

type CreateStoreParam struct {
	ChainStoreCode string `json:"chain_store_code,omitempty"`
	ChainStoreName string `json:"chain_store_name,omitempty"`
	ChainStoreType int    `json:"chain_store_type,omitempty"`
	MerchantCode   string `json:"merchant_code,omitempty"`
	ContactPhone   string `json:"contact_phone,omitempty"`
	Address        string `json:"address,omitempty"`
	PositionSource int    `json:"position_source,omitempty"`
	Longitude      string `json:"longitude,omitempty"`
	Latitude       string `json:"latitude,omitempty"`
	ServiceCode    string `json:"service_code,omitempty"`
}

func (a *API) CreateStore(createStoreParam *CreateStoreParam) (err error) {
	createStoreParam.ServiceCode = "1"
	params := utils.Struct2FlatMap(createStoreParam)
	_, err = a.AccessAPI("v2/chain_store", URL, params, true)
	return err
}

type GetStoreResult struct {
	ChainStoreCode string `json:"chain_store_code"`
	ChainStoreName string `json:"chain_store_name"`
	Address        string `json:"address"`
	Latitude       string `json:"latitude"`
	Longitude      string `json:"longitude"`
	PositionSource int    `json:"position_source"`
	City           string `json:"city"`
	ContactPhone   string `json:"contact_phone"`
	ServiceCode    string `json:"service_code"`
	Status         int    `json:"status"` //1关店，2开店
}

func (a *API) GetStore(storeID string) (getStoreResult *GetStoreResult, err error) {
	result, err := a.AccessAPI("v2/chain_store/query", URL, map[string]interface{}{
		"chain_store_code": []string{storeID},
	}, true)
	if err == nil {
		if data, ok := result["data"].([]interface{}); ok {
			utils.Map2StructByJson(data[0], &getStoreResult, false)
		} else {
			err = fmt.Errorf(result["msg"].(string))
		}
	}
	return getStoreResult, err
}

func IsErrShopNotExist(err error) bool {
	if err != nil {
		if strings.Contains(err.Error(), StoreNotExist) {
			return true
		}
	}
	return false
}

func IsErrShopExist(err error) bool {
	if err != nil {
		if strings.Contains(err.Error(), StoreExist) {
			return true
		}
	}
	return false
}

func (a *API) UpdateStore(createStoreParam *CreateStoreParam) (err error) {
	params := utils.Struct2FlatMap(createStoreParam)
	_, err = a.AccessAPI("v2/chain_store/update", URL, params, true)
	return err
}
