package tiktok_store

import (
	"errors"
	"fmt"
	instantShopping_getDeliveryListByOrderId_response "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/instantShopping_getDeliveryListByOrderId/response"
	"time"

	superm_getStoreAutoCallRiderInfo_response "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/superm_getStoreAutoCallRiderInfo/response"
	superm_setStoreAutoCallRider_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/superm_setStoreAutoCallRider/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/model"
	"git.rosy.net.cn/jx-callback/business/model/dao"
	"git.rosy.net.cn/jx-callback/business/partner"
)

var (
	VendorWaybillStatus2StatusMap = map[int]int{
		tiktok_api.ShipmentStatusCalling:    model.WaybillStatusNew,
		tiktok_api.ShipmentStatusReceived:   model.WaybillStatusAccepted,
		tiktok_api.ShipmentStatusArrived:    model.WaybillStatusCourierArrived,
		tiktok_api.ShipmentStatusDelivering: model.WaybillStatusDelivering,
		tiktok_api.ShipmentStatusRejected:   model.WaybillStatusRejected,
		tiktok_api.ShipmentStatusReturning:  model.WaybillStatusReturning,
		tiktok_api.ShipmentStatusReturned:   model.WaybillStatusReturned,
		tiktok_api.ShipmentStatusDelivered:  model.WaybillStatusDelivered,
		tiktok_api.ShipmentStatusCanceled:   model.WaybillStatusCanceled,
	}
)

func (p *PurchaseHandler) GetWaybillStatusFromVendorStatus(vendorStatus string) int {
	if status, ok := VendorWaybillStatus2StatusMap[utils.Str2Int(vendorStatus)]; ok {
		return status
	}
	return model.WaybillStatusUnknown
}

func (c *PurchaseHandler) onWaybillMsg(tag, orderId string, data interface{}) *tiktok_api.CallbackResponse {
	waybill := c.callbackMsg2Waybill(tag, orderId, data)
	localOrder, _ := partner.CurOrderManager.LoadOrder(waybill.VendorOrderID, model.VendorIDDD)
	// 当前订单的运力状态发生变化时，抖店侧会对open侧推送消息。当前运力状态变化的原因有两个来源：1：呼叫平台运力，平台运力有变化，此时会推送消息；2：商家自配，erp通过回传配送状态触发运力状态变化，此时也会推送消息
	// 问题：当前两种消息来源是没有区分的，都是统一发送消息，但erp侧针对不同的情况有特殊处理，因此需要区分这两种消息
	// 当本地记录骑手数据(非抖音平台运单)与当前运单匹配上是,就直接返回
	if waybill.CourierName != "" && waybill.CourierMobile != "" {
		localWaybill, _ := dao.GetWaybills(dao.GetDB(), localOrder.VendorOrderID, nil)
		for _, v := range localWaybill {
			if v.CourierName != "" && v.CourierMobile != "" && v.WaybillVendorID != model.VendorIDDD && v.CourierName == waybill.CourierName && v.CourierMobile == waybill.CourierMobile {
				return tiktok_api.Err2CallbackResponse(nil, "")
			}
		}
	}
	err := partner.CurOrderManager.OnWaybillStatusChanged(waybill)
	if err == nil {
		status := &model.OrderStatus{
			VendorOrderID:    waybill.VendorOrderID,
			VendorID:         model.VendorIDDD,
			OrderType:        model.OrderTypeWaybill,
			RefVendorOrderID: waybill.VendorOrderID,
			RefVendorID:      model.VendorIDDD,
			Status:           waybill.Status,
			VendorStatus:     waybill.VendorStatus,
			StatusTime:       time.Now(),
			DuplicatedCount:  0,
			Remark:           "",
			ModelTimeInfo: model.ModelTimeInfo{
				CreatedAt: time.Now(),
				UpdatedAt: time.Now(),
			},
		}
		err = partner.CurOrderManager.OnOrderStatusChanged(localOrder.VendorOrgCode, status)
		if err != nil {
			partner.CurOrderManager.OnOrderMsg(localOrder, "", "抖店运单骑手状态修改异常:"+err.Error())
		}
		if status.VendorStatus == utils.Int2Str(tiktok_api.ShipmentStatusCanceled) {
			localOrder.Status = model.WaybillStatusCourierArrived
			dao.UpdateEntity(dao.GetDB(), localOrder, "Status")
		}
	}
	return tiktok_api.Err2CallbackResponse(err, "")
}

