package tiktok_store

import (
	"errors"
	"fmt"
	"reflect"

	trade_batchGetTradeLimitTemplateList_response "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/trade_batchGetTradeLimitTemplateList/response"

	freightTemplate_create_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/freightTemplate_create/request"
	freightTemplate_update_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/freightTemplate_update/request"
	shop_batchCreateStore_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/shop_batchCreateStore/request"
	shop_bindStoreFreight_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/shop_bindStoreFreight/request"
	shop_bindStoreSaleLimit_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/shop_bindStoreSaleLimit/request"
	shop_editStore_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/shop_editStore/request"
	shop_getStoreDetail_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/shop_getStoreDetail/request"
	shop_getStoreList_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/shop_getStoreList/request"
	shop_storeSuspend_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/shop_storeSuspend/request"
	shop_unsuspendStore_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/shop_unsuspendStore/request"
	trade_UpdateTradeLimitTemplate_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/trade_UpdateTradeLimitTemplate/request"
	trade_createTradeLimitTemplate_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/trade_createTradeLimitTemplate/request"
	"git.rosy.net.cn/baseapi/platformapi/tiktok_shop/tiktok_api"
	"git.rosy.net.cn/baseapi/utils"
	"git.rosy.net.cn/baseapi/utils/errlist"
	"git.rosy.net.cn/jx-callback/business/jxcallback/scheduler"
	"git.rosy.net.cn/jx-callback/business/jxstore/event"
	"git.rosy.net.cn/jx-callback/business/jxutils"
	"git.rosy.net.cn/jx-callback/business/jxutils/jxcontext"
	"git.rosy.net.cn/jx-callback/business/jxutils/tasksch"
	"git.rosy.net.cn/jx-callback/business/model"
	"git.rosy.net.cn/jx-callback/business/model/dao"
	"git.rosy.net.cn/jx-callback/business/partner"
	"git.rosy.net.cn/jx-callback/globals"
	"git.rosy.net.cn/jx-callback/globals/api"
)

func SplicingTimeToDoudian(openTime1, closeTime1, openTime2, closeTime2 int16, flag bool) (timeList string) {
	//700 1200 -> 07:00-12:00
	var (
		s1  = ""
		ts1 = ""
		s2  = ""
		ts2 = ""
		//ts3     = ""//暂不支持多时间段
		s4      = ""
		ts4     = ""
		timeStr = ""
	)
	if openTime1 != 0 && closeTime1 != 0 {
		tOpenTime1 := utils.Int64ToStr(int64(openTime1))
		len1 := len(tOpenTime1) - 2
		if utils.Str2Int(tOpenTime1[:len1]) <= 9 {
			ts1 = "0"
		}
		s1 = ts1 + tOpenTime1[:len1] + ":" + tOpenTime1[len1:]
		tCloseTime1 := utils.Int64ToStr(int64(closeTime1))
		len2 := len(tCloseTime1) - 2
		if utils.Str2Int(tCloseTime1[:len2]) <= 9 {
			ts2 = "0"
		}
		s2 = ts2 + tCloseTime1[:len2] + ":" + tCloseTime1[len2:]
		if openTime2 != 0 && closeTime2 != 0 {
			//tOpenTime2 := utils.Int64ToStr(int64(openTime2))
			//len3 := len(tOpenTime2) - 2
			//if utils.Str2Int(tOpenTime2[:len3]) <= 9 {
			//	ts3 = "0"
			//}
			//s3 = ts3 + tOpenTime2[:len3] + ":" + tOpenTime2[len3:]
			tCloseTime2 := utils.Int64ToStr(int64(closeTime2))
			len4 := len(tCloseTime2) - 2
			if utils.Str2Int(tCloseTime2[:len4]) <= 9 {
				ts4 = "0"
			}
			s4 = ts4 + tCloseTime2[:len4] + ":" + tCloseTime2[len4:]
		}
	}
	if flag {
		timeStr += s1 + "-" + s4
	} else {
		timeStr += s1 + "-" + s2
	}
	return timeStr
}

// shop/batchCreateStore 批量创建门店
func (P *PurchaseHandler) CreateStore2(db *dao.DaoDB, storeID int, userName string, params map[string]interface{}, storeDetail *dao.StoreDetail) (vendorStoreID string, err error) {
	var (
		vendorStoreIDs            string
		ShopBatchCreateStoreParam *shop_batchCreateStore_request.ShopBatchCreateStoreParam
		errList                   = errlist.New()
		timeStr                   = ""
		m                         = make(map[int64]string)
		a                         = getAPI(storeDetail.VendorOrgCode, storeID, storeDetail.VendorStoreID)
	)
	if storeDetail.OpenTime1 == 0 || storeDetail.CloseTime1 == 0 {
		return "", fmt.Errorf("营业时间必填")
	} else {
		if storeDetail.OpenTime2 != 0 && storeDetail.CloseTime2 != 0 {
			timeStr = SplicingTimeToDoudian(storeDetail.OpenTime1, storeDetail.CloseTime1, storeDetail.OpenTime2, storeDetail.CloseTime2, true)
		} else {
			timeStr = SplicingTimeToDoudian(storeDetail.OpenTime1, storeDetail.CloseTime1, 0, 0, false)
		}
		for j := 1; j <= 7; j++ {
			m[int64(j)] = timeStr
		}
	}
	ShopBatchCreateStoreParam = &shop_batchCreateStore_request.ShopBatchCreateStoreParam{
		StoreList: []shop_batchCreateStore_request.StoreListItem{
			{
				RowId: 1,
				Name:  "京西菜市(" + storeDetail.Name + ")",
				//StoreCode: utils.Int2Str(storeDetail.Store.ID),
				StoreCode: utils.Int2Str(storeID),
				Longitude: utils.Float64ToStr(jxutils.IntCoordinate2Standard(storeDetail.Lng)),
				Latitude:  utils.Float64ToStr(jxutils.IntCoordinate2Standard(storeDetail.Lat)),
				Province:  storeDetail.ProvinceName,
				City:      storeDetail.CityName,
				District:  storeDetail.DistrictName,
				Address:   storeDetail.Address,
				Contact:   storeDetail.Tel1,
				OpenTime: &shop_batchCreateStore_request.OpenTime{
					DayMap: m,
				},
			},
		},
	}
	if resp, err := a.BatchCreateStore(ShopBatchCreateStoreParam); err != nil || resp.ResultList[0].Store.StoreId == 0 {
		globals.SugarLogger.Debugf("BatchCreateStore err=%v", err)
		return "", err
	} else {
		globals.SugarLogger.Debugf("BatchCreateStore resp=%s", utils.Format4Output(resp, false))
		//必须先存进数据库
		storeMap := &model.StoreMap{
			VendorStoreID:       utils.Int64ToStr(resp.ResultList[0].Store.StoreId),
			StoreID:             storeID,
			VendorID:            model.VendorIDDD,
			VendorOrgCode:       storeDetail.VendorOrgCode,
			Status:              0,
			DeliveryType:        model.StoreDeliveryTypeByStore,
			PricePercentage:     int16(utils.MustInterface2Int64(storeDetail.PricePercentage)),
			AutoPickup:          1,
			DeliveryCompetition: 1,
			IsSync:              1,
			PricePercentagePack: "",
		}
		dao.WrapAddIDCULDEntity(storeMap, userName)
		if err := dao.CreateEntity(db, storeMap); err != nil {
			errList.AddErr(dao.CreateEntity(db, storeMap))
		}
		vendorStoreIDs = utils.Int64ToStr(resp.ResultList[0].Store.StoreId)
		if err := CreateOrUpdateAll(storeDetail.VendorOrgCode, int64(storeID), resp.ResultList[0].Store.StoreId, int64(storeDetail.DeliveryFeeDeductionFee), int64(storeMap.DeliveryFeeDeductionSill), utils.Str2Int64(storeDetail.YbStorePrefix), storeDetail.YbAppID); err != nil {
			errList.AddErr(err)
		}
	}
	endErr := errList.GetErrListAsOne()
	return vendorStoreIDs, errors.New(fmt.Sprintf("创建抖店平台店铺相关错误信息：%v", endErr))
}

