package fnpsapi

import (
	"encoding/json"
	"fmt"
	"net/http"
	"strings"

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

const (
	StoreNotExist = "门店不存在"
	StoreExist    = "门店名称已存在"
)

const (
	// 创建状态
	ShopCreateStatusAuditRejected       = 10 // 上架审核中
	ShopCreateStatusAuditPassed         = 20 // 正常(已上架)
	ShopCreateStatusAuditCreated        = 30 // 上架审核失败
	ShopCreateStatusAuditOnline         = 40 // 已冻结
	ShopCreateStatusAuditUpdateRejected = 50 // 已下架
	// 修改状态
	ShopUpdateStatusAuditRejected = 0  // 无修改
	ShopUpdateStatusAuditPassed   = 10 // 资料修改审核中
	ShopUpdateStatusAuditCreated  = 20 // 审核通过
	ShopUpdateStatusAuditOnline   = 30 // 审核驳回
)

type CreateStoreStruct struct {
	Sign         string `json:"sign"`          //返回值签名，详见开放平台侧返回值签名算法
	Code         string `json:"code"`          //错误码，详见开放平台侧错误码映射表
	Msg          string `json:"msg"`           //错误信息
	BusinessData string `json:"business_data"` // string
	ApiCode      string `json:"api_code"`      // string
}

func (a *API) CreateStore(createStoreParam *CreateStoreBaseInfo) (result1 string, err error) {
	requestHead := a.MakeFnRequestHead()
	storeByte, err := json.Marshal(createStoreParam)
	if err != nil {
		return "", err
	}
	requestHead["business_data"] = string(storeByte)
	result, err := a.AccessAPI(ApiURL, "chainstoreCreate", http.MethodPost, requestHead)
	if err != nil {
		return "", err
	}

	createData := &CreateStoreStruct{}
	if err := utils.Map2StructByJson(result, createData, false); err != nil {
		return "", err
	}

	defaultResult := struct {
		ChainStoreId int64 `json:"chain_store_id"`
	}{}

	if err := json.Unmarshal([]byte(createData.BusinessData), &defaultResult); err != nil {
		return "", err
	}
	return utils.Int64ToStr(defaultResult.ChainStoreId), err
}

func (a *API) UpdateStore(updateStore *UpdateStoreParam) (err error) {
	requestHead := a.MakeFnRequestHead()
	storeByte, err := json.Marshal(updateStore)
	if err != nil {
		return err
	}
	requestHead["business_data"] = string(storeByte)
	_, err = a.AccessAPI(ApiURL, "chainstoreUpdate", http.MethodPost, requestHead)
	return
}

// QueryBillBalance 获取账号余额
func (a *API) QueryBillBalance() (int64, error) {
	requestHead := a.MakeFnRequestHead()
	requestHead["business_data"] = ""
	result, err := a.AccessAPI(ApiURL, "getAmount", http.MethodGet, requestHead)
	if err != nil {
		return 0, err
	}
	if result["code"].(string) != "200" {
		return 0, fmt.Errorf("%s", result["msg"])
	}
	balance := &Balance{}
	if storeData, ok := result["business_data"]; ok {
		if err := json.Unmarshal([]byte(utils.Interface2String(storeData)), balance); err != nil {
			return 0, err
		}
	} else {
		return 0, fmt.Errorf("%s", result["msg"])
	}

	return balance.BalanceAmountCent, err
}

// BalanceRecharge 余额充值
func (a *API) BalanceRecharge() (err error) {
	return fmt.Errorf("蜂鸟暂不支持充值接口")
}

func (a *API) GetStore(storeID string) (getStoreResult *GetOneStoreRespData, err error) {
	params := GetOneStoreParam{
		BaseInfo: BaseInfo{
			AccessToken: a.accessToken,
			Signature:   a.signature,
			MerchantID:  a.merchantId,
			Version:     a.version,
			AppID:       a.appID,
			Timestamp:   a.timestamp,
		},
		BusinessData: "",
	}
	// 序列化请求参数
	data, err := json.Marshal(GetOneStore{MerchantID: a.merchantId, OutShopCode: storeID})
	if err != nil {
		return nil, err
	}
	params.BusinessData = string(data)
	paramsMap := utils.Struct2FlatMap(params)

	result, err := a.AccessAPI(ApiURL, "chainstoreQuery", http.MethodPost, paramsMap)
	if err != nil {
		return nil, err
	}
	if result["code"].(string) != "200" {
		return nil, fmt.Errorf("%s", result["msg"])
	}

	fnResult := &GetOneStoreRespData{}
	if storeData, ok := result["business_data"]; ok {
		if err := json.Unmarshal([]byte(utils.Interface2String(storeData)), fnResult); err != nil {
			return nil, err
		}
	} else {
		return nil, fmt.Errorf("%s", result["msg"])
	}

	return fnResult, 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
}

const (
	FengNiaoCallbackTypeOrder    = "order"    // 订单
	FengNiaoCallbackTypeStore    = "store"    // 门店
	FengNiaoCallbackTypeAbnormal = "abnormal" // 异常
	FengNiaoCallbackTypeToken    = "token"    // token更新
)

// HttpToGuoYuanFN 订单消息推送果园
func HttpToGuoYuanFN(param map[string]interface{}, requestType string, serverType string) (*http.Response, error) {
	//cl := http.Client{}

	url := ""
	if serverType == "prod" {
		switch requestType {
		case FengNiaoCallbackTypeStore:
			url = "http://callback-jxgy.jxc4.com/fn/fnStore"
		case FengNiaoCallbackTypeOrder:
			url = "http://callback-jxgy.jxc4.com/fn/fnOrder"
		case FengNiaoCallbackTypeAbnormal:
			url = "http://callback-jxgy.jxc4.com/fn/fnAbnormal"
		case FengNiaoCallbackTypeToken:
			url = "http://callback-jxgy.jxc4.com/fn/fnToken"
		}
	} else if serverType == "jxgy" {
		switch requestType {
		case FengNiaoCallbackTypeStore:
			url = "http://callback-gblm.jxc4.com/fn/fnStore"
		case FengNiaoCallbackTypeOrder:
			url = "http://callback-gblm.jxc4.com/fn/fnOrder"
		case FengNiaoCallbackTypeAbnormal:
			url = "http://callback-gblm.jxc4.com/fn/fnAbnormal"
		case FengNiaoCallbackTypeToken:
			url = "http://callback-gblm.jxc4.com/fn/fnToken"
		}
	} else {
		return nil, nil
	}

	byteParam, _ := json.Marshal(param)
	httpReq, err := http.NewRequest(http.MethodPost, url, strings.NewReader(string(byteParam)))
	if err != nil {
		return nil, err
	}
	httpReq.Header.Add("content-type", "application/json")

	httpRes, err := http.DefaultClient.Do(httpReq)
	defer httpRes.Body.Close()
	if err != nil {
		return nil, err
	}
	return httpRes, err
}

// HttpToPetFN 订单消息推送宠物
//func HttpToPetFN(param map[string]interface{}, requestType string) (*http.Response, error) {
//	var paramData []byte
//	var err error
//	paramData, err = json.Marshal(param)
//	if err != nil {
//		return nil, err
//	}
//	body := strings.NewReader(string(paramData))
//	url := ""
//	switch requestType {
//	case FengNiaoCallbackTypeStore:
//		url = "http://callback-gblm.jxc4.com/fn/fnStore"
//	case FengNiaoCallbackTypeOrder:
//		url = "http://callback-gblm.jxc4.com/fn/fnOrder"
//	case FengNiaoCallbackTypeAbnormal:
//		url = "http://callback-gblm.jxc4.com/fn/fnAbnormal"
//	case FengNiaoCallbackTypeToken:
//		url = "http://callback-gblm.jxc4.com/fn/fnToken"
//	}
//	httpReq, err := http.NewRequest(http.MethodPost, url, body)
//	if err != nil {
//		return nil, err
//	}
//
//	httpReq.Header.Set("Content-Type", "application/json")
//
//	httpRes, err := http.DefaultClient.Do(httpReq)
//	return httpRes, err
//}
