package jdshopapi

import (
	"bytes"
	"encoding/json"
	"fmt"
	"math/rand"
	"mime/multipart"
	"net/http"
	"net/textproto"
	"regexp"
	"strings"
	"time"

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

var (
	regexpOrderDetailTable     = regexp.MustCompile(`<table id="receiveData">([\s\S]*?)</table>`)
	regexpOrderDetailTd        = regexp.MustCompile(`<td colspan="2">(.*?)</td>`)
	regexpOrderDetailMobile    = regexp.MustCompile(`<span id="mobile">(.*?)</span>`)
	regexpOrderDetailDay       = regexp.MustCompile(`<td class="pubwhite">期望送货日期:</td>[\s\S]*?<td colspan="2">(.*?)</td>`)
	regexpOrderDetailDay2      = regexp.MustCompile(`<td class="pubwhite">配送日期:</td>[\s\S]*?<td colspan="2">(.*?)</td>`)
	regexpOrderDetailPay       = regexp.MustCompile(`<td class="pubwhite">应支付金额:</td>[\s\S]*?<td>[\s\S]*?￥(.*?[\s\S]*?)</td>`)
	regexpOrderDetailMobileKey = regexp.MustCompile(`accesskey="(.*?)"`)
)

const (
	JdsOrderDeliverTypeStore = 1274
	JdsOrderDeleverTypeSelf  = 332098
	letterBytes              = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
)

const (
	OrderStatusFinishedPickup = 51 //待配送
	OrderStatusNew            = 50 //待接单，已支付
	OrderStatusCancelm2       = -2 //(删除)待配送

	categoryURL = "https://seller.shop.jd.com/vendershop/vendershop_doShopCategory.action"
)

func (a *API) AccessStorePage(fullURL string, bizParams map[string]interface{}, isPost bool) (retVal map[string]interface{}, err error) {
	if a.GetCookieCount() == 0 {
		return nil, fmt.Errorf("需要设置Store Cookie才能使用此方法")
	}
	err = platformapi.AccessPlatformAPIWithRetry(a.client,
		func() *http.Request {
			var request *http.Request
			if isPost {
				request, _ = http.NewRequest(http.MethodPost, fullURL, strings.NewReader(utils.Map2URLValues(bizParams).Encode()))
				request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
				if fullURL == categoryURL {
					request.Header.Set("origin", "https://seller.shop.jd.com")
					request.Header.Set("referer", "https://seller.shop.jd.com/vendershop/vendershop_shopCategory.action")
					request.Header.Set("user-agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36")
					request.Header.Set("accept", "application/json, text/javascript, */*; q=0.01")
					request.Header.Set("accept-encoding", "gzip, deflate, br")
					request.Header.Set("accept-language", "zh-CN,zh;q=0.9")
					request.Header.Set("X-Requested-With", "XMLHttpRequest")
					request.Header.Set("Host", "seller.shop.jd.com")
				}
			} else {
				request, _ = http.NewRequest(http.MethodGet, utils.GenerateGetURL(fullURL, "", bizParams), nil)
			}
			a.FillRequestCookies(request)
			return request
		},
		a.config,
		func(response *http.Response, bodyStr string, jsonResult1 map[string]interface{}) (errLevel string, err error) {
			if jsonResult1 == nil {
				return platformapi.ErrLevelRecoverableErr, fmt.Errorf("mapData is nil")
			}
			if strings.Contains(bodyStr, "登录") || strings.Contains(bodyStr, "访问的内容") {
				return platformapi.ErrLevelRecoverableErr, fmt.Errorf("cookie可能过期了！")
			}
			if err == nil {
				if jsonResult1["error_response"] != nil {
					errLevel = platformapi.ErrLevelGeneralFail
					err = utils.NewErrorCode(jsonResult1["error_response"].(map[string]interface{})["zh_desc"].(string), jsonResult1["error_response"].(map[string]interface{})["code"].(string))
				}
				retVal = jsonResult1
			}
			return errLevel, err
		})
	return retVal, err
}

func (a *API) AccessStorePage2(fullURL string, bizParams map[string]interface{}, isPost bool) (retVal map[string]interface{}, err error) {
	if a.GetCookieCount() == 0 {
		return nil, fmt.Errorf("需要设置Store Cookie才能使用此方法")
	}
	data, _ := json.Marshal(bizParams)
	err = platformapi.AccessPlatformAPIWithRetry(a.client,
		func() *http.Request {
			var request *http.Request
			if isPost {
				unix := time.Now().UnixNano() / 1000000
				refer := "https://porder.shop.jd.com/order/o2o/orderlist/allOrders?t=" + utils.Int64ToStr(unix)
				request, _ = http.NewRequest(http.MethodPost, fullURL, strings.NewReader(string(data)))
				request.Header.Set("Content-Type", "application/json;charset=UTF-8")
				request.Header.Set("Accept", "application/json, text/plain, */*")
				request.Header.Set("Accept-Encoding", "gzip, deflate, br")
				request.Header.Set("Accept-Language", "zh-CN,zh;q=0.9")
				request.Header.Set("Origin", "https://porder.shop.jd.com") //ware
				request.Header.Set("Referer", refer)                       //ware.shop.jd.com/rest/storeProduct/view
				request.Header.Set("Host", "porder.shop.jd.com")
				request.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36")
			} else {
				request, _ = http.NewRequest(http.MethodGet, utils.GenerateGetURL(fullURL, "", bizParams), nil)
			}
			a.FillRequestCookies(request)
			return request
		},
		a.config,
		func(response *http.Response, bodyStr string, jsonResult1 map[string]interface{}) (errLevel string, err error) {
			if jsonResult1 == nil {
				return platformapi.ErrLevelRecoverableErr, fmt.Errorf("mapData is nil")
			}
			if strings.Contains(bodyStr, "登录") || strings.Contains(bodyStr, "访问的内容") {
				return platformapi.ErrLevelRecoverableErr, fmt.Errorf("cookie可能过期了！")
			}
			if err == nil {
				if jsonResult1["error_response"] != nil {
					errLevel = platformapi.ErrLevelGeneralFail
					err = utils.NewErrorCode(jsonResult1["error_response"].(map[string]interface{})["zh_desc"].(string), jsonResult1["error_response"].(map[string]interface{})["code"].(string))
				}
				retVal = jsonResult1
			}
			return errLevel, err
		})
	return retVal, err
}

func (a *API) AccessStorePage4(fullURL, param string, isPost bool) (retVal map[string]interface{}, err error) {
	if a.GetCookieCount() == 0 {
		return nil, fmt.Errorf("需要设置Store Cookie才能使用此方法")
	}
	err = platformapi.AccessPlatformAPIWithRetry(a.client,
		func() *http.Request {
			var request *http.Request
			if isPost {
				request, _ = http.NewRequest(http.MethodPost, fullURL, strings.NewReader(param))
				request.Header.Set("Content-Type", "application/json;charset=UTF-8")
			}
			a.FillRequestCookies(request)
			return request
		},
		a.config,
		func(response *http.Response, bodyStr string, jsonResult1 map[string]interface{}) (errLevel string, err error) {
			if jsonResult1 == nil {
				return platformapi.ErrLevelRecoverableErr, fmt.Errorf("mapData is nil")
			}
			if strings.Contains(bodyStr, "登录") || strings.Contains(bodyStr, "访问的内容") {
				return platformapi.ErrLevelRecoverableErr, fmt.Errorf("cookie可能过期了！")
			}
			if err == nil {
				if jsonResult1["error_response"] != nil {
					errLevel = platformapi.ErrLevelGeneralFail
					err = utils.NewErrorCode(jsonResult1["error_response"].(map[string]interface{})["zh_desc"].(string), jsonResult1["error_response"].(map[string]interface{})["code"].(string))
				}
				retVal = jsonResult1
			}
			return errLevel, err
		})
	return retVal, err
}

func RandStringBytes(n int) string {
	b := make([]byte, n)
	for i := range b {
		b[i] = letterBytes[rand.Intn(len(letterBytes))]
	}
	return string(b)
}

func getBoundary() (boundary string) {
	boundary = "----WebKitFormBoundary"
	boundary += RandStringBytes(16)
	return boundary
}

func (a *API) AccessStorePage3(data []byte, fileName string) (retVal map[string]interface{}, err error) {
	// 实例化multipart
	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)
	writer.SetBoundary(getBoundary())
	// 创建multipart 文件字段
	h := make(textproto.MIMEHeader)
	h.Set("Content-Disposition",
		fmt.Sprintf(`form-data; name="%s"; filename="%s"`,
			"file", fileName))
	h.Set("Content-Type", "image/jpeg")
	part, _ := writer.CreatePart(h)
	// part, _ := writer.CreateFormFile("file", "4ff17b24fdccfc37fd0847469a8039e9.jpg")
	// 写入文件数据到multipart，和读取本地文件方法的唯一区别
	_, err = part.Write(data)
	//将额外参数也写入到multipart
	_ = writer.WriteField("name", fileName)
	err = writer.Close()
	err = platformapi.AccessPlatformAPIWithRetry(a.client,
		func() *http.Request {
			request, _ := http.NewRequest(http.MethodPost, "https://o2o-stores.shop.jd.com/shop/uploadImageNew", body)
			request.Header.Set("Content-Type", writer.FormDataContentType())
			a.FillRequestCookies(request)
			return request
		},
		a.config,
		func(response *http.Response, bodyStr string, jsonResult1 map[string]interface{}) (errLevel string, err error) {
			if jsonResult1 == nil {
				return platformapi.ErrLevelRecoverableErr, fmt.Errorf("mapData is nil")
			}
			if strings.Contains(bodyStr, "登录") || strings.Contains(bodyStr, "访问的内容") {
				return platformapi.ErrLevelRecoverableErr, fmt.Errorf("cookie可能过期了！")
			}
			if err == nil {
				if jsonResult1["error_response"] != nil {
					errLevel = platformapi.ErrLevelGeneralFail
					err = utils.NewErrorCode(jsonResult1["error_response"].(map[string]interface{})["zh_desc"].(string), jsonResult1["error_response"].(map[string]interface{})["code"].(string))
					baseapi.SugarLogger.Debugf("jdeclp AccessAPI failed, jsonResult1:%s", utils.Format4Output(jsonResult1, true))
				}
				retVal = jsonResult1
			}
			return errLevel, err
		})
	return retVal, err
}

