package tao_vegetable

import (
	"fmt"
	"git.rosy.net.cn/baseapi/platformapi/tao_vegetable"
	domain3156 "git.rosy.net.cn/baseapi/platformapi/tao_vegetable/sdk/ability3156/domain"
	request3156 "git.rosy.net.cn/baseapi/platformapi/tao_vegetable/sdk/ability3156/request"
	domain591 "git.rosy.net.cn/baseapi/platformapi/tao_vegetable/sdk/ability591/domain"
	request591 "git.rosy.net.cn/baseapi/platformapi/tao_vegetable/sdk/ability591/request"
	"git.rosy.net.cn/baseapi/utils"
	"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"
	"time"
)

// orderStatusChangeNotice 拣货和通知发货状态变化接口
func orderStatusChangeNotice(order *model.GoodsOrder, orderStatus string) (*request591.AlibabaAelophyOrderWorkCallbackRequest, error) {
	param := &request591.AlibabaAelophyOrderWorkCallbackRequest{}
	param.WorkCallbackRequest = &domain591.AlibabaAelophyOrderWorkCallbackWorkCallbackRequest{
		StoreId:    utils.String2Pointer(order.VendorStoreID),
		BizOrderId: utils.Int64ToPointer(utils.Str2Int64(order.VendorOrderID)),
		Status:     utils.String2Pointer(orderStatus),
	}

	workCallbackSubOrderInfoList := make([]domain591.AlibabaAelophyOrderWorkCallbackWorkCallbackSubOrderInfo, 0, 0)
	skuList, err := dao.GetSimpleOrderSkus(dao.GetDB(), order.VendorOrderID, nil)
	if err != nil {
		return nil, err
	}
	if len(skuList) == model.NO {
		return nil, fmt.Errorf("订单商品列表为零,请管理员检查")
	}
	orderDetail, err := getAPI(order.VendorOrgCode, order.JxStoreID, order.VendorStoreID).QueryOrderDetail(&request591.AlibabaAelophyOrderGetRequest{OrderGetRequest: &domain591.AlibabaAelophyOrderGetOrderGetRequest{
		StoreId:    utils.String2Pointer(order.VendorStoreID),
		BizOrderId: utils.Int64ToPointer(utils.Str2Int64(order.VendorOrderID)),
	}})
	if err != nil {
		return nil, err
	}
	for _, v := range *orderDetail.SubOrderResponseList {
		if *v.OrderStatus != tao_vegetable.OrderStatusRefundClose {
			workCallbackSubOrderInfo := domain591.AlibabaAelophyOrderWorkCallbackWorkCallbackSubOrderInfo{
				BizSubOrderId:     v.BizSubOrderId,
				SkuCode:           v.SkuCode,
				PickSaleQuantity:  utils.String2Pointer(utils.Float64ToStr(*v.BuySaleQuantity)),
				PickStockQuantity: utils.String2Pointer(utils.Float64ToStr(*v.BuyStockQuantity)),
			}
			workCallbackSubOrderInfoList = append(workCallbackSubOrderInfoList, workCallbackSubOrderInfo)
		}
	}

	// 出库
	param.WorkCallbackRequest.WorkCallbackSubOrderInfoList = &workCallbackSubOrderInfoList

	return param, nil
}

