package jdshopapi

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

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

type CreateEntityStoreParam struct {
	Name        string `json:"name"`        //是		门店名称
	AddCode     int    `json:"addCode"`     //是		门店三级标准地址编码(京东)
	AddCodeName string `json:"addCodeName"` //否		门店三级标准地址名称(京东)
	AddName     string `json:"addName"`     //是		标准地址加扩展地址以@！分隔 必填 例：北京大兴区亦庄经济开发区@!京东大厦
	Coordinate  string `json:"coordinate"`  //是		门店坐标 纬度在前，经度在后 例：39.786683,116.563075
	Phone       string `json:"phone"`       //是		门店电话
	// Item         []int  `json:"item"`         //否		门店组ID
	CustomerID   string `json:"customerId"`             //否		商家门店Id，商家维度不可重复
	CategoryName string `json:"categoryName,omitempty"` //否		门店扩展属性类目名称固定填为：popmendianSelfdelivery
	ExtendJSON   string `json:"extendJson"`             //是		扩展属性JSON如：{name1：'value1',name2:'value2'},营业时间必传固定json格式：{\'businessBeginTime\':\'09:00\',\'businessEndTime\':\'22:00\'}' ，可将中间的时间变更
	ImageFile    string `json:"imageFile"`              //否		门店图片,图片二进制文件流，允许png、jpg、gif、jpeg、bmp图片格式，1M以内。
}

type UpdateEntityStoreParam struct {
	StoreID     int    `json:"storeId"`               //门店ID(京东)
	Name        string `json:"name,omitempty"`        //是		门店名称
	AddCode     int    `json:"addCode,omitempty"`     //是		门店三级标准地址编码(京东)
	AddCodeName string `json:"addCodeName,omitempty"` //否		门店三级标准地址名称(京东)
	AddName     string `json:"addName,omitempty"`     //是		标准地址加扩展地址以@！分隔 必填 例：北京大兴区亦庄经济开发区@!京东大厦
	Coordinate  string `json:"coordinate,omitempty"`  //是		门店坐标 纬度在前，经度在后 例：39.786683,116.563075
	Phone       string `json:"phone,omitempty"`       //是		门店电话
	ExtendJSON  string `json:"extendJson,omitempty"`  //是		扩展属性JSON如：{name1：'value1',name2:'value2'},营业时间必传固定json格式：{\'businessBeginTime\':\'09:00\',\'businessEndTime\':\'22:00\'}' ，可将中间的时间变更
	ImageFile   string `json:"imageFile,omitempty"`   //否		门店图片,图片二进制文件流，允许png、jpg、gif、jpeg、bmp图片格式，1M以内。
	CustomerID  string `json:"customerId,omitempty"`  //否		商家门店Id，商家维度不可重复
	CategoryID2 int    `json:"categoryId2,omitempty"`
}

type GetAddressCodeResult struct {
	ParentID int    `json:"parentId"`
	Level    int    `json:"level"`
	AreaName string `json:"areaName"`
	Status   int    `json:"status"`
	AreaID   int    `json:"areaId"`
}

type QueryEntityStoreResult struct {
	VenderID      int64  `json:"venderId"`
	StoreID       int64  `json:"storeId"`
	StoreName     string `json:"storeName"`
	Address       string `json:"address"`
	FullAddress   string `json:"fullAddress"`
	Phone         string `json:"phone"`
	AddrCode      int    `json:"addrCode"`
	Status        int    `json:"status"`
	Coordinate    string `json:"coordinate"`
	ExtendValue   string `json:"extendValue"`
	ExStoreID     string `json:"exStoreId"`
	AuditStatus   int    `json:"auditStatus"`
	StoreStatus   string `json:"storeStatus"`
	OperateStatus string `json:"operateStatus"`
}

//创建门店
//https://open.jd.com/home/home#/doc/api?apiCateId=351&apiId=2224&apiName=jingdong.createEntityStore
func (a *API) CreateEntityStore(createEntityStoreParam *CreateEntityStoreParam) (vendorStoreID string, err error) {
	result, err := a.AccessAPI("jingdong.createEntityStore", prodURL, utils.Struct2FlatMap(createEntityStoreParam))
	if err == nil {
		if !result["jingdong_createEntityStore_responce"].(map[string]interface{})["createentitystore_result"].(map[string]interface{})["success"].(bool) {
			return vendorStoreID, fmt.Errorf(result["jingdong_createEntityStore_responce"].(map[string]interface{})["createentitystore_result"].(map[string]interface{})["message"].(string))
		}
		return result["jingdong_createEntityStore_responce"].(map[string]interface{})["createentitystore_result"].(map[string]interface{})["result"].(map[string]interface{})["name"].(string), err
	}
	return vendorStoreID, err
}

//修改门店
//https://open.jd.com/home/home#/doc/api?apiCateId=55&apiId=2221&apiName=jingdong.updateEntityStore
func (a *API) UpdateEntityStore(updateEntityStoreParam *UpdateEntityStoreParam) (err error) {
	result, err := a.AccessAPI("jingdong.updateEntityStore", prodURL, utils.Struct2FlatMap(updateEntityStoreParam))
	if err == nil {
		if !result["jingdong_updateEntityStore_responce"].(map[string]interface{})["updateentitystore_result"].(map[string]interface{})["success"].(bool) {
			return fmt.Errorf(result["jingdong_updateEntityStore_responce"].(map[string]interface{})["updateentitystore_result"].(map[string]interface{})["message"].(string))
		}
	}
	return err
}

//删除门店
//https://open.jd.com/home/home#/doc/api?apiCateId=55&apiId=2222&apiName=jingdong.deleteStoresById
func (a *API) DeleteStoresByID(storeId int64) (err error) {
	_, err = a.AccessAPI("jingdong.deleteStoresById", prodURL, map[string]interface{}{
		"storeId": storeId,
	})
	return err
}