type CreateShopCategoryParam struct {
	HomeShow string `json:"homeShow"`
	ID       string `json:"id"`
	Open     string `json:"open"`
	OrderNo  string `json:"orderNo"`
	ParentID string `json:"parentId"`
	Title    string `json:"title"`
	Type     string `json:"type"`
}

//京东商城创建或修改店内分类
//https://seller.shop.jd.com/vendershop/vendershop_shopCategory.action#
func (a *API) CreateShopCategory(createShopCategoryParam []*CreateShopCategoryParam) (status int64, err error) {
	data, _ := json.Marshal(createShopCategoryParam)
	result, err := a.AccessStorePage(categoryURL, map[string]interface{}{
		"categoryJson": string(data),
	}, true)
	if err == nil {
		status = utils.Interface2Int64WithDefault(result["fakeData"], -1)
	}
	return status, err
}

//京东商城设置门店营业状态
//https://stores.shop.jd.com/stores/updateStoreStatus?storeId=24330156&storeStatus=6
func (a *API) UpdateStoreStatus(storeID, storeStatus int) (err error) {
	_, err = a.AccessStorePage("https://stores.shop.jd.com/stores/updateStoreStatus", map[string]interface{}{
		"storeId":     storeID,
		"storeStatus": storeStatus,
	}, false)
	return err
}

type NewInfoListResult struct {
	ID                 int         `json:"id"`
	VenderID           int         `json:"venderId"`
	CompanyID          interface{} `json:"companyId"`
	CompanyName        interface{} `json:"companyName"`
	StoreType          interface{} `json:"storeType"`
	Name               string      `json:"name"`
	AddCode            int         `json:"addCode"`
	AddCodeName        interface{} `json:"addCodeName"`
	AddName            string      `json:"addName"`
	AddCode1           int         `json:"addCode1"`
	AddCode2           int         `json:"addCode2"`
	AddCode4           interface{} `json:"addCode4"`
	BussinessBeginTime interface{} `json:"bussinessBeginTime"`
	BussinessEndTime   interface{} `json:"bussinessEndTime"`
	AddNameExtend      interface{} `json:"addNameExtend"`
	Coordinate         interface{} `json:"coordinate"`
	CommodityNum       int         `json:"commodityNum"`
	Status             interface{} `json:"status"`
	Created            interface{} `json:"created"`
	Modified           interface{} `json:"modified"`
	Phone              interface{} `json:"phone"`
	EncryptPhone       interface{} `json:"encryptPhone"`
	StoreGroupIds      interface{} `json:"storeGroupIds"`
	VirtualStoresIds   interface{} `json:"virtualStoresIds"`
	VirtualStoresInDB  interface{} `json:"virtualStoresInDB"`
	Address            interface{} `json:"address"`
	Account            interface{} `json:"account"`
	UserName           interface{} `json:"userName"`
	Pwd                interface{} `json:"pwd"`
	CrmPwd             interface{} `json:"crmPwd"`
	Type               interface{} `json:"type"`
	AccountIsAuth      interface{} `json:"accountIsAuth"`
	Slogan             interface{} `json:"slogan"`
	Mobilephone        interface{} `json:"mobilephone"`
	EncryptMobilephone interface{} `json:"encryptMobilephone"`
	UnboundedBizType   interface{} `json:"unboundedBizType"`
	ExStoreID          string      `json:"exStoreId"`
	ExStoreSource      interface{} `json:"exStoreSource"`
	MdImg              interface{} `json:"mdImg"`
	AccountName        interface{} `json:"accountName"`
	StoreStatus        int         `json:"storeStatus"`
	BusinessTime       interface{} `json:"businessTime"`
	IsBindingPurse     interface{} `json:"isBindingPurse"`
	GroupName          interface{} `json:"groupName"`
	SplitID            interface{} `json:"splitId"`
	BusinessID         interface{} `json:"businessId"`
	BrandID            interface{} `json:"brandId"`
	ReturnType         interface{} `json:"returnType"`
	PhoneType          interface{} `json:"phoneType"`
	AfterPhone         interface{} `json:"afterPhone"`
	DeptID             interface{} `json:"deptId"`
	Remark             interface{} `json:"remark"`
	AuditStatus        int         `json:"auditStatus"`
	CategoryID1        interface{} `json:"categoryId1"`
	CategoryID2        interface{} `json:"categoryId2"`
	CategoryName1      interface{} `json:"categoryName1"`
	CategoryName2      interface{} `json:"categoryName2"`
	ImgURL             interface{} `json:"imgUrl"`
	StoreStatusName    string      `json:"storeStatusName"`
	AuditStatusName    string      `json:"auditStatusName"`
	OperateStatus      interface{} `json:"operateStatus"`
	Pin                interface{} `json:"pin"`
}

//京东商城查询门店营业状态
//https://stores.shop.jd.com/stores/newInfoList
func (a *API) NewInfoList(storeID int64) (newInfoListResult *NewInfoListResult, err error) {
	var newInfoListResult2 []*NewInfoListResult
	result, err := a.AccessStorePage2("https://stores.shop.jd.com/stores/newInfoList", map[string]interface{}{
		"storeId":     storeID,
		"inCache":     0,
		"index":       1,
		"pageSize":    10,
		"companyName": nil,
		"exStoreId":   nil,
		"storeName":   nil,
		"storeStatus": nil,
	}, true)
	if err == nil {
		utils.Map2StructByJson(result["list"], &newInfoListResult2, false)
	}
	newInfoListResult = newInfoListResult2[0]
	return newInfoListResult, err
}

type AllOrdersParam struct {
	Current                int           `json:"current"`
	PageSize               int           `json:"pageSize"`
	SortName               string        `json:"sortName"`
	OrderID                string        `json:"orderId"`
	SkuName                string        `json:"skuName"`
	OrderCreateDateRange   []string      `json:"orderCreateDateRange"`
	OrderCompleteDateRange []interface{} `json:"orderCompleteDateRange",omitempty`
	ReceiverName           string        `json:"receiverName"`
	ReceiverTel            string        `json:"receiverTel"`
	UserPin                string        `json:"userPin"`
	SkuID                  string        `json:"skuId"`
	LogiNo                 string        `json:"logiNo"`
	PaymentType            string        `json:"paymentType"`
	OrderType              string        `json:"orderType"`
	OrderSource            string        `json:"orderSource"`
	DeliveryType           string        `json:"deliveryType"`
	StoreID                string        `json:"storeId"`
	HuoHao                 string        `json:"huoHao"`
	OrderStatusArray       []string      `json:"orderStatusArray,omitempty"`
	SelectedTabName        string        `json:"selectedTabName"`
}