func CreateOrUpdateAll(vendorOrgCode string, storeID, vendorStoreID, deliveryFeeDeductionFee, deliveryFeeDeductionSill, minPrice int64, autoCall string) error {
	var (
		errList         = errlist.New()
		FreightTemplate = &model.FreightTemplate{
			StoreID:       int(storeID),
			VendorStoreID: utils.Int64ToStr(vendorStoreID),
		}
	)
	//检查门店是否审核通过
	if IfAuditPass(vendorOrgCode, vendorStoreID) {
		return fmt.Errorf("门店%d 未审核通过，请通过后再进行绑定", storeID)
	}
	//1.运费模板
	bindFreightIDs, err := GetStoreFreight(vendorOrgCode, vendorStoreID)
	if err != nil || bindFreightIDs == 0 { //（1）未查询到绑定信息，不算错误
		//创建
		if freightTemplateID, err := CreateFreightTemplate(int(storeID), int(deliveryFeeDeductionSill)); err != nil || freightTemplateID == 0 {
			errList.AddErr(fmt.Errorf("京西菜市门店:%d 平台门店:%d 创建运费模板:%d 失败:%v", storeID, vendorStoreID, freightTemplateID, err))
		} else { //绑定
			if err = ShopBindStoreFreight(vendorOrgCode, vendorStoreID, freightTemplateID); err != nil {
				errList.AddErr(fmt.Errorf("京西菜市门店:%d 平台门店:%d 绑定运费模板:%d 失败:%v", storeID, vendorStoreID, freightTemplateID, err))
			} else {
				FreightTemplate.TemplateID = freightTemplateID
			}
		}
	} else {
		if err := UpdateFreightTemplate(int(storeID), bindFreightIDs); err != nil {
			globals.SugarLogger.Debug("更新运费模板失败:", err)
			errList.AddErr(fmt.Errorf("更新运费模板失败:%v", err))
		}
		FreightTemplate.TemplateID = bindFreightIDs
	}

	//2.平台获取仓库信息以及电子围栏id
	if bind, err := GetWarehouseByStore(vendorOrgCode, vendorStoreID); err != nil {
		errList.AddErr(fmt.Errorf("获取门店(%d) 绑定仓库信息以及电子围栏出错:%v", vendorStoreID, err))
	} else {
		//(1)仓库
		if bind[utils.Int64ToStr(storeID)][0].WarehouseId > 0 {
			FreightTemplate.WarehouseID = bind[utils.Int64ToStr(storeID)][0].WarehouseId
		} else {
			if warehouseID, err := CreateWarehouse(vendorOrgCode, storeID); err != nil || warehouseID == 0 {
				errList.AddErr(fmt.Errorf("门店(%d) 创建仓库失败:%v", storeID, err))
			} else {
				if err = BindStoreWarehouse(vendorOrgCode, utils.Int64ToStr(storeID), vendorStoreID); err != nil { //仓库绑定通过自定义外部ID
					errList.AddErr(fmt.Errorf("门店(%d) 绑定仓库%d 失败:%v", storeID, warehouseID, err))
				} else {
					FreightTemplate.WarehouseID = warehouseID
				}
			}
			//(2)电子围栏
			if len(bind[utils.Int64ToStr(storeID)][0].OutFenceIds) > 0 {
				tempFenceID := bind[utils.Int64ToStr(storeID)][0].OutFenceIds[0]
				if err1 := UpdateFenceByStore(vendorOrgCode, tempFenceID, utils.Int64ToStr(storeID)); err1 != nil {
					errList.AddErr(fmt.Errorf("平台门店(%d),门店(%d)更新电子围栏失败:%v", vendorStoreID, storeID, err1))
				}
				FreightTemplate.FenceID = bind[utils.Int64ToStr(storeID)][0].OutFenceIds[0] //保存一个就足够
			} else {
				if fenceID, err := CreateFenceByStore(vendorOrgCode, storeID); err != nil || len(fenceID) == 0 {
					errList.AddErr(fmt.Errorf("门店(%d) 创建电子围栏失败:%v", storeID, err))
				} else {
					if err := BindFenceByStore(vendorOrgCode, vendorStoreID, []string{utils.Int64ToStr(storeID)}); err != nil {
						errList.AddErr(fmt.Errorf("门店(%d) 绑定电子围栏:%s失败:%v", storeID, fenceID, err))
					} else {
						FreightTemplate.FenceID = utils.Int64ToStr(storeID)
					}
				}
			}
		}
	}
	//3.平台获取限售模板
	if bindSaleLimitID, err := GetStoreSaleLimit(vendorOrgCode, vendorStoreID); err != nil || bindSaleLimitID == 0 { //未绑定限售模板,目前默认创建起送价限售模板
		if createSaleLimitID, err := CreateAndBindMinPriceTemplate(vendorOrgCode, vendorStoreID, minPrice); err != nil {
			errList.AddErr(fmt.Errorf("设置门店起送价限售模板失败:%v", err))
		} else {
			FreightTemplate.TradeLimitID = createSaleLimitID
		}
	} else {
		if updateSaleLimitID, err := UpdateTradeLimitTemplate(vendorOrgCode, bindSaleLimitID, minPrice); err != nil {
			errList.AddErr(fmt.Errorf("更新门店起送价限售模板失败：%v", err))
		} else {
			FreightTemplate.TradeLimitID = updateSaleLimitID
		}
	}
	//4. 设置门店打包费 默认为0
	if err := SetStorePackageFee(vendorOrgCode, vendorStoreID, deliveryFeeDeductionFee); err != nil {
		errList.AddErr(fmt.Errorf("设置门店打包费失败:%v", err))
	}
	//5.设置自动运力
	if autoCall == tiktok_api.AutoCallRiderOpen {
		if err := SetStoreAutoCallRider(vendorOrgCode, tiktok_api.AutoCallRiderOpen, vendorStoreID); err != nil {
			errList.AddErr(fmt.Errorf("开启门店自动运力失败：%v", err))
		}
	} else {
		if err := SetStoreAutoCallRider(vendorOrgCode, tiktok_api.AutoCallRiderClose, vendorStoreID); err != nil {
			errList.AddErr(fmt.Errorf("关闭门店自动运力失败：%v", err))
		}
	}

	//6.同步进数据库
	if err := dao.ReplaceInsertFreight(FreightTemplate); err != nil {
		if err1 := dao.InsertItemFreight(FreightTemplate); err1 != nil {
			globals.SugarLogger.Debug("同步数据库错误信息:%v", err1)
		}
	}
	//if err := dao.CreateEntity(db, FreightTemplate); dao.IsDuplicateError(err) || err != nil {
	//	if _, err1 := dao.UpdateEntity(db, FreightTemplate, "TemplateID", "WarehouseID", "FenceID", "TradeLimitID", "StoreID", "VendorStoreID"); err1 != nil {
	//		globals.SugarLogger.Debug("更新操作，同步进数据库错误信息:%v", err1)
	//		//errList.AddErr(fmt.Errorf("更新操作，同步进数据库错误信息:%v", err1))
	//	} else {
	//		globals.SugarLogger.Debug("创建操作，同步进数据库错误信息:%v", err)
	//		//errList.AddErr(fmt.Errorf("创建操作，同步进数据库错误信息:%v", err))
	//	}
	//}
	endErr := errList.GetErrListAsOne()
	if endErr != nil {
		globals.SugarLogger.Debug("绑定抖音门店需进行的错误处理:%v", errors.New(fmt.Sprintf("%s", utils.Format4Output(errList, false))))
		return endErr
	} else {
		return nil
	}
}

