package mtps

import (
	"git.rosy.net.cn/baseapi/platformapi/mtpsapi"
	"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"
)

const (
	fakeContactEmail = "fakeemail@163.com"
)

var (
	auditStatusMap = map[int]int{
		mtpsapi.ShopStatusAuditCreated:        model.StoreAuditStatusCreated,
		mtpsapi.ShopStatusAuditRejected:       model.StoreAuditStatusRejected,
		mtpsapi.ShopStatusAuditPassed:         model.StoreAuditStatusCreated,
		mtpsapi.ShopStatusAuditOnline:         model.StoreAuditStatusOnline,
		mtpsapi.ShopStatusAuditUpdatePassed:   model.StoreAuditStatusOnline,
		mtpsapi.ShopStatusAuditUpdateRejected: model.StoreAuditStatusRejected,
	}
)

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

func OnStoreStatus(msg *mtpsapi.CallbackShopStatusMsg) (retVal *mtpsapi.CallbackResponse) {
	return curDeliveryHandler.OnStoreStatus(msg)
}

func (c *DeliveryHandler) OnStoreStatus(msg *mtpsapi.CallbackShopStatusMsg) (retVal *mtpsapi.CallbackResponse) {
	err := partner.CurStoreManager.OnCourierStoreStatusChanged(jxcontext.AdminCtx, msg.ShopID, model.VendorIDMTPS, getAuditStatus(msg.Status), msg.RejectMessage)
	retVal = mtpsapi.Err2CallbackResponse(err, "mtps OnStoreStatus")
	return retVal
}

func (c *DeliveryHandler) CreateStore(ctx *jxcontext.Context, storeDetail *dao.StoreDetail2) (vendorStoreID string, status int, err error) {
	if globals.EnableStoreWrite {
		businessHours := []*mtpsapi.BusinessHour{
			&mtpsapi.BusinessHour{
				BeginTime: "06:00",
				EndTime:   "22:00",
			},
		}
		shopInfo := &mtpsapi.ShopInfo{
			ShopID:               storeDetail.VendorStoreID,
			ShopName:             storeDetail.Name,
			Category:             mtpsapi.ShopCategoryFruit,
			SecondCategory:       mtpsapi.ShopCategoryFruitFruit,
			ContactName:          storeDetail.PayeeName,
			ContactPhone:         storeDetail.Tel1,
			ContactEmail:         fakeContactEmail,
			ShopAddress:          storeDetail.Address,
			ShopLng:              storeDetail.Lng,
			ShopLat:              storeDetail.Lat,
			CoordinateType:       mtpsapi.CoordinateTypeMars,
			BusinessHours:        string(utils.MustMarshal(businessHours)),
			DeliveryServiceCodes: utils.Int2Str(mtpsapi.DeliveryServiceCodeRapid),
		}
		shopStatus := mtpsapi.ShopStatusAuditCreated
		if shopInfo.ShopLat <= 9999999 {
			shopInfo.ShopLat *= 10
		}

		if globals.EnableStoreWrite {
			shopStatus, err = api.MtpsAPI.ShopCreate(shopInfo)
			if err == nil {
				vendorStoreID = shopInfo.ShopID
				status = getAuditStatus(shopStatus)
			}
		} else {
			vendorStoreID = utils.Int64ToStr(jxutils.GenFakeID())
			status = model.StoreAuditStatusOnline
		}
	}
	return vendorStoreID, status, err
}

func (c *DeliveryHandler) GetStore(ctx *jxcontext.Context, storeID int, vendorStoreID string) (storeDetail *dao.StoreDetail2, err error) {
	shopInfo, err := api.MtpsAPI.ShopQuery(vendorStoreID)
	if err == nil {
		storeDetail = &dao.StoreDetail2{
			Store: model.Store{
				Name:      shopInfo.ShopName,
				CityCode:  shopInfo.City,
				PayeeName: shopInfo.ContactName,
				Tel1:      shopInfo.ContactPhone,
				Address:   shopInfo.ShopAddress,
				Lng:       shopInfo.ShopLng,
				Lat:       shopInfo.ShopLat,
			},
			VendorID:      model.VendorIDMTPS,
			VendorStoreID: shopInfo.ShopID,
			// CourierStatus: model.StoreStatusOpened,
			// AuditStatus:   model.StoreAuditStatusOnline,
		}

		//_, _, err = api.MtpsAPI.PreCreateByShop(&mtpsapi.PreCreateByShopParam{
		//	DeliveryID:           time.Now().Unix(),
		//	OrderID:              utils.Int2Str(int(time.Now().Unix() + 200)),
		//	ShopID:               shopInfo.ShopID,
		//	DeliveryServiceCode:  mtpsapi.DeliveryServiceCodeRapid,
		//	ReceiverName:         "test发单",
		//	ReceiverAddress:      shopInfo.ShopAddress,
		//	ReceiverPhone:        shopInfo.ContactPhone,
		//	ReceiverLng:          shopInfo.ShopLng,
		//	ReceiverLat:          shopInfo.ShopLat,
		//	GoodsValue:           10 / 100,
		//	GoodsWeight:          0, // 系统重量转换为千克
		//	PayTypeCode:          0,
		//	ExpectedDeliveryTime: mtpsapi.DeliveryServiceCodeRapid, // 4002飞速达,4011快速达,4012及时达,4013集中送
		//	OuterOrderSourceDesc: "101",
		//})
		//shopInfo.ShopLng = 121345878
		//shopInfo.ShopLat = 3115628
		//_, err = api.MtpsAPI.CheckOrder(shopInfo.ShopID, shopInfo.ShopAddress, int64(shopInfo.ShopLng), int64(shopInfo.ShopLat), time.Now().Unix())
		//result, err := api.MtpsAPI.GetStoreStatus(shopInfo.ShopName)
		//if err == nil {
		//	storeDetail.AuditStatus = mtpsOpenTypeToJx(result.DataList[0].OpenType)
		//	storeDetail.CourierStatus = mtpsOpenTypeToJx2(result.DataList[0].OpenType)
		//}
		//if mtpsapi.IsOpen(err) {
		storeDetail.AuditStatus = model.StoreAuditStatusOnline // 0
		storeDetail.CourierStatus = model.StoreStatusOpened    // 1
		//} else {
		//	storeDetail.AuditStatus = model.StoreAuditStatusRejected // -1
		//	storeDetail.CourierStatus = model.StoreStatusClosed      // -1
		//}
		err = nil
	}
	return storeDetail, err
}

func mtpsOpenTypeToJx(openType int) (status int) {
	if openType == 0 {
		status = model.StoreAuditStatusRejected
	} else {
		status = model.StoreAuditStatusOnline
	}
	return status
}

func mtpsOpenTypeToJx2(openType int) (status int) {
	if openType == 0 {
		status = model.StoreStatusClosed
	} else {
		status = model.StoreStatusOpened
	}
	return status
}

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

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

func (c *DeliveryHandler) UpdateStore(ctx *jxcontext.Context, storeDetail *dao.StoreDetail2) (err error) {
	if globals.EnableStoreWrite {
		shopInfo := &mtpsapi.ShopInfo{
			ShopID:       utils.Int2Str(storeDetail.ID),
			ContactName:  storeDetail.PayeeName,
			ContactPhone: storeDetail.Tel1,
			ShopAddress:  storeDetail.Address,
			ShopLat:      storeDetail.Lat,
			ShopLng:      storeDetail.Lng,
			ShopName:     storeDetail.Name,
		}
		_, err = api.MtpsAPI.ShopUpdate(shopInfo)
	}
	return err
}