//获取省地址信息et
//https://jos.jd.com/api/detail.htm?apiName=jingdong.areas.province.get&id=1011
func (a *API) GetProvince() (getAddressCodeResult []*GetAddressCodeResult, err error) {
	result, err := a.AccessAPI("jingdong.areas.province.get", prodURL, nil)
	if err == nil {
		utils.Map2StructByJson(result["jingdong_areas_province_get_responce"].(map[string]interface{})["baseAreaServiceResponse"].(map[string]interface{})["data"], &getAddressCodeResult, false)
	}
	return getAddressCodeResult, err
}

//获取市地址信息et
//https://jos.jd.com/api/detail.htm?apiName=jingdong.areas.city.get&id=1014
func (a *API) GetCity(parentID int) (getAddressCodeResult []*GetAddressCodeResult, err error) {
	result, err := a.AccessAPI("jingdong.areas.city.get", prodURL, map[string]interface{}{
		"parent_id": parentID,
	})
	if err == nil {
		utils.Map2StructByJson(result["jingdong_areas_city_get_responce"].(map[string]interface{})["baseAreaServiceResponse"].(map[string]interface{})["data"], &getAddressCodeResult, false)
	}
	return getAddressCodeResult, err
}

//获取区地址信息et
//https://jos.jd.com/api/detail.htm?apiName=jingdong.areas.county.get&id=1012
func (a *API) GetCounty(parentID int) (getAddressCodeResult []*GetAddressCodeResult, err error) {
	result, err := a.AccessAPI("jingdong.areas.county.get", prodURL, map[string]interface{}{
		"parent_id": parentID,
	})
	if err == nil {
		utils.Map2StructByJson(result["jingdong_areas_county_get_responce"].(map[string]interface{})["baseAreaServiceResponse"].(map[string]interface{})["data"], &getAddressCodeResult, false)
	}
	return getAddressCodeResult, err
}

type FindSkuSiteStockResult struct {
	VenderSource    string `json:"venderSource"`
	OrderBookingNum int    `json:"orderBookingNum"`
	SiteID          int    `json:"siteId"`
	StockNum        int    `json:"stockNum"`
	AppBookingNum   int    `json:"appBookingNum"`
	SkuID           int64  `json:"skuId"`
	CanUsedNum      int    `json:"canUsedNum"`
}

//查询门店库存
//https://open.jd.com/home/home#/doc/api?apiCateId=48&apiId=2983&apiName=jingdong.stock.read.findSkuSiteStock
func (a *API) FindSkuSiteStock(siteId int, skuId int64) (findSkuSiteStockResult *FindSkuSiteStockResult, err error) {
	result, err := a.AccessAPI("jingdong.stock.read.findSkuSiteStock", prodURL, map[string]interface{}{
		"siteId":       siteId,
		"skuId":        skuId,
		"venderSource": 4,
	})
	if err == nil {
		utils.Map2StructByJson(result["jingdong_stock_read_findSkuSiteStock_responce"].(map[string]interface{})["app_params"], &findSkuSiteStockResult, false)
	}
	return findSkuSiteStockResult, err
}

//设置门店sku库存
//https://open.jd.com/home/home#/doc/api?apiCateId=48&apiId=2980&apiName=jingdong.stock.write.updateSkuSiteStock
//siteId 门店ID，venderSource 固定传4
func (a *API) UpdateSkuSiteStock(skuId int64, stockNum, siteId int) (err error) {
	_, err = a.AccessAPI("jingdong.stock.write.updateSkuSiteStock", prodURL, map[string]interface{}{
		"skuId":        skuId,
		"stockNum":     stockNum,
		"siteId":       siteId,
		"venderSource": 4,
	})
	return err
}

//获取门店信息
//https://open.jd.com/home/home#/doc/api?apiCateId=351&apiId=2223&apiName=jingdong.queryEntityStore
func (a *API) QueryEntityStore(storeId int64) (queryEntityStoreResult *QueryEntityStoreResult, err error) {
	result, err := a.AccessAPI("jingdong.queryEntityStore", prodURL, map[string]interface{}{
		"storeId": storeId,
	})
	if err == nil {
		data := result["jingdong_queryEntityStore_responce"].(map[string]interface{})["queryentitystore_result"].(map[string]interface{})["jsonResult"].(string)
		data = strings.ReplaceAll(data, "[", "")
		data = strings.ReplaceAll(data, "]", "")
		err = json.Unmarshal([]byte(data), &queryEntityStoreResult)
		// utils.Map2StructByJson(data, &queryEntityStoreResult, false)
	}
	return queryEntityStoreResult, err
}

//获取门店信息2
//https://open.jd.com/home/home#/doc/api?apiCateId=351&apiId=4972&apiName=jingdong.findStoreInfoByExtStoreId
func (a *API) FindStoreInfoByExtStoreId(storeID int) (queryEntityStoreResult *QueryEntityStoreResult, err error) {
	_, err = a.AccessAPI("jingdong.findStoreInfoByExtStoreId", prodURL, map[string]interface{}{
		"extStoreId": storeID,
	})

	return queryEntityStoreResult, err
}

//更新门店状态
//https://open.jd.com/home/home#/doc/api?apiCateId=351&apiId=6418&apiName=jingdong.updateStoreStatus
//	停启状态 1.启用，2.停用
func (a *API) UpdateStoreStatusAPI(storeID, status int) (err error) {
	_, err = a.AccessAPI("jingdong.updateStoreStatus", prodURL, map[string]interface{}{
		"storeStatus": status,
		"id":          storeID,
	})
	return err
}