//  shop/editStore 编辑门店信息 正向推送平台
func (P *PurchaseHandler) UpdateStore(db *dao.DaoDB, storeID int, userName string) (err error) {
	var (
		m               = make(map[int64]string)
		name            string
		storeInfo       *dao.StoreDetail
		errList         = errlist.New()
		timeStr         = ""
		tempFenceID     string
		FreightTemplate = &model.FreightTemplate{
			StoreID: storeID,
		}
	)
	if db == nil {
		db = dao.GetDB()
	}
	storeInfo, err = dao.GetStoreDetail(db, storeID, model.VendorIDDD, "")
	apiObj := getAPI(storeInfo.VendorOrgCode, storeID, storeInfo.VendorStoreID)
	//判断是否需要更新
	if !IsNeedStoreUpdate(storeInfo, storeInfo.VendorStoreID) {
		return nil
	} else {
		if storeInfo.OpenTime1 != 0 && storeInfo.CloseTime1 != 0 {
			if storeInfo.OpenTime2 != 0 && storeInfo.CloseTime2 != 0 {
				timeStr = SplicingTimeToDoudian(storeInfo.OpenTime1, storeInfo.CloseTime1, storeInfo.OpenTime2, storeInfo.CloseTime2, true)
			} else {
				timeStr = SplicingTimeToDoudian(storeInfo.OpenTime1, storeInfo.CloseTime1, 0, 0, false)
			}
			for j := 1; j <= 7; j++ {
				m[int64(j)] = timeStr
			}
		} else {
			return fmt.Errorf("营业时间必填")
		}
		if globals.EnableDdStoreWrite {
			remoteStoreInfo, err2 := apiObj.GetStoreDetail(&shop_getStoreDetail_request.ShopGetStoreDetailParam{
				StoreId: storeInfo.VendorStoreID,
			})
			if err2 != nil {
				return err2
			}
			if remoteStoreInfo.StoreDetail.Store.StoreId == 0 {
				return fmt.Errorf("ID(%d) 的门店不存在,请先创建", utils.Str2Int64(storeInfo.VendorStoreID))
			}
			mergedStoreStatus := jxutils.MergeStoreStatus(storeInfo.Status, storeInfo.VendorStatus)
			name = remoteStoreInfo.StoreDetail.Store.Name
			if storeInfo.SyncStatus&(model.SyncFlagNewMask|model.SyncFlagStoreName) != 0 {
				if storeInfo.VendorStoreName != "" {
					name = storeInfo.VendorStoreName
				}
			}
			store := fmt.Sprintf("门店id:%d,门店名称:%s,第三方门店状态:%d,本地修改前门店状态%d,本地门店修改后状态:%d,第三方平台Id(抖店):%s", storeID, remoteStoreInfo.StoreDetail.Store.Name, remoteStoreInfo.StoreDetail.Store.State, storeInfo.Status, mergedStoreStatus, storeInfo.VendorOrgCode)
			event.AddOperateEvent(jxcontext.AdminCtx, jxcontext.AdminCtx.GetTrackInfo(), store, "", "", 10, "UpdateStore")
			params := &shop_editStore_request.ShopEditStoreParam{
				StoreId:   remoteStoreInfo.StoreDetail.Store.StoreId, //平台id不可修改
				Name:      name,
				StoreCode: utils.Int2Str(storeInfo.ID), //自用编码即本地storeID
				Latitude:  utils.Float64ToStr(jxutils.IntCoordinate2Standard(storeInfo.Lat)),
				Longitude: utils.Float64ToStr(jxutils.IntCoordinate2Standard(storeInfo.Lng)),
				Province:  storeInfo.ProvinceName,
				City:      storeInfo.CityName,
				District:  storeInfo.DistrictName,
				Address:   storeInfo.Address,
				Contact:   storeInfo.Tel1,
				OpenTime: &shop_editStore_request.OpenTime{
					DayMap: m,
				},
			}
			//修改店铺状态
			if storeInfo.SyncStatus&(model.SyncFlagNewMask|model.SyncFlagStoreStatus) != 0 {
				errList.AddErr(UpdateStoreStatus(jxcontext.AdminCtx, storeInfo.VendorOrgCode, storeID, storeInfo.VendorStoreID, mergedStoreStatus))
			}
			if err3 := apiObj.EditStore(params); err3 != nil {
				errList.AddErr(fmt.Errorf("修改门店(%d) 信息失败:%v", utils.Str2Int64(storeInfo.VendorStoreID), err3))
			}
			//电子围栏
			bind, err := GetWarehouseByStore(storeInfo.VendorOrgCode, utils.Str2Int64(storeInfo.VendorStoreID))
			if err != nil {
				errList.AddErr(fmt.Errorf("获取门店(%d) 电子围栏失败:%v", utils.Str2Int64(storeInfo.VendorStoreID), err))
			} else if len(bind[storeInfo.VendorStoreID][0].OutFenceIds) == 0 {
				//检查是否以storeID创建过
				if bindFence, err := GetFence(storeInfo.VendorOrgCode, []string{utils.Int2Str(storeID)}); err == nil {
					tempFenceID = bindFence[0].OutFenceId
				} else {
					if fenceID, err := CreateFenceByStore(storeInfo.VendorOrgCode, int64(storeID)); err != nil || len(fenceID) == 0 { //创建
						globals.SugarLogger.Debug("门店(%d) 创建电子围栏失败:%v", storeID, err)
						errList.AddErr(fmt.Errorf("门店(%d) 创建电子围栏失败:%v", storeID, err))
					} else {
						tempFenceID = fenceID
					}
				}
				if err := BindFenceByStore(storeInfo.VendorOrgCode, utils.Str2Int64(storeInfo.VendorStoreID), []string{utils.Int2Str(storeID)}); err != nil {
					globals.SugarLogger.Debug("门店(%d) 绑定电子围栏:%s失败:%v", storeID, tempFenceID, err)
					errList.AddErr(fmt.Errorf("门店(%d) 绑定电子围栏:%s失败:%v", storeID, tempFenceID, err))
				}
			} else if len(bind[storeInfo.VendorStoreID][0].OutFenceIds) > 0 {
				//默认更新第一个电子围栏
				outFenceID := bind[storeInfo.VendorStoreID][0].OutFenceIds[0]
				if err = UpdateFenceByStore(storeInfo.VendorOrgCode, outFenceID, utils.Int2Str(storeID)); err != nil {
					errList.AddErr(errors.New(fmt.Sprintf("更新电子围栏失败，原因:%v", err)))
				}
				FreightTemplate.FenceID = outFenceID
			}
		}
		//同步进数据库
		FreightTemplate.FenceID = tempFenceID
		FreightTemplate.VendorStoreID = storeInfo.VendorStoreID
		if err := dao.ReplaceInsertFreight(FreightTemplate); err != nil {
			if err1 := dao.InsertItemFreight(FreightTemplate); err1 != nil {
				globals.SugarLogger.Debug("同步数据库错误信息:%v", err1)
			}
		}
		//if err = dao.CreateEntity(db, FreightTemplate); dao.IsDuplicateError(err) || err != nil {
		//	if _, err1 := dao.UpdateEntity(db, FreightTemplate, "FenceID", "StoreID", "VendorStoreID"); err1 != nil {
		//		errList.AddErr(fmt.Errorf("更新操作，同步进数据库错误信息:%v", err1))
		//	} else {
		//		errList.AddErr(fmt.Errorf("创建操作，同步进数据库错误信息:%v", err))
		//	}
		//}
		if endErr := errList.GetErrListAsOne(); endErr != nil {
			globals.SugarLogger.Debugf("DouDian UpdateStore wrong information:%v", endErr)
		}
		return nil
	}
}