type AllOrdersResult struct {
	TotalCount int `json:"totalCount"`
	Current    int `json:"current"`
	OrderList  []struct {
		XiaDanTime           interface{} `json:"xiaDanTime"`
		ModifiedTime         interface{} `json:"modifiedTime"`
		CustomsName          interface{} `json:"customsName"`
		MerchantName         interface{} `json:"merchantName"`
		CustomsModelName     interface{} `json:"customsModelName"`
		ProcessStatus        interface{} `json:"processStatus"`
		StorageAndShipStatus interface{} `json:"storageAndShipStatus"`
		ProcessStatusMsg     interface{} `json:"processStatusMsg"`
		OrderID              int64       `json:"orderId"`
		SelectedTabName      interface{} `json:"selectedTabName"`
		VenderID             int         `json:"venderId"`
		OrderCreateTime      string      `json:"orderCreateTime"`
		PaymentConfirmTime   string      `json:"paymentConfirmTime"`
		OrderCompleteTime    interface{} `json:"orderCompleteTime"`
		OrderItems           []struct {
			WareID              interface{} `json:"wareId"`
			SkuID               int64       `json:"skuId"`
			SkuName             string      `json:"skuName"`
			HuoHao              interface{} `json:"huoHao"`
			JdPrice             float64     `json:"jdPrice"`
			SkuNum              int         `json:"skuNum"`
			SkuImg              interface{} `json:"skuImg"`
			URL                 string      `json:"url"`
			ServiceName         string      `json:"serviceName"`
			Imei                interface{} `json:"imei"`
			SequenceFlag        bool        `json:"sequenceFlag"`
			SequenceInfoList    interface{} `json:"sequenceInfoList"`
			UpdateCount         interface{} `json:"updateCount"`
			CertificateFlag     bool        `json:"certificateFlag"`
			CertificateInfoList interface{} `json:"certificateInfoList"`
			MedicalInfoFlag     bool        `json:"medicalInfoFlag"`
			MedicalInfoParamVos interface{} `json:"medicalInfoParamVos"`
			UniqueCode          interface{} `json:"uniqueCode"`
			InspectReportID     interface{} `json:"inspectReportId"`
		} `json:"orderItems"`
		PaymentTypeName         string        `json:"paymentTypeName"`
		ShouldPay               float64       `json:"shouldPay"`
		Freight                 float64       `json:"freight"`
		ServiceFee              interface{}   `json:"serviceFee"`
		Commission              float64       `json:"commission"`
		CouponFlag              bool          `json:"couponFlag"`
		UserPin                 string        `json:"userPin"`
		UserRemark              string        `json:"userRemark"`
		ConsigneeInfo           interface{}   `json:"consigneeInfo"`
		LogiFlag                bool          `json:"logiFlag"`
		LogisticsInfos          []interface{} `json:"logisticsInfos"`
		StoreName               string        `json:"storeName"`
		CodDT                   interface{}   `json:"codDT"`
		ScDT                    interface{}   `json:"scDT"`
		OrderStatusStrCN        string        `json:"orderStatusStrCN"`
		OrderStatus             int           `json:"orderStatus"`
		InvalidOrderFlag        bool          `json:"invalidOrderFlag"`
		OrderType               int           `json:"orderType"`
		CustomsModel            interface{}   `json:"customsModel"`
		SalesPin                interface{}   `json:"salesPin"`
		MdbStoreID              int64         `json:"mdbStoreId"`
		SuspendType             interface{}   `json:"suspendType"`
		SuspendReason           interface{}   `json:"suspendReason"`
		SuspendReasonDesc       interface{}   `json:"suspendReasonDesc"`
		SuspendDetailReasonFlag interface{}   `json:"suspendDetailReasonFlag"`
		StoreInfo               interface{}   `json:"storeInfo"`
		IsDivShow               bool          `json:"isDivShow"`
		IsMenDianOrder          bool          `json:"isMenDianOrder"`
		IsMenDianBangOrder      bool          `json:"isMenDianBangOrder"`
		IsMenDianZiTiOrder      bool          `json:"isMenDianZiTiOrder"`
		IsPhoneOrder            bool          `json:"isPhoneOrder"`
		IsReturnOrder           bool          `json:"isReturnOrder"`
		IsPreSaleOrder          bool          `json:"isPreSaleOrder"`
		IsVenderSplitOrder      bool          `json:"isVenderSplitOrder"`
		IsAuctionOrder          bool          `json:"isAuctionOrder"`
		IsLargeAmountOrder      bool          `json:"isLargeAmountOrder"`
		IsMicroShopOrder        bool          `json:"isMicroShopOrder"`
		IsRuralPromotionOrder   bool          `json:"isRuralPromotionOrder"`
		IsHkMacaoOrder          bool          `json:"isHkMacaoOrder"`
		IsTaiWanOrder           bool          `json:"isTaiWanOrder"`
		IsOverseasOrder         bool          `json:"isOverseasOrder"`
		IsDistributionOrder     bool          `json:"isDistributionOrder"`
		IsJdDeliveryOrder       bool          `json:"isJdDeliveryOrder"`
		IsEclpOrder             bool          `json:"isEclpOrder"`
		IsYiPanHuoOrder         bool          `json:"isYiPanHuoOrder"`
		IsJingZunDaOrder        bool          `json:"isJingZunDaOrder"`
		IsBrandMall             bool          `json:"isBrandMall"`
		IsPinGou                bool          `json:"isPinGou"`
		IsYhd                   bool          `json:"isYhd"`
		IsXtl                   bool          `json:"isXtl"`
		IsSplitOrder            bool          `json:"isSplitOrder"`
		IsCloudWarehouseOrder   bool          `json:"isCloudWarehouseOrder"`
		IsTopLifeOrder          bool          `json:"isTopLifeOrder"`
		IsTuanGou               bool          `json:"isTuanGou"`
		IsDuoBaoDao             bool          `json:"isDuoBaoDao"`
		IsJingPinShi            bool          `json:"isJingPinShi"`
		BizLinkVo               struct {
			ShowModifyFee             bool `json:"showModifyFee"`
			ShowSingleOut             bool `json:"showSingleOut"`
			ShowModifyAddr            bool `json:"showModifyAddr"`
			ShowDelayDeliveryRemind   bool `json:"showDelayDeliveryRemind"`
			ShowSplitOrder            bool `json:"showSplitOrder"`
			ShowMoreLogisticsDelivery bool `json:"showMoreLogisticsDelivery"`
			ShowMergeDelivery         bool `json:"showMergeDelivery"`
			ShowInfoCheck             bool `json:"showInfoCheck"`
			ShowLivingAuth            bool `json:"showLivingAuth"`
			ShowModifyWaybill         bool `json:"showModifyWaybill"`
		} `json:"bizLinkVo"`
		IsOut                       bool          `json:"isOut"`
		IsMultiLogisticsOutShow     bool          `json:"isMultiLogisticsOutShow"`
		PaimaiOrder                 int           `json:"paimaiOrder"`
		CannotModifyProvinceAndCity bool          `json:"cannotModifyProvinceAndCity"`
		CanWaitInnerShip            bool          `json:"canWaitInnerShip"`
		ShowShangChuanHeTong        bool          `json:"showShangChuanHeTong"`
		ShowManageCertificate       bool          `json:"showManageCertificate"`
		OrderSeqFlag                bool          `json:"orderSeqFlag"`
		CustomInfoFlag              bool          `json:"customInfoFlag"`
		OrderDaYangFlag             bool          `json:"orderDaYangFlag"`
		ShowMedicalInfo             bool          `json:"showMedicalInfo"`
		Card3CFlag                  bool          `json:"card3cFlag"`
		ShowOrderPackage            bool          `json:"showOrderPackage"`
		ShowWaybill                 bool          `json:"showWaybill"`
		IsGlobalZhiYouOrder         bool          `json:"isGlobalZhiYouOrder"`
		IsGlobalBaoShuiOrder        bool          `json:"isGlobalBaoShuiOrder"`
		ManageImeiFlag              bool          `json:"manageImeiFlag"`
		SpecialViewOrder            []interface{} `json:"specialViewOrder"`
	} `json:"orderList"`
	Cluster interface{} `json:"cluster"`
}

//尝试扒订单
//https://porder.shop.jd.com/order/orderlist/allOrders
func (a *API) AllOrders(allOrdersParam *AllOrdersParam) (allOrdersResult *AllOrdersResult, err error) {
	result, err := a.AccessStorePage2("https://porder.shop.jd.com/order/orderlist", map[string]interface{}{
		"current":              allOrdersParam.Current,
		"pageSize":             allOrdersParam.PageSize,
		"selectedTabName":      "allOrders",
		"sortName":             "desc",
		"orderCreateDateRange": allOrdersParam.OrderCreateDateRange,
		//"storeId":              allOrdersParam.StoreID,
		//"orderStatusArray":     allOrdersParam.OrderStatusArray,
		"orderId": allOrdersParam.OrderID,
	}, true)

	_, err = a.AccessStorePage2("https://porder.shop.jd.com/order/orderlist", map[string]interface{}{
		"current":              allOrdersParam.Current,
		"pageSize":             allOrdersParam.PageSize,
		"selectedTabName":      "allOrders",
		"sortName":             "desc",
		"orderCreateDateRange": allOrdersParam.OrderCreateDateRange,
		//"storeId":              allOrdersParam.StoreID,
		//"orderStatusArray":     allOrdersParam.OrderStatusArray,
		//"orderId": allOrdersParam.OrderID,
	}, true)
	if err == nil {
		utils.Map2StructByJson(result, &allOrdersResult, false)
	}
	return allOrdersResult, err
}