// OrderStatusChangeDelivery 订单开始配送和送达通知接口
func OrderStatusChangeDelivery(order *model.GoodsOrder, orderStatus string) *request591.AlibabaAelophyOrderWorkCallbackRequest {
	param := &request591.AlibabaAelophyOrderWorkCallbackRequest{}
	param.WorkCallbackRequest = &domain591.AlibabaAelophyOrderWorkCallbackWorkCallbackRequest{
		StoreId:    utils.String2Pointer(order.VendorStoreID),
		BizOrderId: utils.Int64ToPointer(utils.Str2Int64(order.VendorOrderID)),
		Status:     utils.String2Pointer(orderStatus),
	}
	var bill *model.Waybill
	bill, _ = partner.CurOrderManager.LoadWaybill(order.VendorWaybillID, order.WaybillVendorID)
	if bill == nil {
		bill, _ = partner.CurOrderManager.LoadWaybill(order.VendorOrderID, model.VendorJXFakeWL)
	}
	storeDetail, _ := dao.GetStoreDetail(dao.GetDB(), order.JxStoreID, model.VendorIDTaoVegetable, "")
	if bill != nil {
		if bill.CourierName == "" && bill.CourierMobile == "" {
			param.WorkCallbackRequest.DelivererName = utils.String2Pointer("门店老板")
			param.WorkCallbackRequest.DelivererPhone = utils.String2Pointer(storeDetail.Tel1)
			param.WorkCallbackRequest.DelivererCompany = utils.String2Pointer(tao_vegetable.TaoDeliveryTypeSELF)
			param.WorkCallbackRequest.LogisticsNo = utils.String2Pointer(bill.VendorWaybillID)
		} else {
			param.WorkCallbackRequest.DelivererName = utils.String2Pointer(bill.CourierName)
			param.WorkCallbackRequest.DelivererPhone = utils.String2Pointer(bill.CourierMobile)
			switch bill.WaybillVendorID {
			case model.VendorIDDada:
				param.WorkCallbackRequest.DelivererCompany = utils.String2Pointer(tao_vegetable.TaoDeliveryTypeDD)
			case model.VendorIDFengNiao:
				param.WorkCallbackRequest.DelivererCompany = utils.String2Pointer(tao_vegetable.TaoDeliveryTypeFN)
			case model.VendorIDMTPS:
				param.WorkCallbackRequest.DelivererCompany = utils.String2Pointer(tao_vegetable.TaoDeliveryTypeMT)
			case model.VendorIDSFPS:
				param.WorkCallbackRequest.DelivererCompany = utils.String2Pointer(tao_vegetable.TaoDeliveryTypeSF)
			default:
				param.WorkCallbackRequest.DelivererCompany = utils.String2Pointer(tao_vegetable.TaoDeliveryTypeOther)
			}
			param.WorkCallbackRequest.LogisticsNo = utils.String2Pointer(bill.VendorWaybillID)
		}
	}

	if param.WorkCallbackRequest.DelivererName == nil || param.WorkCallbackRequest.DelivererPhone == nil {
		param.WorkCallbackRequest.DelivererName = utils.String2Pointer("门店老板")
		param.WorkCallbackRequest.DelivererPhone = utils.String2Pointer(storeDetail.Tel1)
		param.WorkCallbackRequest.DelivererCompany = utils.String2Pointer(tao_vegetable.TaoDeliveryTypeSELF)
		param.WorkCallbackRequest.LogisticsNo = utils.String2Pointer(order.VendorOrderID + "_1")
	}

	return param
}

// getOrderCancelList 获取订单可取消的订单列表
func getOrderCancelList(api *tao_vegetable.API, order *model.GoodsOrder) (*domain3156.AlibabaTclsAelophyRefundCsapplyrenderRefundCsApplyRenderResponseDto, error) {
	param := &request3156.AlibabaTclsAelophyRefundCsapplyrenderRequest{
		RefundCsApplyRenderDTO: &domain3156.AlibabaTclsAelophyRefundCsapplyrenderRefundCsApplyRenderDto{
			OutOrderId:     utils.String2Pointer(order.VendorOrderID2),
			StoreId:        utils.String2Pointer(order.VendorStoreID),
			OutSubOrderIds: nil,
			OrderFrom:      utils.Int64ToPointer(utils.Str2Int64(tao_vegetable.TaoVegetableChannelCode)),
		},
	}

	skuList, err := dao.GetSimpleOrderSkus(dao.GetDB(), order.VendorOrderID, nil)
	if err != nil {
		return nil, err
	}

	outSubOrderIds := make([]string, 0, len(skuList))
	for _, v := range skuList {
		outSubOrderIds = append(outSubOrderIds, v.VendorSubOrderID)
	}
	param.RefundCsApplyRenderDTO.OutSubOrderIds = &outSubOrderIds

	return api.PartialRefundReason(param)
}

func getTimeFromTimestamp(timeStamp int64) time.Time {
	if timeStamp < 1538103149 { // 立即达订单给的是1（而不是空，0），1538103149不是特殊值，只是一个任意之前的时间，这样写可以处理
		return utils.DefaultTimeValue
	}
	return utils.Timestamp2Time(timeStamp)
}