// UpdateStoreStatus shop/unsuspendStore 门店恢复营业
func UpdateStoreStatus(ctx *jxcontext.Context, vendorOrgCode string, storeID int, vendorStoreID string, status int) (err error) {
	isOnline := bizStatusJX2DouDian(status)
	a := getAPI(vendorOrgCode, storeID, vendorStoreID)
	if globals.EnableDdStoreWrite {
		if isOnline != tiktok_api.StoreStatusOnline { //暂停营业状态
			if _, err = a.StoreSuspend(&shop_storeSuspend_request.ShopStoreSuspendParam{
				StoreId: utils.Str2Int64(vendorStoreID),
			}); err != nil {
				return err
			}
		} else { //恢复营业
			//与平台上店铺状态对比
			if remoteStoreInfo, err2 := a.GetStoreDetail(&shop_getStoreDetail_request.ShopGetStoreDetailParam{
				StoreId: vendorStoreID,
			}); err2 != nil {
				return err2
			} else {
				if remoteStoreInfo.StoreDetail.Store.SuspendType == tiktok_api.SuspendTypePlatformPenalty {
					err = errors.New("门店因平台处罚暂停营业，不可主动修改营业状态")
				} else {
					if _, err = a.UnsuspendStore(&shop_unsuspendStore_request.ShopUnsuspendStoreParam{
						StoreId: utils.Str2Int64(vendorStoreID),
					}); err != nil {
						return err
					}
				}
			}
		}
	}
	return err
}

// CreateFreightTemplate 默认 运费模板只创建 固定运费模板
func CreateFreightTemplate(storeCode, deliveryFeeDeductionSill int) (int64, error) {
	storeDetail, err := dao.GetStoreDetail(dao.GetDB(), storeCode, model.VendorIDDD, "")
	if err != nil {
		return 0, err
	}
	param := &freightTemplate_create_request.FreightTemplateCreateParam{
		Template: &freightTemplate_create_request.Template{
			TemplateName:    utils.Int2Str(storeCode) + "的",
			ProductProvince: utils.Str2Int64(utils.Int2Str(storeDetail.ProvinceCode)[:2]),
			CalculateType:   tiktok_api.CalculateTypeNum,
			TransferType:    tiktok_api.TransferTypeExpress,
			RuleType:        tiktok_api.RuleTypeFlatShipping,
			FixedAmount:     500, //固定运费 单位：分
		},
	}
	//直辖市特殊处理
	if flag, code := HandleMunicipality(storeDetail.CityName); flag {
		param.Template.ProductCity = code
		//param.Columns = []freightTemplate_create_request.ColumnsItem{{
		//	ProvinceInfos: []freightTemplate_create_request.ProvinceInfosItem{{
		//		Id: utils.Str2Int64(utils.Int2Str(storeDetail.ProvinceCode)[:2]),
		//		Children: []freightTemplate_create_request.ChildrenItem_4{
		//			{
		//				Id: int64(storeDetail.ProvinceCode),
		//				Children: []freightTemplate_create_request.ChildrenItem_5{
		//					{
		//						Id: int64(storeDetail.DistrictCode),
		//						//Children: []freightTemplate_create_request.ChildrenItem{
		//						//	{Id: 0},
		//						//},
		//					},
		//				},
		//			},
		//		}},
		//	}},
		//}
	} else {
		param.Template.ProductCity = int64(storeDetail.CityCode)
		//param.Columns = []freightTemplate_create_request.ColumnsItem{{
		//	ProvinceInfos: []freightTemplate_create_request.ProvinceInfosItem{
		//		{
		//			Id: utils.Str2Int64(utils.Int2Str(storeDetail.ProvinceCode)[:2]),
		//			Children: []freightTemplate_create_request.ChildrenItem_4{
		//				{
		//					Id: int64(storeDetail.CityCode),
		//					Children: []freightTemplate_create_request.ChildrenItem_5{
		//						{
		//							Id: int64(storeDetail.DistrictCode),
		//							//Children: []freightTemplate_create_request.ChildrenItem{
		//							//	{Id: 0},
		//							//},
		//						},
		//					},
		//				},
		//			}},
		//	},
		//},
		//}
	}
	if deliveryFeeDeductionSill != 0 {
		param.Template.TemplateName += "满减包邮模板"
		param.Columns = []freightTemplate_create_request.ColumnsItem{{
			IsOverFree: true, //是否包邮
			IsLimited:  false,
			OverAmount: int64(deliveryFeeDeductionSill), //此字段在vendor_id=14时 存储满x包邮金额
		}}
	} else {
		param.Template.TemplateName += "固定运费模板"
	}

	resp, err := getAPI(storeDetail.VendorOrgCode, storeCode, storeDetail.VendorStoreID).FreightTemplateCreate(param)
	if err != nil {
		return 0, err
	}
	return resp.TemplateId, nil
}

// UpdateFreightTemplate  修改运费模板
func UpdateFreightTemplate(storeCode int, templateId int64) error {
	//获取本地门店信息
	storeDetail, err := dao.GetStoreDetail(dao.GetDB(), storeCode, model.VendorIDDD, "")
	if err != nil {
		return errors.New(fmt.Sprintf("获取本地门店信息失败:%v", err))
	}

	//获取绑定的运费模板信息
	param := &freightTemplate_update_request.FreightTemplateUpdateParam{
		Template: &freightTemplate_update_request.Template{
			Id:              templateId,
			TemplateName:    utils.Int2Str(storeCode) + "的",
			ProductProvince: utils.Str2Int64(utils.Int2Str(storeDetail.ProvinceCode)[:2]),
			CalculateType:   tiktok_api.CalculateTypeNum,
			TransferType:    tiktok_api.TransferTypeExpress,
			RuleType:        tiktok_api.RuleTypeFlatShipping,
			FixedAmount:     500, //固定运费 单位：分
		},
	}
	if storeDetail.CityName == tiktok_api.MunicipalityBeiJin || storeDetail.CityName == tiktok_api.MunicipalityShangHai || storeDetail.CityName == tiktok_api.MunicipalityTianJin || storeDetail.CityName == tiktok_api.MunicipalityChongQing {
		param.Template.ProductCity = int64(storeDetail.ProvinceCode)
	} else {
		param.Template.ProductCity = int64(storeDetail.CityCode)
	}
	if int64(storeDetail.DeliveryFeeDeductionSill) != 0 {
		param.Template.TemplateName += "满减包邮模板"
		columns := []freightTemplate_update_request.ColumnsItem{
			{
				IsOverFree: true, //是否包邮
				IsDefault:  0,
				IsLimited:  false,
				OverAmount: int64(storeDetail.DeliveryFeeDeductionSill), //此字段在vendor_id=14时 存储满x包邮金额
			}}
		param.Columns = columns
	} else {
		param.Columns = nil
		param.Template.TemplateName += "固定运费模板"
	}
	_, err = getAPI(storeDetail.VendorOrgCode, storeCode, storeDetail.VendorStoreID).FreightTemplateUpdate(param)
	if err != nil {
		return err
	}
	return nil
}