type OrderDetailResult struct {
	ConsigneeName         string `json:"consigneeName"`
	ConsigneeAddress      string `json:"consigneeAddress"`
	ConsigneeMobile       string `json:"consigneeMobile"`
	ExpectedDeliveredTime string `json:"expectedDeliveredTime"`
	ActualPayPrice        int64  `json:"actualPayPrice"`
	MobileKey             string `json:"mobileKey"`
}

//订单详情
//https://neworder.shop.jd.com/order/orderDetail?orderId=122367441996
func (a *API) OrderDetail(orderId string) (orderDetailResult *OrderDetailResult, err error) {
	result, err := a.AccessStorePage("https://neworder.shop.jd.com/order/orderDetail", map[string]interface{}{
		"orderId": orderId,
	}, false)
	if err == nil {
		orderDetailResult = &OrderDetailResult{}
		body := result["fakeData"].(string)
		expectedDeliveredTime := regexpOrderDetailDay.FindStringSubmatch(body)
		actualPayPrice := regexpOrderDetailPay.FindStringSubmatch(body)
		consigneeTable := regexpOrderDetailTable.FindStringSubmatch(body)
		mobileKey := regexpOrderDetailMobileKey.FindStringSubmatch(body)
		if len(consigneeTable) > 0 {
			consigneeTd := regexpOrderDetailTd.FindAllStringSubmatch(consigneeTable[1], -1)
			consigneeMobiles := regexpOrderDetailMobile.FindStringSubmatch(consigneeTable[1])
			if len(consigneeTd) > 0 {
				orderDetailResult.ConsigneeName = consigneeTd[0][1]
				orderDetailResult.ConsigneeAddress = consigneeTd[1][1]
			}
			if len(consigneeMobiles) > 0 {
				orderDetailResult.ConsigneeMobile = consigneeMobiles[1]
			}
		}
		if len(expectedDeliveredTime) > 0 {
			expectedDeliveredTime := expectedDeliveredTime[1][:strings.LastIndex(expectedDeliveredTime[1], "-")] + ":00"
			if expectedDeliveredTime2, err := utils.TryStr2Time(expectedDeliveredTime); err == nil {
				expectedDeliveredTime = utils.Time2Str(expectedDeliveredTime2)
				orderDetailResult.ExpectedDeliveredTime = utils.Time2Str(utils.Str2Time(expectedDeliveredTime).Add(50 * time.Minute))
			} else {
				orderDetailResult.ExpectedDeliveredTime = ""
			}
		} else {
			expectedDeliveredTime2 := regexpOrderDetailDay2.FindStringSubmatch(body)
			if len(expectedDeliveredTime2) > 0 {
				times := strings.Split(expectedDeliveredTime2[1], ",")
				if len(times) > 1 {
					orderDetailResult.ExpectedDeliveredTime = times[0] + " " + times[1][:strings.Index(times[1], ":")] + ":50:00"
				}
			}
		}
		if len(actualPayPrice) > 0 {
			orderDetailResult.ActualPayPrice = utils.Float64TwoInt64(utils.Str2Float64(strings.TrimSpace(actualPayPrice[1])) * 100)
		}
		if len(mobileKey) > 0 {
			orderDetailResult.MobileKey = mobileKey[1]
		}
	}
	return orderDetailResult, err
}

//尝试获取订单的真实手机号
//https://neworder.shop.jd.com/order/json/phoneSensltiveInfo
func (a *API) PhoneSensltiveInfo(orderId, accessKey string) (fakeMobile string, err error) {
	result, err := a.AccessStorePage("https://neworder.shop.jd.com/order/json/phoneSensltiveInfo", map[string]interface{}{
		"orderId":    orderId,
		"accessKey":  accessKey,
		"accessType": "0",
		"token":      JdsMobileToken,
	}, true)
	if err == nil {
		if result["model"].(map[string]interface{})["mobile"] == nil {
			fakeMobile = ""
		} else {
			fakeMobile = result["model"].(map[string]interface{})["mobile"].(string)
		}
	}
	return fakeMobile, err
}

//订单的订单号转移
//https://porder.shop.jd.com/order/global/updateWaybill
func (a *API) UpdateWaybill(orderId, logiId, logiNo string) (err error) {
	var waybiilList = []map[string]interface{}{}
	param := map[string]interface{}{
		"logiId":   logiId,
		"logiNos":  []string{logiNo},
		"overseas": false,
		"logiNo":   logiNo,
	}
	waybiilList = append(waybiilList, param)
	_, err = a.AccessStorePage2("https://porder.shop.jd.com/order/global/updateWaybill", map[string]interface{}{
		"orderId":     orderId,
		"globalOrder": false,
		"waybillList": waybiilList,
	}, true)
	return err
}

