package dadaapi

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

const (
	BusinessTypeSnack          = 1
	BusinessTypeDrink          = 2
	BusinessTypeFlower         = 3
	BusinessTypePrintTicket    = 8
	BusinessTypeConvStore      = 9
	BusinessTypeFruitVegetable = 13
	BusinessTypeCityEComm      = 19
	BusinessTypeMedicine       = 20
	BusinessTypeCake           = 21
	BusinessTypeWine           = 24
	BusinessTypeSmallware      = 25
	BusinessTypeClothing       = 26
	BusinessTypeCarPart        = 27
	BusinessTypeDigital        = 28
	BusinessTypeCray           = 29
	BusinessTypeOther          = -5
)

const (
	ShopStatusOffline = 0 // -门店下线
	ShopStatusOnline  = 1 // -门店激活
)

type ShopInfo struct {
	StationName    string  `json:"station_name,omitempty"`
	Business       int     `json:"business,omitempty"`
	CityName       string  `json:"city_name,omitempty"`
	AreaName       string  `json:"area_name,omitempty"`
	StationAddress string  `json:"station_address,omitempty"`
	Lng            float64 `json:"lng,omitempty"`
	Lat            float64 `json:"lat,omitempty"`
	ContactName    string  `json:"contact_name,omitempty"`
	Phone          string  `json:"phone,omitempty"`

	OriginShopID string `json:"origin_shop_id,omitempty"`
	IDCard       string `json:"id_card,omitempty"`
	UserName     string `json:"username,omitempty"`
	Password     string `json:"password,omitempty"`

	NewShopID string `json:"new_shop_id,omitempty"` // 修改用
	Status    int    `json:"status"`                // 修改用，0是有效值
}

type AddShopFailedInfo struct {
	Code     int    `json:"code"`
	ShopNo   string `json:"shopNo"`
	Msg      string `json:"msg"`
	ShopName string `json:"shopName"`
}

type AddShopSuccessInfo struct {
	AreaName       string  `json:"areaName"`
	Business       int     `json:"business"`
	CityName       string  `json:"cityName"`
	ContactName    string  `json:"contactName"`
	Lat            float64 `json:"lat"`
	Lng            float64 `json:"lng"`
	OriginShopID   string  `json:"originShopId"`
	Phone          string  `json:"phone"`
	StationAddress string  `json:"stationAddress"`
	StationName    string  `json:"stationName"`
}

type AddShopResult struct {
	Success     int                   `json:"success"`
	SuccessList []*AddShopSuccessInfo `json:"successList"`
	FailedList  []*AddShopFailedInfo  `json:"failedList"`
}

func (a *API) ShopDetail(originShopID string) (shopDetail *ShopInfo, err error) {
	params := map[string]interface{}{
		"origin_shop_id": originShopID,
	}
	result, err := a.AccessAPI("api/shop/detail", params)
	if err == nil {
		err = utils.Map2StructByJson(result.Result, &shopDetail, false)
	}
	return shopDetail, err
}

func (a *API) ShopAdd(shopInfo *ShopInfo) (outOriginShopID string, err error) {
	addResult, err := a.BatchShopAdd([]*ShopInfo{shopInfo})
	if addResult != nil && len(addResult.FailedList) == 1 {
		return "", utils.NewErrorIntCode(addResult.FailedList[0].Msg, int(utils.MustInterface2Int64(addResult.FailedList[0].Code)))
	} else if err != nil {
		return "", err
	}
	return addResult.SuccessList[0].OriginShopID, nil
}

func (a *API) BatchShopAdd(shopInfoList []*ShopInfo) (addResult *AddShopResult, err error) {
	mapList := make([]map[string]interface{}, len(shopInfoList))
	for k, v := range shopInfoList {
		mapList[k] = utils.Struct2MapByJson(v)
		delete(mapList[k], "status") // 创建时没有status参数
	}
	result, err := a.AccessAPI("api/shop/add", mapList)
	err2 := utils.Map2StructByJson(result.Result, &addResult, false)
	if err == nil {
		err = err2
	}
	return addResult, err
}

func (a *API) ShopUpdate(shopInfo *ShopInfo) (err error) {
	_, err = a.AccessAPI("api/shop/update", shopInfo)
	return err
}

// QueryBillBalance 查询达达账户余额
func (a *API) QueryBillBalance() (balance int64, err error) {
	params := map[string]interface{}{
		"category": 3,
	}
	result, err := a.AccessAPI("api/balance/query", params)
	if err != nil {
		return 0, err
	}

	if result.Code != 0 {
		return 0, fmt.Errorf(result.Msg)
	}
	return utils.Float64TwoInt64(utils.MustInterface2Float64(result.Result.(map[string]interface{})["deliverBalance"]) * 100), err
}

func (a *API) BalanceRecharge(param *RechargeParam) (string, error) {
	params := utils.Struct2MapByJson(param)
	result, err := a.AccessAPI("api/recharge", params)
	if err != nil {
		return "", err
	}

	if result.Code != 0 {
		return "", fmt.Errorf(result.Msg)
	}
	return result.Result.(string), err
}

type RechargeParam struct {
	Amount    float64 `json:"amount"`     // 充值金额,元
	Category  string  `json:"category"`   // 生成链接适应场景（category有二种类型值：PC、H5）
	NotifyUrl string  `json:"notify_url"` // 支付成功后跳转的页面（支付宝在支付成功后可以跳转到某个指定的页面，微信支付不支持）
}