//
//func (p *PurchaseHandler) GetOrderConsigneeNumber(ctx *jxcontext.Context, storeID int, vendorStoreID string) (numberList []*partner.OrderPhoneNumberInfo, err error) {
//	offset := 0
//	for {
//		store, _ := dao.GetStoreDetail(dao.GetDB(), storeID, model.VendorIDMTWM, "")
//		result, err2 := getAPI(store.VendorOrgCode, storeID, "").OrderBatchPullPhoneNumber(vendorStoreID, offset, mtwmapi.MaxBatchPullPhoneNumberLimit)
//		if err = err2; err == nil {
//			for _, v := range result {
//				v2 := &partner.OrderPhoneNumberInfo{
//					VendorOrderID: utils.Int64ToStr(v.OrderID),
//					PhoneNumber:   v.RealPhoneNumber,
//				}
//				if v2.PhoneNumber == "" {
//					v2.PhoneNumber = v.RealOrderPhoneNumber
//				}
//				numberList = append(numberList, v2)
//			}
//			if len(result) <= mtwmapi.MaxBatchPullPhoneNumberLimit {
//				break
//			}
//			offset += mtwmapi.MaxBatchPullPhoneNumberLimit
//		} else {
//			break
//		}
//	}
//	return numberList, err
//}
//
//func (p *PurchaseHandler) GetOrderCourierNumber(ctx *jxcontext.Context, storeID int, vendorStoreID string) (numberList []*partner.OrderPhoneNumberInfo, err error) {
//	offset := 0
//	for {
//		store, _ := dao.GetStoreDetail(dao.GetDB(), storeID, model.VendorIDMTWM, "")
//		result, err2 := getAPI(store.VendorOrgCode, 0, "").OrderGetRiderInfoPhoneNumber(vendorStoreID, offset, mtwmapi.MaxBatchPullPhoneNumberLimit)
//		if err = err2; err == nil {
//			for _, v := range result {
//				numberList = append(numberList, &partner.OrderPhoneNumberInfo{
//					VendorOrderID: utils.Int64ToStr(v.OrderID),
//					PhoneNumber:   v.RiderRealPhoneNumber,
//				})
//			}
//			if len(result) <= mtwmapi.MaxBatchPullPhoneNumberLimit {
//				break
//			}
//			offset += mtwmapi.MaxBatchPullPhoneNumberLimit
//		} else {
//			break
//		}
//	}
//	return numberList, err
//}
//
//func (p *PurchaseHandler) onNumberDowngrade(msg *mtwmapi.CallbackMsg) (response *mtwmapi.CallbackResponse) {
//	userNumberMap := make(map[string]*partner.OrderPhoneNumberInfo)
//	courierNumberMap := make(map[string]*partner.OrderPhoneNumberInfo)
//	orderMap := make(map[string]int)
//	ctx := jxcontext.AdminCtx
//	task := tasksch.NewParallelTask("美团外卖平台处理隐私号降级通知", tasksch.NewParallelConfig().SetParallelCount(1).SetIsContinueWhenError(true), ctx,
//		func(task *tasksch.ParallelTask, batchItemList []interface{}, params ...interface{}) (retVal interface{}, err error) {
//			step := batchItemList[0].(int)
//			switch step {
//			case 0:
//				userNumberList, err2 := p.GetOrderConsigneeNumber(ctx, 0, "")
//				if err = err2; err == nil {
//					for _, v := range userNumberList {
//						userNumberMap[v.VendorOrderID] = v
//						orderMap[v.VendorOrderID] = 1
//					}
//				}
//			case 1:
//				courierNumberList, err2 := p.GetOrderCourierNumber(ctx, 0, "")
//				if err = err2; err == nil {
//					for _, v := range courierNumberList {
//						courierNumberMap[v.VendorOrderID] = v
//						orderMap[v.VendorOrderID] = 1
//					}
//				}
//			case 2:
//				orderList := jxutils.StringMap2List(orderMap)
//				if len(orderList) > 0 {
//					updateTask := tasksch.NewParallelTask("美团外卖平台处理隐私号降级通知/处理订单", tasksch.NewParallelConfig().SetParallelCount(1).SetIsContinueWhenError(true), ctx,
//						func(task *tasksch.ParallelTask, batchItemList []interface{}, params ...interface{}) (retVal interface{}, err error) {
//							vendorOrderID := batchItemList[0].(string)
//							db := dao.GetDB()
//							if userNumberMap[vendorOrderID] != nil {
//								_, err = dao.UpdateEntityByKV(db, &model.GoodsOrder{}, map[string]interface{}{
//									"ConsigneeMobile":  userNumberMap[vendorOrderID].PhoneNumber,
//									"ConsigneeMobile2": userNumberMap[vendorOrderID].PhoneNumber,
//								}, map[string]interface{}{
//									model.FieldVendorOrderID: vendorOrderID,
//									model.FieldVendorID:      model.VendorIDMTWM,
//								})
//							}
//							if courierNumberMap[vendorOrderID] != nil {
//								_, err = dao.UpdateEntityByKV(db, &model.Waybill{}, map[string]interface{}{
//									"CourierMobile": courierNumberMap[vendorOrderID].PhoneNumber,
//								}, map[string]interface{}{
//									"VendorWaybillID": vendorOrderID,
//									"WaybillVendorID": model.VendorIDMTWM,
//								})
//							}
//							return retVal, err
//						}, orderList)
//					tasksch.HandleTask(updateTask, task, true).Run()
//					_, err = updateTask.GetResult(0)
//				}
//			}
//			return retVal, err
//		}, []int{0, 1, 2})
//	tasksch.HandleTask(task, nil, true).Run()
//	return response
//}