//登录
// Accept: */*
// Accept-Encoding: gzip, deflate, br
// Accept-Language: zh-CN,zh;q=0.9
// Connection: keep-alive
// Content-Length: 2129
// Content-Type: application/x-www-form-urlencoded; charset=UTF-8
// Cookie: __jdu=15913386790311275342874
// Host: passport.jd.com
// Origin: https://passport.jd.com
// Referer: https://passport.jd.com/common/loginPage?from=pop_vender&regTag=2&ReturnUrl=https%3A%2F%2Fseller.shop.jd.com%2Fseller%2Fsellerinfo%2Fseller_info.action
// User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3761.400 QQBrowser/10.6.4121.400
// X-k39sGHmW-a: w9fV4=jzG=ce4jhYrOwXaIhG4oeGSZzNBFUXMdcfztckhgq_4MHU49dkqt-U_IweW=f-hl5g7PhWWUfeT4iw7a5YxNBIMIzY89pf_Zve_6wU7tK3btorTN8PW=vySXE1WvKtB=pOxyJ5PDwWT2w_BN0PJqvqaufP9PJerFcHrtj8UImbajPUeDwEv0aEW=ixJDw_nYW1MIJqffqfT9K_mlq5i9csTufgztir-OXI-=2GwrqOqshrWm2GdV25A=d9WWV_Jl3FSqieSWqffOSP1tYGa_I1Otq-bCfrqlcWnfikSEq5_uB9TmN_hX8=aaJHSZ8_WyZcSXwUoY6WJfcya7d0PFcYDI4N4yWVh7qOJv8Zc7WkJnwGBPqUSY5QJfakSPSwhtuXnOv=a=hh8yE5zEzGptNkSV-sZXhrO9BB0Y1qSK4dWrLVBgakiZhfWuKefoiszdlwJZWKa94ehgvW4=s_aaiG4=-phkh54Gaf4gB_OOa-alhYayGVA=cUiaW-i38tc55FagvZ1FcE4yqUNtZZSEd9Wu1_aofqWZdeBUldimcy4=OtZNJUMtaV4Ei_MKHZnmECBpKpaOJcSu2YitoGJup5jol1ivaW_0aki9YN4XNcSPEWS9=dmoHrTmLa3ZwPhNzG_l5yAIwYSPKGD0sW4gieO_5GW9a_itvVhpq3SOsrzWKQ4sieSF-5BmWex=cWBNn=-gUGWVNdK=pnSEIjMghEByKe79YWS=zW_ZqFSEJeJMfNidwIhls_uOq_79z1StjBz0hU09sNMw7WP74kS92sZmcGTpw=3tUOTgw9cuO17W8GMtDX4dg14=9Q49tFTuUUnu1__=5ra91P4tHpZG8FWWBEGFWPTMfWJuf_h4KWM7dNWmWGzEiEJ3Q1T7sq7D7qSE8eiEzObuOWBGyVWtdkxyIVi=f_ht2Oo1dgW4qGtWhUidqXSPKp4WWP4=vrJOqXa0Wp2=c_7fVNBNdY1EZz==jVmoKgMt6WnESsaSc1TJhEJ9k3Zyh63Iw0T=fkMtwsrZzqhtJh7V2UNWh9SfUbJZvU3EKOTge5S=8UzKiU4yEtSPqpT9OyJ3fk3MIwJtvGalhsngq7B=f9BY04arq_4yWgffGDiywG4G5coPKYeDwPSus_4Dzp_IEP4sW_aId-JZisWZhroPI14Y2_Wl3s7EiGSNK5WEaNag7gztvG-PqxJf-zavmNZaws1IweWImnh6E1MIa_qZ7Gr7frm_I=JuuszIiaqdq5492eqDIPStdG7I7kMDjPJtfpa9jcnZfWh9cyaIZ0auuH4=hpMI4NGyJF_DwcnOweJud6WEhp-U7pJg8GiasWS=dPB=1VMtPjJnW=o=KWZu1kB6JVTZakWtj3n92GSzJ5S_8tTO4P-Oikni8GTPyEa=ckzplPaIW9it1TvIqU4GaczIquMtfJ
// X-k39sGHmW-b: a348oo
// X-k39sGHmW-c: A_MO-4hlAQAA29XveTX0-KoQbPiy3xbjIijWum-rT-EHQtuHV6skyxlsJAsDAawUIfCucinBwH8AAOfvAAAAAA==
// X-k39sGHmW-d: 0
// X-k39sGHmW-uniqueStateKey: A7ae-4hlAQAAngSz4VMCAl-Vlq71Ta_smPn9uLwC7A7bioCLfwLMadcFYPb2AawUIfGLr4YoFOgAAAAAAAAAAA==
// X-Requested-With: XMLHttpRequest
func (a *API) TryGetCookie() (cookie string, err error) {
	params := map[string]interface{}{
		"uuid":             "15fc964c-aa54-4c2d-b718-cd3da5af9d69",
		"eid":              "GS2E2DOSGES5EJGLTQLTXN2FXRWYH2BLDSJ2JGEHLXBBE563VC2OAJEFTO5ZUHRDTRMWOADDAEKFTDAGZHXTULGZBM",
		"fp":               "b5c13ce2badacb92763e140cf2385bfc",
		"_t":               "_t",
		"loginname":        "jxcs_syl",
		"nloginpwd":        "RUUE/EHuNMv88DMcVoMxYix5wjvOSL2rhz1xckkkzgL/Nr4aVKcPvfYDvp9sW1AD32oJ4PM/shLiUAof0KKO3olq5+KwavGQW4UTI2SV+RjSmU830j4v0nSdMKfbszikj4z4R9A7W9HK853tlI0r5cSBuQK5KhsDJf7hWVFgV1c=",
		"authcode":         "3ad7a8a58e8f4122aaa522ec3e034bd3",
		"pubKey":           "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDC7kw8r6tq43pwApYvkJ5laljaN9BZb21TAIfT/vexbobzH7Q8SUdP5uDPXEBKzOjx2L28y7Xs1d9v3tdPfKI2LR7PAzWBmDMn8riHrDDNpUpJnlAGUqJG9ooPn8j7YNpcxCa1iybOlc2kEhmJn5uwoanQq+CA6agNkqly2H4j6wIDAQAB",
		"sa_token":         "B68C442BE645754F33277E701208059080DD726A94A73F76DEC3053A838549C06EB7D3797CE1C5BBE7C2B2EF9CA7D4676F3D489984B517943EA13575FA80C7E7ACE37FCFF6F535F07B6FF67F57EA6A0581BD84EA37554047DF10ECB7C873652D89DB5CAEE8F1090FB49A29547319CF16FBF33734EFA4BF8F86849797883219C3E197A604140E904BA7E538273F59893FDF9BFD6EBA3121C9E3CD43FCF0A83781B9A15920719D6C522B442FEB4A3A8C9CC7224AA55DC3877FC1BF5C845DEA80CCFB4D0CF33C8D9563ADF38943F28CEC9013C3BA8916B81844BBA454ACF21EDC3B7364C10CF219ABE7ADFFF42E2063BC2C957642453DA5E5B1E3277AE284D508B740A66BC4913EF086ACA2540C5ABB3E36C7BF693C668DFC806D4A7EFDD347D3C6869E4B529881FE46C9414D0E8E0B2B3BA3689CFCBE5CB26921DA46FABA0098E823B687A7F94DB84900C616284D5F6E49E605BFA8FD4473FD03FACD353DFA026C205B536A0DF325AC713A5B6916A60483BD386F29FF3F28046C4B19E6EE6B18F7C299C4F873C04993A085D6D6DE63C9DFECA20332F02D31EB2BA069EB9FDD3F6C14BEB40ABF57093396EEE3C2C2D727FF8C324016E2BE7BB61F4D7E2669B081E45E24801B6760CEBFE54A188FAD77B99B63D054B55FE09C6FD0A1F7B6EF448E9BBDC4D7554386AB5A2FA0787DB95D788470D913E453AF7E98F05D14B20C342F0A3CD62B833E7AC8B75C5C23ED0FC4FC4C2F23A1FAA047DEB10A856DA39B40BC9E8FC48DF17B98B28FC6C8ED1ABB248D4863083CB04E9DAD58FED19195DC02C2378C10426377996BDA4C1D060D2132BE99C37970727983EFD266A62B498B0116124E6403B18110B868B132C747F08B6DE52FD8BDD1A757E3DC74EC36D62BDF125703CB83DAA362EB086FF567C0549C6BFD26E53EC964405375B6F0CE100B44692D671D7017E45B19B42015F96D2D173B8BDA912FC3C4C8A21528EE0C28E6D4CBB8",
		"seqSid":           "331828644098046192",
		"useSlideAuthCode": "1",
	}
	err = platformapi.AccessPlatformAPIWithRetry(a.client,
		func() *http.Request {
			request, _ := http.NewRequest(http.MethodPost, "https://passport.jd.com/common/loginService?nr=1&uuid=094087da-1373-40bf-bba2-63bb64026cfd&from=pop_vender&regTag=2&ReturnUrl=https://seller.shop.jd.com/seller/sellerinfo/seller_info.action&r=0.21554654723242117", strings.NewReader(utils.Map2URLValues(params).Encode()))
			request.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
			request.Header.Set("Host", "passport.jd.com")
			request.Header.Set("Origin", "https://passport.jd.com")
			request.Header.Set("Referer", "https://passport.jd.com/common/loginPage?from=pop_vender&regTag=2&ReturnUrl=https://seller.shop.jd.com/seller/sellerinfo/seller_info.action")
			request.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3761.400 QQBrowser/10.6.4121.400")
			request.Header.Set("X-k39sGHmW-a", "ZtUfrFE109K33EiraIwE4CweB9pexmWIS9jITuItWOvk_upGBNBF7=K6nPW_O0NGwPW_at8qz0hEAaJJ405haPKUBGqUhWqrJtUeSNt7MdcGStLGWtf_hWECJasNSj5h4ke5Nh7ViE8=JnwUSsEf3tOPSKmawFcPzt_pePK6nOw5xUhOi_qIZ=M8Z=oN49KcJ0aG4tvEn-lc1O5UW9KQaZSchZakBr19ipKraXhkidpGJEKyo9UYBj5yaOdNJnTNJuMFotKPhG5OWV2Gaaifh5s1z_hG4=vZJZf_aEqcttie4tjVBXO8_=0yag7eSNwGnuYWh=vxzIzraEws4I8Y4phP4tq5Ju1_Mtc_aj1PSPWfrNEWT=usJu-y57Eaa=wgT=SPh6se4=bs_uvHSgq_4VWkSPyzhOWEJgzNSFcrryKZiFcUoAzKTYEPT96pTmPtJIUXaPhE8oasv901qgwZvI7WS=UpiuLWogw3ht_9So1g4FYkWWdq7ulJadKpSrUa3lyPrgzrJt857yqUqWNka=9QWv0Ix=KPfrWdnJ8GWt17xdUYS=w5TO7_UtzYsvf_W=hO4gqWaZW97PadSUiG1WvIJwW-JOmfJuJONtckTuMb4=YkJuYYnuKrqyS1hlFySoTqitFsWXqB49Uyn7KgWPJEiawt_yoWa9fxsZKGaEaqWIJsJVUGxVq5Wu2e4UhrMt55aFcXd=i2q646rV2kr4spMV5UJ4wPnfdq8G5EJ7Keza8UhofgWu23iVsNvjakidwzfuKFc=NZztfdttifvVE5fmWGMwK0vEdg7up6iudV_8HXTlweSj091t_kvWE14p7kBx8waWVN8Y5Fh=fkvK7N7thUnZwp3XWGerVsKjUUDWW9T_BPS9-kDDhceuhqTGagJ7t0W=c5ogO5SOSCTXZhBscUJZhymgq5hgz9dXO1nlh5BXfLJfaWWja-T9K8iGhkhusPSdWGT90wSgiXnrLzMt-Fjg8h5Fjr-g8g_sqQJh-=_Xqr4t2GTmEWf0y3SrLPupl17uIPi3e32=KqS9d-B9Yg4ywHaEWVvgef8Nhk7j21S_8rru2_3us-SN7q4XfGqW7_SZwGWVWWaPhPJZ4-J3JEor-YSNq_WO06aOfNWm1pJZqU-=8Hr9vQiF1ziPWkaZwaarcGuUw7VmJAS=O14yaWvX8GaG5Xogz1iE0WT9fk4ybFaZ8BruMFhqJk1Ii6x=KGJmWX6ai6T=OKJ7KHmP7rMIhEjg5UvI7m4=-e_iwBMKokSIwHo2a-nufWxsKr_fqGWVqUJa_G4sqeBjaKOYqri4NgoPh8r_KcvoUfiU85qZlcT6SoaupZ7d2cx=jK-rciat1_4PJGWly1blhWhuvUSyKeZXVHE_WGoP8UWZh9WawYnA7WfPfuUE01ar1vSVceWsIqAjW-JZEP4t5etEa_JlUP3p8r3fJWatvPJl3F")
			request.Header.Set("X-k39sGHmW-b", "-9kt3q0")
			request.Header.Set("X-k39sGHmW-c", "A_MO-4hlAQAA29XveTX0-KoQbPiy3xbjIijWum-rT-EHQtuHV6skyxlsJAsDAawUIfCucinBwH8AAOfvAAAAAA==")
			request.Header.Set("X-k39sGHmW-d", "0")
			request.Header.Set("X-k39sGHmW-uniqueStateKey", "A7ae-4hlAQAAngSz4VMCAl-Vlq71Ta_smPn9uLwC7A7bioCLfwLMadcFYPb2AawUIfGLr4YoFOgAAAAAAAAAAA==")
			request.Header.Set("X-Requested-With", "XMLHttpRequest")
			c := &http.Cookie{
				Name:  "alc",
				Value: "RinKQBiRr1QceieVnkF+Uw==",
			}
			c2 := &http.Cookie{
				Name:  "_t",
				Value: "DplFmazbesu5rn1NUKhLBe8yV7ia5OQcE7GXyFv3QCw=",
			}
			request.AddCookie(c)
			request.AddCookie(c2)
			return request
		},
		a.config,
		func(response *http.Response, bodyStr string, jsonResult1 map[string]interface{}) (errLevel string, err error) {
			fmt.Println(utils.Format4Output(response.Cookies(), false))
			return errLevel, err
		})
	return cookie, err
}