//  /freightTemplate/create 批量创建绑定 满x包邮 运费模板
func CreateBindFreeShipTemplate(vendorOrgCode string, storeID int, shipFee int64) error {
	var (
		errList         = errlist.New()
		FreightTemplate = &model.FreightTemplate{
			StoreID: storeID,
		}
	)
	if shipFee == 0 {
		return errors.New("包邮金额必传,请检查")
	}
	storeDetail, err := dao.GetStoreDetail(dao.GetDB(), storeID, model.VendorIDDD, "")
	if err != nil {
		return errors.New("创建包邮运费模板,获取门店信息失败,请重试")
	}
	param := &freightTemplate_create_request.FreightTemplateCreateParam{
		Template: &freightTemplate_create_request.Template{
			TemplateName:    utils.Int2Str(storeID) + "的满减包邮模板",
			ProductProvince: utils.Str2Int64(utils.Int2Str(storeDetail.ProvinceCode)[:2]),
			CalculateType:   tiktok_api.CalculateTypeNum,
			TransferType:    tiktok_api.TransferTypeExpress,
			RuleType:        tiktok_api.RuleTypeFlatShipping,
			FixedAmount:     500, //固定运费 单位：分
		},
		Columns: []freightTemplate_create_request.ColumnsItem{
			{
				IsOverFree: true,
				IsLimited:  false,
				OverAmount: shipFee * 100,
			}},
	}
	//直辖市特殊处理
	if flag, code := HandleMunicipality(storeDetail.CityName); flag {
		param.Template.ProductCity = code
	} else {
		param.Template.ProductCity = int64(storeDetail.CityCode)
	}
	if resp, err := getAPI(vendorOrgCode, 0, "").FreightTemplateCreate(param); err != nil {
		return errors.New(fmt.Sprintf("平台门店(%s) 京西门店(%d) 创建包邮模板失败:%v,根据提示处理", storeDetail.VendorStoreID, storeID, err))
	} else {
		if err := ShopBindStoreFreight(vendorOrgCode, utils.Str2Int64(storeDetail.VendorStoreID), resp.TemplateId); err != nil {
			return errors.New(fmt.Sprintf("平台门店(%s) 京西门店(%d) 绑定包邮模板失败:%v,根据提示处理", storeDetail.VendorStoreID, storeID, err))
		} else {
			FreightTemplate.VendorStoreID = storeDetail.VendorStoreID
			FreightTemplate.TemplateID = resp.TemplateId
			if err := dao.ReplaceInsertFreight(FreightTemplate); err != nil {
				if err1 := dao.InsertItemFreight(FreightTemplate); err1 != nil {
					globals.SugarLogger.Debug("同步数据库错误信息:%v", err1)
				}
			}
			//if err := dao.CreateEntity(db, FreightTemplate); dao.IsDuplicateError(err) || err != nil {
			//	if _, err1 := dao.UpdateEntity(db, FreightTemplate, "TemplateID"); err1 != nil {
			//		errList.AddErr(fmt.Errorf("包邮模板:更新操作，同步进数据库错误信息:%v", err1))
			//	} else {
			//		errList.AddErr(fmt.Errorf("包邮模板:创建操作，同步进数据库错误信息:%v", err))
			//	}
			//}
		}
	}
	if errList.GetErrListAsOne() != nil {
		return errList.GetErrListAsOne()
	}
	return nil
}

//更新 包邮运费模板
func UpdateFreeShipTemplate(vendorOrgCode string, storeID int, shipFee int64) error {
	if shipFee == 0 {
		return errors.New("包邮金额必传,请检查")
	}
	storeDetail, err := dao.GetStoreDetail(dao.GetDB(), storeID, model.VendorIDDD, "")
	if err != nil {
		return errors.New("更新包邮运费模板,获取门店信息失败,请重试")
	}
	a := getAPI(vendorOrgCode, storeID, storeDetail.VendorStoreID)
	//获取远程运费模板详情
	if bindFreightID, err := a.GetStoreFreight(utils.Str2Int64(storeDetail.VendorStoreID)); err != nil || len(bindFreightID) == 0 || utils.IsNil(bindFreightID) {
		//return errors.New("门店未绑定运费模板，")
	} else {
		if freightDetail, err := a.GetStoreFreightDetail(bindFreightID[0]); err == nil {
			param := &freightTemplate_update_request.FreightTemplateUpdateParam{
				Template: &freightTemplate_update_request.Template{
					Id:              bindFreightID[0],
					TemplateName:    freightDetail.Template.TemplateName,
					ProductProvince: utils.Str2Int64(freightDetail.Template.ProductProvince),
					ProductCity:     utils.Str2Int64(freightDetail.Template.ProductCity),
					CalculateType:   tiktok_api.CalculateTypeNum,
					TransferType:    tiktok_api.TransferTypeExpress,
					RuleType:        tiktok_api.RuleTypeFlatShipping,
					FixedAmount:     500,
				},
				Columns: []freightTemplate_update_request.ColumnsItem{
					{
						IsOverFree: true,
						IsLimited:  false,
						OverAmount: shipFee * 100,
					}},
			}
			if _, err := a.FreightTemplateUpdate(param); err != nil {
				return errors.New("更新包邮运费模板失败")
			}
		}
	}
	return nil
}

// /shop/bindStoreFreight  门店绑定运费模版
//门店绑定运费模版，运费模版必须属于门店关联的抖店，且门店与运费模版是一对一关系
func ShopBindStoreFreight(vendorOrgCode string, storeID, freightID int64) error {
	if err := getAPI(vendorOrgCode, int(storeID), "").BindFreightTemplate(&shop_bindStoreFreight_request.ShopBindStoreFreightParam{
		StoreId:   storeID,
		FreightId: freightID,
	}); err != nil {
		return err
	}
	return nil
}

//  /shop/getStoreFreight 获取门店绑定运费模板
func GetStoreFreight(vendorOrgCode string, storeID int64) (int64, error) {
	if resp, err := getAPI(vendorOrgCode, int(storeID), "").GetStoreFreight(storeID); err != nil || len(resp) == 0 {
		return 0, err
	} else {
		return resp[0], nil
	}
}

// /trade/createTradeLimitTemplate 创建限售模板 默认模板 暂时不使用
func CreateTradeLimitTemplate(appOrgCode string, vendorStoreID int64) (tradeLimitID int64, err error) {
	param := &trade_createTradeLimitTemplate_request.TradeCreateTradeLimitTemplateParam{
		StoreId: vendorStoreID,
		TradeLimitRuleRequestList: []trade_createTradeLimitTemplate_request.TradeLimitRuleRequestListItem{
			{
				TradeLimitModel:    tiktok_api.TradeLimitModelQuantity,
				TradeLimitResource: tiktok_api.TradeLimitResourceDouDian,
				TradeLimitPattern: &trade_createTradeLimitTemplate_request.TradeLimitPattern{
					Minimum:       1,
					Maximum:       1000,
					CumulativeMax: 10000,
				},
				TradeLimitSubjectList: []int32{tiktok_api.TradeLimitSubjectBuyMobile},
			},
		},
	}
	resp, err := getAPI(appOrgCode, 0, utils.Int64ToStr(vendorStoreID)).CreateTradeLimitTemplate(param)
	if err != nil {
		return 0, err
	}
	return resp.TradeLimitId, nil
}

