package fn

import (
	"git.rosy.net.cn/baseapi/platformapi/fnpsapi"
	"git.rosy.net.cn/baseapi/utils"
	"git.rosy.net.cn/jx-callback/business/jxutils"
	"git.rosy.net.cn/jx-callback/business/jxutils/jxcontext"
	"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"
	beego "github.com/astaxie/beego/server/web"
)

var (
	auditStatusMap = map[int]int{
		// 创建
		fnpsapi.ShopCreateStatusAuditRejected:       model.StoreAuditStatusCreated,
		fnpsapi.ShopCreateStatusAuditPassed:         model.StoreAuditStatusRejected,
		fnpsapi.ShopCreateStatusAuditCreated:        model.StoreAuditStatusCreated,
		fnpsapi.ShopCreateStatusAuditOnline:         model.StoreAuditStatusOnline,
		fnpsapi.ShopCreateStatusAuditUpdateRejected: model.StoreAuditStatusOnline,

		// 修改
		fnpsapi.ShopUpdateStatusAuditRejected: model.StoreAuditStatusCreated,
	}
)

func getAuditStatus(vendorAuditStatus int) int {
	if auditStatus, ok := auditStatusMap[vendorAuditStatus]; ok {
		return auditStatus
	}
	return model.StoreAuditStatusCreated
}

func (c *DeliveryHandler) CreateStore(ctx *jxcontext.Context, storeDetail *dao.StoreDetail2) (vendorStoreID string, status int, err error) {
	// 获取品牌名称
	brandInfo, err := dao.GetBrands(dao.GetDB(), "", storeDetail.BrandID, "", false, "")
	if err != nil {
		return "", 0, err
	}
	createStore := &fnpsapi.CreateStoreBaseInfo{
		ContactPhone:           storeDetail.Tel1,
		Address:                storeDetail.Address,
		Longitude:              jxutils.IntCoordinate2Standard(storeDetail.Lng),
		Latitude:               jxutils.IntCoordinate2Standard(storeDetail.Lat),
		PositionSource:         3,
		OutShopCode:            utils.Int2Str(storeDetail.ID),
		CategoryID:             "51",
		OwnerName:              storeDetail.IDName,
		OwnerIDNum:             storeDetail.IDCode,
		HandheldLicencePicHash: "暂不需要(手持身份证、营业执照图片)",
		OwnerIDPicFrontHash:    "暂不需要(省份证正)",
		OwnerIDPicBackHash:     "暂不需要(身份证反)",
		CreditCode:             storeDetail.LicenceCode,
		ChainstoreType:         1,
		BusinessLicencePicHash: storeDetail.Licence,
	}
	if createStore.OwnerName == "" {
		createStore.OwnerName = model.DefaultName
	}
	if createStore.OwnerIDNum == "" {
		createStore.OwnerIDNum = "610126198012230014"
	}
	createStore.BranchShopName = storeDetail.Name
	createStore.HeadShopName = brandInfo[0].Name + "-" + storeDetail.Name

	fnShopId, err := api.FnAPI.CreateStore(createStore)
	if err != nil {
		return "", 0, err
	}

	return fnShopId, status, err
}

func shopStatus2JX(status int) (jxStatus int) {
	if status == 1 {
		return 0
	} else {
		return 1
	}
}

func (c *DeliveryHandler) GetStore(ctx *jxcontext.Context, storeID int, vendorStoreID string) (storeDetail *dao.StoreDetail2, err error) {
	shopInfo, err := api.FnAPI.GetStore(vendorStoreID)
	if err == nil {
		storeDetail = &dao.StoreDetail2{
			Store: model.Store{
				Name:    shopInfo.Name,
				Tel1:    shopInfo.ContactPhone,
				Address: shopInfo.Address,
				Lng:     jxutils.StandardCoordinate2Int(shopInfo.Longitude),
				Lat:     jxutils.StandardCoordinate2Int(shopInfo.Latitude),
			},
			VendorID:      model.VendorIDFengNiao,
			VendorStoreID: string(shopInfo.ChainStoreID),
			CourierStatus: shopStatus2JX(shopInfo.Status),
		}
	}
	return storeDetail, err
}