func (a *API) JdSSO() (err error) {
	_, err = a.AccessStorePage("https://sso.jd.com/setCookie?t=https://seller.shop.jd.com/seller/sellerinfo/seller_info.action&callback=https://seller.shop.jd.com/seller/sellerinfo/seller_info.action", nil, false)
	return err
}

type UpdateBasicParam struct {
	Version               string                   `json:"version"`
	Source                string                   `json:"source"`
	RequestID             int64                    `json:"requestId"`
	StoreID               int                      `json:"storeId"`
	StoreName             string                   `json:"storeName,omitempty"`
	CategoryID2           int                      `json:"categoryId2"`
	Coordinate            string                   `json:"coordinate"`
	BussinessBeginTime    string                   `json:"bussinessBeginTime"`
	BussinessEndTime      string                   `json:"bussinessEndTime"`
	ImgURL                string                   `json:"imgUrl"`
	StorePhone            string                   `json:"storePhone"`
	AddName               string                   `json:"addName"`
	AddCode1              int                      `json:"addCode1"`
	AddCode2              int                      `json:"addCode2"`
	AddCode3              int                      `json:"addCode3"`
	CategoryID1           int                      `json:"categoryId1"`
	ExStoreID             int                      `json:"exStoreID"`
	QualificationRequests []*QualificationRequests `json:"qualificationRequests"`
}

type QualificationRequests struct {
	QualificationID      int      `json:"qualificationId"`
	QualificationName    string   `json:"qualificationName"`
	Time                 []string `json:"time,omitempty"`
	StartTime            string   `json:"startTime,omitempty"`
	EndingTime           string   `json:"endingTime,omitempty"`
	QualificationNo      string   `json:"qualificationNo,omitempty"`
	QualificationURL     string   `json:"qualificationUrl,omitempty"`
	QualificationBusType int      `json:"qualificationBusType,omitempty"`
	QualificationBusName string   `json:"qualificationBusName,omitempty"`
}

//创建门店
func (a *API) SubmitBasic(updateBasicParam *UpdateBasicParam) (vendorStoreID int64, err error) {
	reqID := time.Now().Unix()
	result, err := a.AccessStorePage2("https://o2o-stores.shop.jd.com/shop/submitBasic?version=1.0.0&source=pc&requestId="+utils.Int64ToStr(reqID), map[string]interface{}{
		"qualificationRequests": updateBasicParam.QualificationRequests,
		"storeName":             updateBasicParam.StoreName,
		"categoryId2":           updateBasicParam.CategoryID2,
		"coordinate":            updateBasicParam.Coordinate,
		"bussinessBeginTime":    updateBasicParam.BussinessBeginTime,
		"bussinessEndTime":      updateBasicParam.BussinessEndTime,
		"imgUrl":                updateBasicParam.ImgURL,
		"storePhone":            updateBasicParam.StorePhone,
		"addName":               updateBasicParam.AddName,
		"addCode1":              updateBasicParam.AddCode1,
		"addCode2":              updateBasicParam.AddCode2,
		"addCode3":              updateBasicParam.AddCode3,
		"categoryId1":           updateBasicParam.CategoryID1,
		"version":               "1.0.0",
		"source":                "pc",
		"requestId":             reqID,
	}, true)
	if err == nil {
		if result != nil {
			if result["data"] != nil {
				vendorStoreID = utils.MustInterface2Int64(result["data"])
			} else {
				err = fmt.Errorf("err %s", result["msg"])
			}
		}
	}
	return vendorStoreID, err
}

//更新门店信息
//https://porder.shop.jd.com/order/orderlist/allOrders
func (a *API) UpdateBasic(updateBasicParam *UpdateBasicParam) (err error) {
	reqID := time.Now().Unix()
	_, err = a.AccessStorePage2("https://o2o-stores.shop.jd.com/shop/updateBasic?version=1.0.0&source=pc&requestId="+utils.Int64ToStr(reqID), map[string]interface{}{
		"storeId":               updateBasicParam.StoreID,
		"qualificationRequests": updateBasicParam.QualificationRequests,
		"storeName":             updateBasicParam.StoreName,
		"categoryId2":           updateBasicParam.CategoryID2,
		"coordinate":            updateBasicParam.Coordinate,
		"bussinessBeginTime":    updateBasicParam.BussinessBeginTime,
		"bussinessEndTime":      updateBasicParam.BussinessEndTime,
		"imgUrl":                updateBasicParam.ImgURL,
		"storePhone":            updateBasicParam.StorePhone,
		"addName":               updateBasicParam.AddName,
		"addCode1":              updateBasicParam.AddCode1,
		"addCode2":              updateBasicParam.AddCode2,
		"addCode3":              updateBasicParam.AddCode3,
		"categoryId1":           updateBasicParam.CategoryID1,
		"exStoreId":             updateBasicParam.ExStoreID,
		"version":               "1.0.0",
		"source":                "pc",
		"requestId":             reqID,
	}, true)
	return err
}

type ShopDetailResult struct {
	StoreID                 int         `json:"storeId"`
	StoreName               string      `json:"storeName"`
	CategoryID2             int         `json:"categoryId2"`
	Coordinate              string      `json:"coordinate"`
	BussinessBeginTime      string      `json:"bussinessBeginTime"`
	BussinessEndTime        string      `json:"bussinessEndTime"`
	ImgURL                  string      `json:"imgUrl"`
	Slogan                  interface{} `json:"slogan"`
	StorePhone              string      `json:"storePhone"`
	CustomerPhone           interface{} `json:"customerPhone"`
	StoreMobile             interface{} `json:"storeMobile"`
	AddCode1                int         `json:"addCode1"`
	AddCode2                int         `json:"addCode2"`
	AddCode3                int         `json:"addCode3"`
	AddCode4                int         `json:"addCode4"`
	AddName                 string      `json:"addName"`
	QualificationInfoTOList []struct {
		QualificationID   int    `json:"qualificationId"`
		QualificationNo   string `json:"qualificationNo"`
		QualificationName string `json:"qualificationName"`
		StartTime         string `json:"startTime"`
		EndingTime        string `json:"endingTime"`
		QualificationURL  string `json:"qualificationUrl"`
	} `json:"qualificationInfoTOList"`
	Created       string      `json:"created"`
	Modified      string      `json:"modified"`
	FlowID        int         `json:"flowId"`
	CategoryID1   int         `json:"categoryId1"`
	CategoryName1 string      `json:"categoryName1"`
	CategoryName2 interface{} `json:"categoryName2"`
	AuditTime     interface{} `json:"auditTime"`
}

//查询门店信息
//https://porder.shop.jd.com/order/orderlist/allOrders
func (a *API) ShopDetail(storeID int) (shopDetailResult *ShopDetailResult, err error) {
	reqID := time.Now().Unix()
	result, err := a.AccessStorePage2("https://o2o-stores.shop.jd.com/shop/detail", map[string]interface{}{
		"t":         reqID,
		"storeId":   storeID,
		"version":   "1.0.0",
		"source":    "pc",
		"requestId": reqID,
	}, false)
	if err == nil {
		utils.Map2StructByJson(result["data"], &shopDetailResult, false)
	}
	return shopDetailResult, err
}