//创建起送价的 限售模板以及绑定
func CreateAndBindMinPriceTemplate(vendorOrgCode string, vendorStoreID, minimum int64) (int64, error) {
	resp, err := getAPI(vendorOrgCode, 0, "").CreateTradeLimitTemplate(&trade_createTradeLimitTemplate_request.TradeCreateTradeLimitTemplateParam{
		StoreId: vendorStoreID,
		TradeLimitRuleRequestList: []trade_createTradeLimitTemplate_request.TradeLimitRuleRequestListItem{
			{
				TradeLimitModel:    tiktok_api.TradeLimitModelMoney,
				TradeLimitResource: tiktok_api.TradeLimitResourceDouDian,
				TradeLimitPattern: &trade_createTradeLimitTemplate_request.TradeLimitPattern{
					Minimum:       minimum,
					Maximum:       minimum,
					CumulativeMax: 100,
				},
				TradeLimitSubjectList: []int32{
					tiktok_api.TradeLimitSubjectEndUser,
				},
			},
		},
	})
	if err != nil || resp.TradeLimitId == 0 {
		return 0, errors.New(fmt.Sprintf("创建门店(%d)的起送价失败：%v", vendorStoreID, err))
	} else { //绑定
		if err := BindStoreSaleLimit(vendorOrgCode, vendorStoreID, resp.TradeLimitId); err != nil {
			return 0, errors.New(fmt.Sprintf("门店(%d)绑定 起送价限售模板失败：%v", vendorStoreID, err))
		}
	}
	return resp.TradeLimitId, nil
}

//  /trade/UpdateTradeLimitTemplate 更新限售模板 目前只做起送价
func UpdateTradeLimitTemplate(vendorOrgCode string, tradeLimitID, minPrice int64) (int64, error) {
	if updateTradeLimit, err := getAPI(vendorOrgCode, 0, "").UpdateTradeLimitTemplate(&trade_UpdateTradeLimitTemplate_request.TradeUpdateTradeLimitTemplateParam{
		TradeLimitTemplateId: tradeLimitID,
		TradeLimitRuleRequestList: []trade_UpdateTradeLimitTemplate_request.TradeLimitRuleRequestListItem{
			{
				TradeLimitModel:    tiktok_api.TradeLimitModelMoney,
				TradeLimitResource: tiktok_api.TradeLimitResourceDouDian,
				TradeLimitPattern: &trade_UpdateTradeLimitTemplate_request.TradeLimitPattern{
					Minimum:       minPrice,
					Maximum:       minPrice,
					CumulativeMax: 100,
				},
				TradeLimitSubjectLisit: []int32{
					tiktok_api.TradeLimitSubjectEndUser,
				},
			},
		},
	}); err != nil {
		return 0, err
	} else if updateTradeLimit.TradeLimitTemplateId == 0 {
		return 0, errors.New(fmt.Sprintf("更新操作返回的TradeLimitTemplateId=0"))
	} else {
		return updateTradeLimit.TradeLimitTemplateId, nil
	}
}

// /shop/bindStoreSaleLimit 门店绑定限售模板
func BindStoreSaleLimit(appOrgCode string, storeID, saleLimitTemplateID int64) error {
	if err := getAPI(appOrgCode, 0, utils.Int64ToStr(storeID)).BindStoreSaleLimit(&shop_bindStoreSaleLimit_request.ShopBindStoreSaleLimitParam{
		StoreId:     storeID,
		SaleLimitId: saleLimitTemplateID,
	}); err != nil {
		return err
	}
	return nil
}

//  /shop/getStoreSaleLimit 获取门店绑定限售模板
func GetStoreSaleLimit(appOrgCode string, storeID int64) (int64, error) {
	if saleLimitTemplateID, err := getAPI(appOrgCode, 0, "").StoreQuerySaleLimitTemp(storeID); err != nil {
		return 0, err
	} else {
		return saleLimitTemplateID, nil
	}
}

// /trade/batchGetTradeLimitTemplateList 批量获取限售模板详情
func BatchGetTradeLimitDetail(appOrgCode string, saleLimitIDs []int64) (*trade_batchGetTradeLimitTemplateList_response.TradeBatchGetTradeLimitTemplateListData, error) {
	if details, err := getAPI(appOrgCode, 0, "").GetSaleLimitDetail(&saleLimitIDs); err != nil {
		return nil, err
	} else {
		return details, nil
	}
}

func (P *PurchaseHandler) UpdateStoreOpTime(ctx *jxcontext.Context, vendorOrgCode string, storeID int, vendorStoreID string, opTimeList []int16) (err error) {
	var (
		timeStr = ""
		t1      = opTimeList[0]
		t2      = opTimeList[1]
		t3      = opTimeList[2]
		t4      = opTimeList[4]
		m       = make(map[int64]string)
	)
	if t1 != 0 && t2 != 0 {
		if t3 != 0 && t4 != 0 {
			timeStr = SplicingTimeToDoudian(t1, t2, t3, t4, true)
		} else {
			timeStr = SplicingTimeToDoudian(t1, t2, t3, t4, false)
		}
	} else {
		return fmt.Errorf("营业时间必填")
	}
	for j := 1; j <= 7; j++ {
		m[int64(j)] = timeStr
	}
	if globals.EnableDdStoreWrite {
		err = getAPI(vendorOrgCode, storeID, vendorStoreID).EditStore(&shop_editStore_request.ShopEditStoreParam{
			StoreId: utils.Str2Int64(vendorStoreID),
			OpenTime: &shop_editStore_request.OpenTime{
				DayMap: m,
			},
		})
	}
	return err
}

//获取门店状态
func (P *PurchaseHandler) GetStoreStatus(ctx *jxcontext.Context, vendorOrgCode string, storeID int, vendorStoreID string) (storeStatus int, err error) {
	if result, err := getAPI(vendorOrgCode, storeID, vendorStoreID).GetStoreDetail(&shop_getStoreDetail_request.ShopGetStoreDetailParam{
		StoreId:            vendorStoreID,
		IsNeedChargeInfo:   false,
		IsNeedPoiAuditInfo: false,
		IsNeedRelShopUser:  false,
	}); err != nil {
		return 0, err
	} else {
		poiStatus := int(result.StoreDetail.Store.PoiAuditState)
		return poiStatus, nil
	}
}

func (P *PurchaseHandler) EnableAutoAcceptOrder(ctx *jxcontext.Context, vendorOrgCode string, storeID int, vendorStoreID string, isSetEnable bool) (err error) {
	return err
}

// 获取店铺所有平台ID
func (P *PurchaseHandler) GetAllStoresVendorID(ctx *jxcontext.Context, vendorOrgCode string) (vendorStoreIDs []string, err error) {
	//param := &shop_getStoreList_request.ShopGetStoreListParam{
	//	Page:     "0",
	//	PageSize: "20",
	//}
	//if stores, err := getAPI(vendorOrgCode, 0, "").GetStoreList(param); err != nil || stores.Total == 0 {
	//	return nil, errors.New(fmt.Sprintf("暂时无门店数据返回，请重试:%v", err))
	//}
	//else if len(stores.StoreDetailList) > 0 {
	//	vendorStoreIDs = make([]string, len(stores.StoreDetailList))
	//	for k, v := range stores.StoreDetailList {
	//		vendorStoreIDs[k] = utils.Int64ToStr(v.Store.StoreId)
	//	}
	//}
	//return vendorStoreIDs, err
	return nil, err
}

