package showapi

import (
	"fmt"
	"math"
	"regexp"
	"strings"

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

const (
	RetCodeFailed  = -1
	RetCodeSuccess = 0
)

type ProductInfo struct {
	OriginalName string   `json:"originalName"`
	OriginalSpec string   `json:"originalSpec"`
	Name         string   `json:"name"`
	Img          string   `json:"img"`
	SpecQuality  int      `json:"specQuality"`
	SpecUnit     string   `json:"specUnit"`
	Unit         string   `json:"unit"`
	Weight       float32  `json:"weight"`
	Price        int      `json:"price"`
	Categories   []string `json:"categories"`
	ManName      string   `json:"manName"` // 生产商
	BrandName    string   `json:"brandName"`
}

var (
	specPat     *regexp.Regexp
	specUnitMap = map[string]string{
		"克":  "g",
		"千克": "kg",
		"升":  "L",
		"毫升": "ml",
	}
)

func init() {
	specPat = regexp.MustCompile(`(\d+)([^\/]+)(?:\/(.+))?`)
}

func SplitProductSpec(spec string) (specQuality int, specUnit, Unit string) {
	searchResult := specPat.FindStringSubmatch(spec)
	// baseapi.SugarLogger.Debug(utils.Format4Output(searchResult, false))
	if len(searchResult) == 4 {
		return int(utils.Str2Int64WithDefault(searchResult[1], 0)), searchResult[2], searchResult[3]
	}
	return 0, "", ""
}

func CalculateWeight(specQuality int, specUnit string) (weight float32) {
	weight = float32(specQuality)
	if specUnit == "g" || specUnit == "ml" {
		weight /= 1000
	}
	return weight
}

func (a *API) GetProductInfoByBarCode(barCode string) (product *ProductInfo, err error) {
	res := ShowapiRequest("http://route.showapi.com/66-22", a.appID, a.appSecret)
	res.AddTextPara("code", barCode)
	result, err := res.Post()
	if err != nil {
		return nil, err
	}
	var jsonResult map[string]interface{}
	if err = utils.UnmarshalUseNumber([]byte(result), &jsonResult); err != nil {
		return nil, err
	}
	showApiResCode := int(utils.MustInterface2Int64(jsonResult["showapi_res_code"]))
	if showApiResCode != 0 {
		return nil, utils.NewErrorIntCode(utils.Interface2String(jsonResult["showapi_res_error"]), showApiResCode)
	}
	// baseapi.SugarLogger.Debug(utils.Format4Output(jsonResult, false))

	showapiResBody := jsonResult["showapi_res_body"].(map[string]interface{})
	retCode := int(utils.ForceInterface2Int64(showapiResBody["ret_code"]))
	if retCode != RetCodeSuccess {
		return nil, utils.NewErrorIntCode(utils.Interface2String(showapiResBody["remark"]), retCode)
	}
	product = &ProductInfo{
		OriginalName: showapiResBody["goodsName"].(string),
		OriginalSpec: showapiResBody["spec"].(string),
		Img:          utils.Interface2String(showapiResBody["img"]),
		Price:        int(math.Round(utils.Str2Float64WithDefault(utils.Interface2String(showapiResBody["price"]), 0))),
		Categories:   strings.Split(utils.Interface2String(showapiResBody["goodsType"]), ">>"),
		ManName:      showapiResBody["manuName"].(string),
		BrandName:    showapiResBody["trademark"].(string),
	}
	product.SpecQuality, product.SpecUnit, product.Unit = SplitProductSpec(product.OriginalSpec)
	product.Name = utils.TrimBlankChar(strings.Replace(product.OriginalName, fmt.Sprintf("%d%s", product.SpecQuality, product.SpecUnit), "", -1))
	product.Weight = CalculateWeight(product.SpecQuality, product.SpecUnit)
	return product, err
}