type ShopListResult struct {
	Total int `json:"total"`
	List  []struct {
		StoreID          int         `json:"storeId"`
		StoreName        string      `json:"storeName"`
		StoreStatus      string      `json:"storeStatus"`
		OperateStatus    string      `json:"operateStatus"`
		AuditStatus      string      `json:"auditStatus"`
		AuditStatusNum   int         `json:"auditStatusNum"`
		AddNameExtend    interface{} `json:"addNameExtend"`
		AddName          string      `json:"addName"`
		Status           interface{} `json:"status"`
		Kilometres       string      `json:"kilometres"`
		Created          string      `json:"created"`
		Modified         string      `json:"modified"`
		UnitCategoryName string      `json:"unitCategoryName"`
	} `json:"list"`
}

//查询门店列表
//https://porder.shop.jd.com/order/orderlist/allOrders
func (a *API) ShopList(pageNum int) (shopDetailResult *ShopListResult, err error) {
	reqID := time.Now().Unix()
	result, err := a.AccessStorePage2("https://o2o-stores.shop.jd.com/shop/list", map[string]interface{}{
		"t":           reqID,
		"version":     "1.0.0",
		"source":      "pc",
		"requestId":   reqID,
		"pageNum":     pageNum,
		"pageSize":    40,
		"categoryId1": 34,
		"categoryId2": 62,
	}, false)
	if err == nil {
		utils.Map2StructByJson(result["data"], &shopDetailResult, false)
	}
	return shopDetailResult, err
}

//更新门店起送等
//https://porder.shop.jd.com/order/orderlist/allOrders
func (a *API) UpdateExpand(storeID int) (err error) {
	reqID := time.Now().Unix()
	_, err = a.AccessStorePage2("https://o2o-stores.shop.jd.com/shop/updateExpand?version=1.0.0&source=pc&requestId="+utils.Int64ToStr(reqID), map[string]interface{}{
		"storeId":       storeID,
		"deliveryPrice": 0,
		"weightLimit":   3000,
		"version":       "1.0.0",
		"source":        "pc",
		"requestId":     reqID,
	}, true)
	return err
}

//更新门店围栏等
//https://porder.shop.jd.com/order/orderlist/allOrders
func (a *API) CreateGisFence(storeID int, kilometres string) (err error) {
	reqID := time.Now().Unix()
	result, err := a.AccessStorePage2("https://o2o-stores.shop.jd.com/shop/createGisFence", map[string]interface{}{
		"storeIds":   storeID,
		"kilometres": kilometres,
		"version":    "1.0.0",
		"source":     "pc",
		"requestId":  reqID,
	}, false)
	if result["data"] != nil && strings.Contains(result["data"].(string), "不能重复添加") {
		err = fmt.Errorf("%s", result["data"].(string)[strings.Index(result["data"].(string), "[")+1:strings.Index(result["data"].(string), "]")])
	}
	return err
}

//更新门店配送时效
//https://porder.shop.jd.com/order/orderlist/allOrders
func (a *API) UpdateDeliveryPromise(start, end string, storeID int) (err error) {
	_, err = a.AccessStorePage2("https://delivery.shop.jd.com/o2o/promise/update", map[string]interface{}{
		"storeIds":          []int{storeID},
		"showCalendar":      false,
		"openHoursEnd":      end,
		"openHoursStart":    start,
		"immediateDelivery": true,
		"agingType":         1,
	}, true)
	return err
}

//上传图片
//https://porder.shop.jd.com/order/orderlist/allOrders
func (a *API) UploadImageNew(data []byte, fileName string) (jdURL string, err error) {
	result, err := a.AccessStorePage3(data, fileName)
	if err == nil {
		jdURL = result["data"].(string)
	}
	return jdURL, err
}

type WareSaveParam struct {
	AdContent             string            `json:"adContent"`
	AdContentURL          string            `json:"adContentUrl"`
	AdContentWords        string            `json:"adContentWords"`
	AvailableFeatures     []interface{}     `json:"availableFeatures"`
	BrandID               int               `json:"brandId"`
	CatIDLevel1           int               `json:"catIdLevel1"`
	CatIDLevel2           int               `json:"catIdLevel2"`
	CatIDLevel4           int               `json:"catIdLevel4"`
	CategoryID            int               `json:"categoryId"`
	CharacteristicService []interface{}     `json:"characteristicService"`
	ColType               int               `json:"colType"`
	CostPrice             string            `json:"costPrice"`
	Delivery              int               `json:"delivery"`
	DeliveryID1           int               `json:"deliveryId1"`
	Density               string            `json:"density"`
	DesignConcept         string            `json:"designConcept"`
	ExtendFeatures        []interface{}     `json:"extendFeatures"`
	Features              []WareSaveSkusFea `json:"features"`
	FitmentNote           string            `json:"fitmentNote"`
	FitmentNoteMobile     string            `json:"fitmentNoteMobile"`
	HasWareBoot           bool              `json:"hasWareBoot"`
	Height                int               `json:"height"`
	HouseInfo             struct {
		Address struct {
			AreaCode     int    `json:"areaCode"`
			AreaName     string `json:"areaName"`
			CityCode     int    `json:"cityCode"`
			CityName     string `json:"cityName"`
			Detail       string `json:"detail"`
			Img          string `json:"img"`
			Lat          int    `json:"lat"`
			Lng          int    `json:"lng"`
			ProvinceCode int    `json:"provinceCode"`
			ProvinceName string `json:"provinceName"`
		} `json:"address"`
		AvgPrice        int           `json:"avgPrice"`
		Characteristics string        `json:"characteristics"`
		ExtentImgMap    interface{}   `json:"extentImgMap"`
		Flag            int           `json:"flag"`
		PresaleList     []interface{} `json:"presaleList"`
		TotalPrice      int           `json:"totalPrice"`
	} `json:"houseInfo"`
	ImageMap struct {
		Num0000000000 []*CreateSkuParamImages `json:"0000000000"`
	} `json:"imageMap"`
	ImgAgreementSelected bool   `json:"imgAgreementSelected"`
	IntroductionUseFlag  string `json:"introductionUseFlag"`
	Is7ToReturn          int    `json:"is7ToReturn"`
	IsAllChannel         bool   `json:"isAllChannel"`
	IsLoc                int    `json:"isLoc"`
	IsLocSwitch          int    `json:"isLocSwitch"`
	IsOperateInvoice     int    `json:"isOperateInvoice"`
	IsRentWare           int    `json:"isRentWare"`
	IsTaxCheap           int    `json:"isTaxCheap"`
	ItemNum              string `json:"itemNum"`
	JdPrice              int    `json:"jdPrice"`
	LastCategoryID       int    `json:"lastCategoryId"`
	Length               int    `json:"length"`
	LocAreaID1           int    `json:"locAreaId1"`
	LocMatchInfoVO       struct {
		ActivitiesIllustration string `json:"activitiesIllustration"`
		ActivityAgreement      int    `json:"activityAgreement"`
		ActivityBegin          string `json:"activityBegin"`
		ActivityEnd            string `json:"activityEnd"`
		AddressID              int    `json:"addressId"`
		Coordinate             string `json:"coordinate"`
		DetailAddress          string `json:"detailAddress"`
		RegistrationField      int    `json:"registrationField"`
		VenderID               int    `json:"venderId"`
		WareID                 int    `json:"wareId"`
	} `json:"locMatchInfoVO"`
	MainImg             string        `json:"mainImg"`
	MarkSource          int           `json:"markSource"`
	MarketPrice         int           `json:"marketPrice"`
	MobileDesc          string        `json:"mobileDesc"`
	MobileDescUseFlag   string        `json:"mobileDescUseFlag"`
	MobileZhuangBaID    string        `json:"mobileZhuangBaId"`
	MoreImage           bool          `json:"moreImage"`
	MultiCateProps      []interface{} `json:"multiCateProps"`
	Notes               string        `json:"notes"`
	OptionType          int           `json:"optionType"`
	OutTime             string        `json:"outTime"`
	OuterID             string        `json:"outerId"`
	PackListing         string        `json:"packListing"`
	PayType             string        `json:"payType"`
	PromiseID           int           `json:"promiseId"`
	PromiseTemplateType int           `json:"promiseTemplateType"`
	PropsSet            []interface{} `json:"propsSet"`
	PutawayTime         string        `json:"putawayTime"`
	PwMarketingLabelVo  struct {
		IsRequestSku      bool          `json:"isRequestSku"`
		PwBdsLabelBindVos []interface{} `json:"pwBdsLabelBindVos"`
		PwBdsProposalVos  []interface{} `json:"pwBdsProposalVos"`
		RelationID        int           `json:"relationId"`
	} `json:"pwMarketingLabelVo"`
	QcReports interface{} `json:"qcReports"`
	Rate      string      `json:"rate"`
	RentSpuVO struct {
		CreateTime interface{}   `json:"createTime"`
		PlotID     int           `json:"plotId"`
		PlotInfo   interface{}   `json:"plotInfo"`
		SkuList    []interface{} `json:"skuList"`
		SpuBroker  interface{}   `json:"spuBroker"`
		SpuID      int           `json:"spuId"`
		SpuName    string        `json:"spuName"`
		StaffID    int           `json:"staffId"`
		UpdateTime interface{}   `json:"updateTime"`
	} `json:"rentSpuVO"`
	SaleAttrs             []interface{}   `json:"saleAttrs"`
	Service               string          `json:"service"`
	ServiceDesc           string          `json:"serviceDesc"`
	ServiceFeeID          int             `json:"serviceFeeId"`
	ShopCategorys         []int           `json:"shopCategorys"`
	SkuJSON               string          `json:"skuJson"`
	Skus                  []*WareSaveSkus `json:"skus"`
	TaxCheapContent       string          `json:"taxCheapContent"`
	TaxCode               string          `json:"taxCode"`
	TaxRate               int             `json:"taxRate"`
	TempID                string          `json:"tempId"`
	TemplateID            int             `json:"templateId"`
	Title                 string          `json:"title"`
	ToUsePrice            string          `json:"toUsePrice"`
	TransparentImageAudit []interface{}   `json:"transparentImageAudit"`
	TransparentImageMap   struct {
	} `json:"transparentImageMap"`
	TransportID          int    `json:"transportId"`
	UpcCode              string `json:"upcCode"`
	VenderID             int    `json:"venderId"`
	WareID               int64  `json:"wareId"`
	WareLocation         string `json:"wareLocation"`
	WareStatus           int    `json:"wareStatus"`
	WareStatusStr        string `json:"wareStatusStr"`
	Weight               string `json:"weight"`
	Wide                 int    `json:"wide"`
	ZeroTaxRate          int    `json:"zeroTaxRate"`
	ZhuangBaID           string `json:"zhuangBaId"`
	ZhuangBaIntroduction string `json:"zhuangBaIntroduction"`
	ZhuangBaMobileDesc   string `json:"zhuangBaMobileDesc"`
}