func (c *DeliveryHandler) IsErrStoreExist(err error) bool {
	return fnpsapi.IsErrShopExist(err)
}

func (c *DeliveryHandler) IsErrStoreNotExist(err error) bool {
	return fnpsapi.IsErrShopNotExist(err)
}

func (c *DeliveryHandler) UpdateStore(ctx *jxcontext.Context, storeDetail *dao.StoreDetail2) (err error) {
	// 获取蜂鸟门店id
	fnStore, err := api.FnAPI.GetStore(storeDetail.VendorStoreID)
	if err != nil {
		return err
	}

	updateStore := &fnpsapi.UpdateStoreParam{
		ChainStoreID:           fnStore.ChainStoreID,
		ContactPhone:           storeDetail.Tel1,
		Address:                storeDetail.Address,
		Longitude:              jxutils.IntCoordinate2Standard(storeDetail.Lng),
		Latitude:               jxutils.IntCoordinate2Standard(storeDetail.Lat),
		PositionSource:         3,
		OutShopCode:            utils.Int2Str(storeDetail.ID),
		CategoryID:             "51",
		OwnerName:              storeDetail.IDName,
		OwnerIDNum:             storeDetail.IDCode,
		HandheldLicencePicHash: "暂不需要(手持身份证、营业执照图片)",
		OwnerIDPicFrontHash:    "暂不需要(省份证正)",
		OwnerIDPicBackHash:     "暂不需要(身份证反)",
		CreditCode:             storeDetail.LicenceCode,
		BusinessLicencePicHash: storeDetail.Licence,
	}
	if storeDetail.Name != fnStore.Name {
		updateStore.HeadShopName = storeDetail.Name
		updateStore.BranchShopName = storeDetail.Name
	}
	if updateStore.OwnerName == "" {
		updateStore.OwnerName = model.DefaultName
	}
	if updateStore.OwnerIDNum == "" {
		updateStore.OwnerIDNum = "610126198012230014"
	}

	return api.FnAPI.UpdateStore(updateStore)
}

// 蜂鸟门店状态改变
func OnStoreStatus(msg *fnpsapi.ChainstoreStatusNotify, reallyData *fnpsapi.ShortStatus) (retVal *fnpsapi.CallbackResponse) {
	store, err := dao.GetStoreDetail2(dao.GetDB(), 0, msg.Param.OutShopCode, model.VendorIDFengNiao)
	if store == nil || store.ID == model.NO || err != nil {
		if _, err = fnpsapi.HttpToGuoYuanFN(utils.Struct2MapByJson(reallyData), fnpsapi.FengNiaoCallbackTypeStore, beego.BConfig.RunMode); err != nil {
			return fnpsapi.Err2CallbackResponse(err, "")
		}
		return fnpsapi.Err2CallbackResponse(nil, "")
	}
	return CurDeliveryHandler.OnStoreStatus(msg)
}

// 修改本地门店审核状态
func (c *DeliveryHandler) OnStoreStatus(msg *fnpsapi.ChainstoreStatusNotify) (retVal *fnpsapi.CallbackResponse) {
	var status int = 0
	switch msg.CallbackBusinessType {
	case "chainstoreStatusNotify": // 门店状态
		if msg.Param.Status != "" {
			status = int(utils.ForceInterface2Int64(msg.Param.Status)) // 10-上架审核中,20-正常(已上架), 30-上架审核失败,40-已冻结,50-已下架
		} else {
			status = int(utils.ForceInterface2Int64(msg.Param.ModifyStatus)) // 0-无修改,10-资料修改审核中, 20-审核通过,30-审核驳回
		}
	case "chainstoreServiceStatusNotify": // 配送范围变更回调
		status = 20
	}

	err := partner.CurStoreManager.OnCourierStoreStatusChanged(
		jxcontext.AdminCtx,
		utils.Interface2String(msg.Param.OutShopCode),
		model.VendorIDFengNiao,
		getAuditStatus(status),
		utils.Interface2String(msg.Param.Remark),
	)

	if err != nil {
		globals.SugarLogger.Debugf("FNPS OnStoreStatus callback fail :[%s]", err)
	}

	retVal = fnpsapi.Err2CallbackResponse(err, "fn ps OnStoreStatus")
	return retVal
}