//获取京西 抖店门店映射关系
func GetAllVendorStoreMap(ctx *jxcontext.Context, vendorOrgCode string) (map[int64]string, error) {
	param := &shop_getStoreList_request.ShopGetStoreListParam{
		Page:     "0",
		PageSize: "20",
	}
	if stores, err := getAPI(vendorOrgCode, 0, "").GetStoreList(param); err != nil || len(stores) == 0 {
		return nil, errors.New(fmt.Sprintf("暂时无门店数据返回，请重试:%v", err))
	} else {
		return stores, err
	}
}

func (P *PurchaseHandler) UpdateStoreLineStatus(ctx *jxcontext.Context, vendorOrgCode string, storeID int, vendorStoreID string, lineStatus int) (err error) {
	a := getAPI(vendorOrgCode, storeID, vendorStoreID)
	if lineStatus == model.StoreStatusOpened {
		_, err = a.UnsuspendStore(&shop_unsuspendStore_request.ShopUnsuspendStoreParam{
			StoreId: utils.Str2Int64(vendorStoreID),
		})
	} else {
		_, err = a.StoreSuspend(&shop_storeSuspend_request.ShopStoreSuspendParam{
			StoreId: utils.Str2Int64(vendorStoreID),
		})
	}
	return err
}
func (P *PurchaseHandler) ReadStore(ctx *jxcontext.Context, vendorOrgCode, vendorStoreID, vendorStoreName string) (store *dao.StoreDetail, err error) {
	a := getAPI(vendorOrgCode, 0, "")
	vendorStore, err := a.GetStoreDetail(&shop_getStoreDetail_request.ShopGetStoreDetailParam{StoreId: vendorStoreID})
	if err != nil {
		return nil, err
	}
	retVal := &dao.StoreDetail{
		Store: model.Store{
			Address: vendorStore.StoreDetail.Store.Address,
			Tel1:    vendorStore.StoreDetail.Store.Contact,
		},
	}
	//获取自动运力设置
	autoInfo, err := a.GetStoreAutoCallRiderInfo(utils.Str2Int64(vendorStoreID))
	if err == nil {
		if autoInfo.ServiceStatus == tiktok_api.ServiceStatusOpen {
			retVal.YbAppID = tiktok_api.AutoCallRiderOpen
		} else {
			retVal.YbAppID = tiktok_api.AutoCallRiderClose
		}
	}
	//获取门店限售模板即起送价
	saleLimit, err := a.StoreQuerySaleLimitTemp(utils.Str2Int64(vendorStoreID))
	if err != nil {
		retVal.YbStorePrefix = "0"
	} else {
		saleDetail, err := a.GetSaleLimitDetail(&[]int64{saleLimit})
		if err != nil {
			retVal.YbStorePrefix = "0"
		} else {
			if len(saleDetail.TradeLimitTemplateList) > 0 && len(saleDetail.TradeLimitTemplateList[0].TradeLimitRuleList) > 0 {
				if saleDetail.TradeLimitTemplateList[0].TradeLimitRuleList[0].TradeLimitModel == tiktok_api.TradeLimitModelMoney {
					retVal.YbStorePrefix = utils.Int64ToStr(saleDetail.TradeLimitTemplateList[0].TradeLimitRuleList[0].TradeLimitPattern.Minimum * 100)
				}
			} else {
				retVal.YbStorePrefix = "0"
			}
		}
	}
	//获取满减包邮金额
	freightIDs, err := a.GetStoreFreight(utils.Str2Int64(vendorStoreID))
	if err != nil || len(freightIDs) == 0 || freightIDs[0] == 0 {
		retVal.DeliveryFeeDeductionSill = 0
	} else {
		freightDetail, err := a.GetStoreFreightDetail(freightIDs[0])
		if err == nil && len(freightDetail.Columns) > 0 {
			retVal.DeliveryFeeDeductionSill = int(freightDetail.Columns[0].OverAmount * 100)
		} else {
			retVal.DeliveryFeeDeductionSill = 0
		}
	}
	//获取打包费
	packageFee, err := a.GetStorePackageFee(utils.Str2Int64(vendorStoreID))
	if err != nil {
		retVal.DeliveryFeeDeductionFee = 0
	} else {
		retVal.DeliveryFeeDeductionFee = int(packageFee * 100)
	}
	retVal.OriginalName = vendorStore.StoreDetail.Store.Name
	_, retVal.Name = jxutils.SplitStoreName(retVal.OriginalName, partner.StoreNameSeparator, globals.StoreNameTiktok)
	if len(vendorStore.StoreDetail.Store.OpenTime.DayMap) != 0 {
		retVal.SetTiktokOpenTime(vendorStore.StoreDetail.Store.OpenTime.DayMap[1])
	}
	retVal.Status = bizStatusTiktok2JX(vendorStore.StoreDetail.Store.State)
	retVal.Lng = int(utils.Str2Float64(vendorStore.StoreDetail.Store.Longitude) * 1000000)
	retVal.Lat = int(utils.Str2Float64(vendorStore.StoreDetail.Store.Latitude) * 1000000)
	lng := jxutils.IntCoordinate2Standard(retVal.Lng)
	lat := jxutils.IntCoordinate2Standard(retVal.Lat)
	db := dao.GetDB()
	retVal.DistrictCode = api.TencentMapAPI.GetCoordinateDistrictCode(lng, lat)
	city, err := dao.GetPlaceByCode(db, utils.Str2Int(vendorStore.StoreDetail.Store.CityCode))
	retVal.CityName = city.Name
	retVal.CityCode = utils.Str2Int(vendorStore.StoreDetail.Store.CityCode)
	poiCode := vendorStore.StoreDetail.Store.StoreCode
	retVal.VendorStoreID = vendorStoreID
	retVal.ID = utils.Str2Int(poiCode)
	retVal.DeliveryRangeType = model.DeliveryRangeTypeRadius
	retVal.DeliveryRange = "3000"
	retVal.DeliveryType = scheduler.StoreDeliveryTypeByStore
	return retVal, nil
}

//设置门店打包费
func SetStorePackageFee(vendorOrgCode string, vendorStoreID, packageFee int64) error {
	if err := getAPI(vendorOrgCode, 0, "").SetStorePackageFee(vendorStoreID, packageFee); err != nil {
		return err
	}
	return nil
}

func (P *PurchaseHandler) RefreshAllStoresID(ctx *jxcontext.Context, parentTask tasksch.ITask, isAsync bool) (hint string, err error) {
	return "", errors.New("抖店暂不支持此操作")
}

func bizStatusJX2DouDian(status int) (onLine int) {
	if status == model.StoreStatusDisabled || status == model.StoreStatusClosed || status == model.StoreStatusHaveRest {
		return tiktok_api.StoreStatusOffline
	}
	return tiktok_api.StoreStatusOnline
}

func (P *PurchaseHandler) DeleteStore(db *dao.DaoDB, storeID int, userName string) (err error) {
	return errors.New("抖店暂不支持此操作")
}

func (P *PurchaseHandler) UpdateStoreCustomID(ctx *jxcontext.Context, vendorOrgCode, vendorStoreID string, storeID int64) (err error) {
	return err
}

func (P *PurchaseHandler) GetOrderStatus(vendorOrgCode, vendorOrderID string) (status int, err error) {
	return 0, errors.New("抖店暂不支持此操作")
}

func (p *PurchaseHandler) GetSkus(ctx *jxcontext.Context, vendorOrgCode string, skuID int, vendorSkuID string) (skuNameList []*partner.SkuNameInfo, err error) {
	return nil, err
}

type RemoteSth struct {
	YbAppID                  string `json:"ybAppID"`                  //自动运力设置 open/close
	YbStorePrefix            string `json:"ybStorePrefix"`            //限售模板即起送价
	DeliveryFeeDeductionSill int    `json:"deliveryFeeDeductionSill"` //在vendorID=14,存储满 x 包邮金额
	DeliveryFeeDeductionFee  int    `json:"deliveryFeeDeductionFee"`  //在vendorID=14,存储打包费
}