type WareSaveSkusFea struct {
	Cn    string `json:"cn"`
	Key   string `json:"key"`
	Value string `json:"value"`
}

type WareSaveSkusProp struct {
	AttrID         int    `json:"attrId"`
	AttrValues     int64  `json:"attrValues"`
	AttrValueAlias string `json:"attrValueAlias"`
}

type WareSaveSkus struct {
	Props          []*WareSaveSkusProp `json:"props"`
	Features       []interface{}       `json:"features"`
	SkuID          int64               `json:"skuId,omitempty"`
	JdPrice        string              `json:"jdPrice"`
	OuterID        string              `json:"outerId"`
	StockNum       int                 `json:"stockNum"`
	RentDeposit    string              `json:"rentDeposit"`
	RentUnit       string              `json:"rentUnit"`
	RentServiceDay string              `json:"rentServiceDay"`
	SkuProps       []interface{}       `json:"skuProps"`
	Plu            string              `json:"plu"`
	Capacity       interface{}         `json:"capacity"`
}

type WareSaveResult struct {
	SkuID    int64 `json:"skuId"`
	VenderID int   `json:"venderId"`
	WareID   int64 `json:"wareId"`
	Props    []struct {
		AttrID         string `json:"attrId"`
		AttrValues     string `json:"attrValues"`
		AttrValueAlias string `json:"attrValueAlias"`
	} `json:"props"`
	JdPrice  float64 `json:"jdPrice"`
	OuterID  string  `json:"outerId"`
	StockNum int     `json:"stockNum"`
}

//创建商品
func (a *API) WareSave(wareSaveParam *WareSaveParam) (wareSaveResult []*WareSaveResult, err error) {
	params := utils.Struct2FlatMap(wareSaveParam)
	result, err := a.AccessStorePage2("https://ware.shop.jd.com/rest/shop/ware/save", params, true)
	if err == nil && result["data"] != nil {
		utils.Map2StructByJson(result["data"].(map[string]interface{})["skus"], &wareSaveResult, false)
	}
	return wareSaveResult, err
}

//商品上下架
func (a *API) WareDoUpdate(op string, updateWareIds string) (err error) {
	_, err = a.AccessStorePage("https://ware.shop.jd.com/rest/ware/list/doUpdate", map[string]interface{}{
		"op":            op,
		"updateWareIds": updateWareIds + ",",
	}, true)
	return err
}

//门店商品上下架
func (a *API) StoreWareDoUpdate(status int, skuId int64, vendorStoreID string) (err error) {
	params := map[string]interface{}{
		"skuId":   skuId,
		"storeId": vendorStoreID,
	}
	data, _ := json.Marshal(params)
	_, err = a.AccessStorePage4("https://ware.shop.jd.com/rest/storeProduct/updateStatus/"+utils.Int2Str(status), "["+string(data)+"]", true)
	return err
}

//门店商品改价
func (a *API) StoreUpdatePrice(price string, skuId int64, vendorStoreID string) (err error) {
	params := map[string]interface{}{
		"skuId":   skuId,
		"storeId": vendorStoreID,
		"features": map[string]interface{}{
			"store_sku_price": price,
		},
	}
	data, _ := json.Marshal(params)
	_, err = a.AccessStorePage4("https://ware.shop.jd.com/rest/storeProduct/updateStoreFeature", "["+string(data)+"]", true)
	return err
}

//门店商品改库存
func (a *API) StoreUpdateStock(stockNum int, skuId int64, vendorStoreID string) (err error) {
	params := map[string]interface{}{
		"skuId":    skuId,
		"storeId":  vendorStoreID,
		"stockNum": stockNum,
	}
	data, _ := json.Marshal(params)
	_, err = a.AccessStorePage4("https://ware.shop.jd.com/rest/storeProduct/updateStoreStock", "["+string(data)+"]", true)
	return err
}

//门店关注商品
func (a *API) StoreSkuBindStore(allStore bool, skuIds, vendorStoreIDs []string) (err error) {
	params := map[string]interface{}{
		"skuIds":   skuIds,
		"storeIds": vendorStoreIDs,
		"allStore": allStore,
	}
	_, err = a.AccessStorePage2("https://ware.shop.jd.com/rest/storeProduct/skuBindStore", params, true)
	return err
}

//订单接单
func (a *API) SetOrderStateToWait(orderId int64) (err error) {
	params := map[string]interface{}{
		"orderId": orderId,
	}
	_, err = a.AccessStorePage("https://porder.shop.jd.com/order/global/setOrderStateToWait", params, false)
	return err
}

//订单妥投
func (a *API) SetOrderStateToFinish(orderId int64) (err error) {
	params := map[string]interface{}{
		"orderId": orderId,
	}
	_, err = a.AccessStorePage("https://porder.shop.jd.com/order/global/setOrderStateToFinish", params, false)
	return err
}

type StoreProductSearchResult struct {
	SkuID        int64       `json:"skuId"`
	CategoryID   int         `json:"categoryId"`
	CategoryName []string    `json:"categoryName"`
	StoreID      string      `json:"storeId"`
	StoreName    string      `json:"storeName"`
	StoreAddress string      `json:"storeAddress"`
	VenderID     string      `json:"venderId"`
	Status       int         `json:"status"`
	LastUpTime   interface{} `json:"lastUpTime"`
	LastDownTime int64       `json:"lastDownTime"`
	StorePrice   float64     `json:"storePrice"`
	StockNum     int         `json:"stockNum"`
	SkuName      string      `json:"skuName"`
	Logo         string      `json:"logo"`
	FeatureMap   struct {
	} `json:"featureMap"`
	PriceAuditStatus interface{} `json:"priceAuditStatus"`
	Reason           interface{} `json:"reason"`
	ShopSkuStatus    interface{} `json:"shopSkuStatus"`
}

//门店商品查询
func (a *API) StoreProductSearch(pageNo, pageSize int, vendorStoreIDs []string) (storeProductSearchResult []*StoreProductSearchResult, totalCount int, err error) {
	result, err := a.AccessStorePage2("https://ware.shop.jd.com/rest/storeProduct/search", map[string]interface{}{
		"pageNo":   pageNo,
		"pageSize": pageSize,
		"storeIds": vendorStoreIDs,
	}, true)
	if err == nil && result["data"] != nil {
		utils.Map2StructByJson(result["data"].(map[string]interface{})["data"], &storeProductSearchResult, false)
		totalCount = int(utils.MustInterface2Int64(result["data"].(map[string]interface{})["totalItem"]))
	}
	return storeProductSearchResult, totalCount, err
}

//京东商城设置门店营业状态
//https://o2o-stores.shop.jd.com/shop/updateStatus?version=1.0.0&source=pc&requestId=1622010400041
func (a *API) UpdateStatus(storeID, storeStatus int) (err error) {
	reqID := time.Now().Unix()
	_, err = a.AccessStorePage2("https://o2o-stores.shop.jd.com/shop/updateStatus?version=1.0.0&source=pc&requestId="+utils.Int64ToStr(reqID), map[string]interface{}{
		"storeId":     storeID,
		"storeStatus": storeStatus,
		"version":     "1.0.0",
		"source":      "pc",
		"requestId":   reqID,
	}, true)
	return err
}