func (c *PurchaseHandler) callbackMsg2Waybill(tag, orderId string, data interface{}) (retVal *model.Waybill) {
	req := data.(tiktok_api.ShipmentInfoData)
	tempRemark := ""
	if req.Status == tiktok_api.ShipmentStatusReceived {
		tempRemark = req.RiderName + "," + req.RiderPhone
	}
	way := &model.Waybill{
		VendorOrderID:   utils.Int64ToStr(req.ShopOrderID),
		OrderVendorID:   model.VendorIDDD,
		VendorWaybillID: utils.Int64ToStr(req.ShopOrderID),
		WaybillVendorID: model.VendorIDDD,
		CourierName:     req.RiderName,
		CourierMobile:   req.RiderPhone,
		VendorStatus:    utils.Int64ToStr(req.Status),
		Status:          c.GetWaybillStatusFromVendorStatus(utils.Int64ToStr(req.Status)),
		StatusTime:      utils.Str2Time(req.OperateTime),
		Remark:          tempRemark,
		VendorOrgCode:   utils.Int64ToStr(req.ShopID), //为抖音账号ID
	}
	return way
}

//设置自动呼叫运力
func SetStoreAutoCallRider(vendorOrgCode, opType string, storeID int64) error {
	if opType == tiktok_api.AutoCallRiderOpen {
		if err := getAPI(vendorOrgCode, 0, "").SetStoreAutoCallRider(&superm_setStoreAutoCallRider_request.SupermSetStoreAutoCallRiderParam{
			StoreID:     storeID,
			OpType:      opType,
			ServiceType: tiktok_api.ServiceTypeDelayCall,
			DelayTime:   tiktok_api.AutoCallDelayTime15,
		}); err != nil {
			return err
		}
	} else {
		if err := getAPI(vendorOrgCode, 0, "").SetStoreAutoCallRider(&superm_setStoreAutoCallRider_request.SupermSetStoreAutoCallRiderParam{
			StoreID: storeID,
			OpType:  opType,
		}); err != nil {
			return err
		}
	}
	return nil
}

//批量查询自动呼叫运力配置
func GetStoreAutoCallRiderInfo(vendorOrgCode string, storeIDs []int64) (map[int64]*superm_getStoreAutoCallRiderInfo_response.AutoCallInfo, error) {
	if len(storeIDs) == 0 {
		return nil, errors.New("门店ID为空，请检查")
	}
	errList := errlist.ErrList{}
	tAutoCallInfos := make(map[int64]*superm_getStoreAutoCallRiderInfo_response.AutoCallInfo, 0)
	for _, i := range storeIDs {
		if autoCallInfo, err := getAPI(vendorOrgCode, 0, "").GetStoreAutoCallRiderInfo(i); err != nil {
			errList.AddErr(err)
		} else {
			tAutoCallInfos[i] = &superm_getStoreAutoCallRiderInfo_response.AutoCallInfo{
				ServiceStatus: autoCallInfo.ServiceStatus,
				ServiceType:   autoCallInfo.ServiceType,
				DelayTime:     autoCallInfo.DelayTime,
			}
		}
	}
	if errList.GetErrListAsOne() != nil {
		return nil, errList.GetErrListAsOne()
	}
	return tAutoCallInfos, nil
}

//取消自动运力
func (c *PurchaseHandler) CancelWaybill(bill *model.Waybill, cancelReasonID int, cancelReason string) (err error) {
	params := make(map[string]interface{}, 0)
	params["vendorOrderID"] = bill.VendorOrderID
	if localOrder, _, err := dao.GetOrders(dao.GetDB(), nil, false, false, "", "", false, []int{0}, false, "", params, 0, 0); err != nil {
		return errors.New("取消运单时，获取平台门店ID失败，请重试")
	} else {
		if err = getAPI(bill.VendorOrgCode, 0, "").ShopOrderDispatcher(utils.Str2Int64(localOrder[0].VendorStoreID), bill.VendorOrderID, tiktok_api.DispatcherFeeTypeCancel); err != nil {
			return fmt.Errorf("抖音配送取消运力失败:%v", err)
		}
		bill.Status = model.WaybillStatusCanceled
		bill.Remark = cancelReason
		partner.CurOrderManager.OnWaybillStatusChanged(bill)
	}
	return err
}

//查询运力状态
func (c *PurchaseHandler) GetDYPSRiderInfo(orderId string) (*instantShopping_getDeliveryListByOrderId_response.InstantShoppingGetDeliveryListByOrderIdData, error) {
	params := map[string]interface{}{
		"vendorOrderID": orderId,
	}
	orderInfo, _, err := dao.GetOrders(dao.GetDB(), nil, false, false, "", "", false, nil, false, "", params, 0, 0)
	if err != nil {
		return nil, errors.New("获取本地门店账号信息失败，请重试")
	}

	waybill, err := getAPI(orderInfo[0].VendorOrgCode, 0, "").GetShipmentInfo(utils.Str2Int64(orderId), 0, tiktok_api.ShipmentTypeInvoice)
	if err != nil {
		return nil, err
	}

	return waybill, nil
}