//获取抖音线上 自动运力设置，满减包邮金额，起送价(限售)，打包费
func GetRemoteStoreSth(vendorOrgCode, vendorStoreID string, storeID int) *RemoteSth {
	remoteSth := &RemoteSth{}
	a := getAPI(vendorOrgCode, 0, "")
	//获取自动运力设置
	autoInfo, err := a.GetStoreAutoCallRiderInfo(utils.Str2Int64(vendorStoreID))
	if err == nil {
		if autoInfo.ServiceStatus == tiktok_api.ServiceStatusOpen {
			remoteSth.YbAppID = tiktok_api.AutoCallRiderOpen
		} else {
			remoteSth.YbAppID = tiktok_api.AutoCallRiderClose
		}
	}
	//获取门店限售模板即起送价
	saleLimit, err := a.StoreQuerySaleLimitTemp(utils.Str2Int64(vendorStoreID))
	if err != nil {
		remoteSth.YbStorePrefix = "0"
	} else {
		saleDetail, err := a.GetSaleLimitDetail(&[]int64{saleLimit})
		if err != nil {
			remoteSth.YbStorePrefix = "0"
		} else {
			if len(saleDetail.TradeLimitTemplateList) > 0 && len(saleDetail.TradeLimitTemplateList[0].TradeLimitRuleList) > 0 {
				if saleDetail.TradeLimitTemplateList[0].TradeLimitRuleList[0].TradeLimitModel == tiktok_api.TradeLimitModelMoney {
					remoteSth.YbStorePrefix = utils.Int64ToStr(saleDetail.TradeLimitTemplateList[0].TradeLimitRuleList[0].TradeLimitPattern.Minimum)
				}
			} else {
				remoteSth.YbStorePrefix = "0"
			}
		}
	}
	//获取满减包邮金额
	freightIDs, err := a.GetStoreFreight(utils.Str2Int64(vendorStoreID))
	if err != nil || len(freightIDs) == 0 || freightIDs[0] == 0 {
		remoteSth.DeliveryFeeDeductionSill = 0
	} else {
		freightDetail, err := a.GetStoreFreightDetail(freightIDs[0])
		if err == nil && len(freightDetail.Columns) > 0 {
			remoteSth.DeliveryFeeDeductionSill = int(freightDetail.Columns[0].OverAmount)
		} else {
			remoteSth.DeliveryFeeDeductionSill = 0
		}
	}
	//获取打包费
	packageFee, err := a.GetStorePackageFee(utils.Str2Int64(vendorStoreID))
	if err != nil {
		remoteSth.DeliveryFeeDeductionFee = 0
	} else {
		remoteSth.DeliveryFeeDeductionFee = int(packageFee)
	}
	//更新本地数据库
	/*	remoteSth = &RemoteSth{
		DeliveryFeeDeductionFee:  9999,
		DeliveryFeeDeductionSill: 9999,
		YbStorePrefix:            "test111",
		YbAppID:                  "test111",
	}*/
	var storeMaps []*model.StoreMap
	cond := map[string]interface{}{
		model.FieldStoreID:  storeID,
		model.FieldVendorID: model.VendorIDDD,
	}
	if err1 := dao.GetEntitiesByKV(dao.GetDB(), &storeMaps, cond, false); err1 == nil {
		storeMaps[0].YbAppID = remoteSth.YbAppID
		storeMaps[0].YbStorePrefix = remoteSth.YbStorePrefix
		storeMaps[0].DeliveryFeeDeductionSill = remoteSth.DeliveryFeeDeductionSill
		storeMaps[0].DeliveryFeeDeductionFee = remoteSth.DeliveryFeeDeductionFee
		if _, err2 := dao.UpdateEntity(dao.GetDB(), storeMaps[0]); err2 != nil {
			globals.SugarLogger.Debug(err2)
		}
	}
	return remoteSth
}

//以下为辅助函数

type RelInfo struct {
	StoreID       string `json:"storeID"`
	VendorStoreID string `json:"vendorStoreID"`
}

func ToStringSlice(actual interface{}) ([]string, error) {
	var res []string
	value := reflect.ValueOf(actual)
	if value.Kind() != reflect.Slice || value.Kind() != reflect.Array {
		return nil, errors.New("parse error")
	}
	for i := 0; i < value.Len(); i++ {
		res = append(res, value.Index(i).Interface().(string))
	}
	return res, nil
}

//直辖市判断
func HandleMunicipality(cityName string) (bool, int64) {
	if cityName == tiktok_api.MunicipalityBeiJin || cityName == tiktok_api.MunicipalityShangHai || cityName == tiktok_api.MunicipalityTianJin || cityName == tiktok_api.MunicipalityChongQing {
		return true, int64(tiktok_api.MunicipalityCode[cityName])
	}
	return false, 0
}

//判断门店是否审核通过
func IfAuditPass(vendorOrgCode string, vendorStoreID int64) bool {
	if remoteStore, err := getAPI(vendorOrgCode, 0, " ").GetStoreDetail(&shop_getStoreDetail_request.ShopGetStoreDetailParam{
		StoreId: utils.Int64ToStr(vendorStoreID),
	}); err == nil {
		if remoteStore.StoreDetail.Store.PoiAuditState != tiktok_api.PoiAuditStateSuccessBind || remoteStore.StoreDetail.Store.State != tiktok_api.StoreStateSuccessBind || remoteStore.StoreDetail.Store.QualState != tiktok_api.QualStateCheckingPassed || remoteStore.StoreDetail.Store.RemitState != tiktok_api.RemitStateCheckingPassed || remoteStore.StoreDetail.Store.OpenAccountState != tiktok_api.OpenAccountStateOpen {
			return true
		}
	}
	return false
}

//判断门店信息是否需要修改
func IsNeedStoreUpdate(lStore *dao.StoreDetail, storeID string) bool {
	if remoteStore, err := getAPI(lStore.VendorOrgCode, 0, "").GetStoreDetail(&shop_getStoreDetail_request.ShopGetStoreDetailParam{
		StoreId:            storeID,
		IsNeedPoiAuditInfo: false,
		IsNeedRelShopUser:  false,
		IsNeedChargeInfo:   false,
	}); err == nil {
		rStore := remoteStore.StoreDetail.Store
		if lStore.Tel1 != rStore.Contact || lStore.Name != rStore.Name || lStore.Address != rStore.Address {
			return true
		}
		if lStore.ProvinceName != rStore.Province || lStore.CityName != rStore.City || lStore.DistrictName != rStore.District {
			return true
		}
		if utils.Float64ToStr(jxutils.IntCoordinate2Standard(lStore.Lat)) != rStore.Latitude || utils.Float64ToStr(jxutils.IntCoordinate2Standard(lStore.Lng)) != rStore.Longitude {
			return true
		}
		timeStr := ""
		if lStore.OpenTime1 != 0 && lStore.CloseTime1 != 0 {
			if lStore.OpenTime2 != 0 && lStore.CloseTime2 != 0 {
				timeStr = SplicingTimeToDoudian(lStore.OpenTime1, lStore.CloseTime1, lStore.OpenTime2, lStore.CloseTime2, true)
			} else {
				timeStr = SplicingTimeToDoudian(lStore.OpenTime1, lStore.CloseTime1, 0, 0, false)
			}
		}
		if timeStr != rStore.OpenTime.DayMap[1] {
			return true
		}
	}
	return false
}
