package bidding

import (
	"encoding/json"
	"fmt"
	"git.rosy.net.cn/baseapi/platformapi/ali_logistics_query"
	"git.rosy.net.cn/baseapi/platformapi/dingdingapi"
	"git.rosy.net.cn/baseapi/platformapi/tonglianpayapi"
	"git.rosy.net.cn/baseapi/platformapi/weixinapi"
	"git.rosy.net.cn/baseapi/utils"
	"git.rosy.net.cn/jx-callback/business/jxutils/ddmsg"
	"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"
	"time"
)

func LoadingLogistics(paramLogistic []*model.UpdateMaterialLogistic) []error {
	var param []*model.UpdateMaterialLogistic
	if len(paramLogistic) == 0 || paramLogistic == nil {
		param = GetLogisticOrder()
	} else {
		param = paramLogistic
	}

	var db = dao.GetDB()
	var errList = make([]error, 0, 0)

	for _, v := range param {
		// 更新订单状态
		goodsOrder, err := partner.CurOrderManager.LoadOrder(v.OrderId, model.VendorIDJX)
		if err != nil {
			errList = append(errList, err)
			continue
		}
		if time.Since(goodsOrder.CreatedAt) >= 3*24*time.Hour {
			goodsOrder.Status = model.OrderStatusFinished
			goodsOrder.VendorStatus = utils.Int2Str(model.WaybillStatusDelivered)
			goodsOrder.StatusTime = time.Now()
			goodsOrder.OrderFinishedAt = time.Now()
			if _, err := dao.UpdateEntity(db, goodsOrder, "Status", "VendorStatus", "StatusTime", "OrderFinishedAt"); err != nil {
				errList = append(errList, err)
				continue
			}

			payList, _ := dao.GetOrderPayList(db, goodsOrder.VendorOrderID, goodsOrder.VendorID)
			for _, pl := range payList {
				if pl.OriginalData != "" {
					originalData := &tonglianpayapi.CallBackResult{}
					json.Unmarshal([]byte(pl.OriginalData), originalData)

					if err = api.WeixinMiniAPI2.SNSDeliveryGoodsOrder(&weixinapi.DeliveryOrder{
						TransactionId: originalData.ChnlTrxID,
						ReceivedTime:  time.Now().Unix(),
					}); err != nil {
						ddmsg.SendUserMessage(dingdingapi.MsgTyeText, "2452A93EEB9111EC9B06525400E86DC0", "微信物料送达推送", fmt.Sprintf("物料商城下单,送达错误:%s,请注意查看,err:%s", goodsOrder.VendorOrderID, err.Error()))
					}

				}
			}

		}

	}
	return nil

	// GetLogisticsInfo 免费物流查询资源不可用,暂时不管
	//for _, logistics := range param {
	//	// 获取当前订单物流状态
	//	statusList, err := orderman.FixedOrderManager.GetLogisticsOrderStatusList(logistics.OrderId, logistics.LogisticId, 9)
	//	if err != nil {
	//		errList = append(errList, err)
	//		continue
	//	}
	//
	//	// 获取当前订单三方配送物流
	//	logisticsList, err := api.LogisticsApi.GetLogisticsInfo(logistics.LogisticId)
	//	if err != nil {
	//		errList = append(errList, err)
	//		continue
	//	}
	//
	//	// 新订单,本地暂无物流信息,全部更新远端物流信息到本地
	//	if len(logisticsList.Info[0].LogisticsTraceDetailList) == model.NO {
	//		errList = append(errList, errors.New("运单号[%s]:已经过期/新订单暂无物流推送信息"))
	//		continue
	//	}
	//	var orderStatus = make([]*model.OrderStatus, 0, 0)
	//	goodsOrderStatus := 0
	//	for _, v := range logisticsList.Info[0].LogisticsTraceDetailList {
	//		orderStatusToLocal := &model.OrderStatus{
	//			VendorOrderID:    logisticsList.Info[0].MailNo,
	//			VendorID:         model.VendorIDTotalWl,
	//			OrderType:        model.OrderTypeWaybill,
	//			RefVendorOrderID: logistics.OrderId,
	//			RefVendorID:      model.VendorIDJX,
	//			VendorStatus:     v.SubLogisticsStatus,
	//			StatusTime:       time.Time{},
	//			DuplicatedCount:  0,
	//			Remark:           v.Desc,
	//			ModelTimeInfo:    model.ModelTimeInfo{CreatedAt: time.Now(), UpdatedAt: time.Now()},
	//		}
	//
	//		switch v.SubLogisticsStatus {
	//		case ali_logistics_query.LogisticsStatusRECEVIE:
	//			orderStatusToLocal.Status = model.WaybillStatusNew // 新订单
	//			goodsOrderStatus = model.OrderStatusNew            // 新订单
	//		case ali_logistics_query.LogisticsStatusWAIT_ACCEPT:
	//			orderStatusToLocal.Status = model.WaybillStatusAccepted // 分配骑手
	//			goodsOrderStatus = model.OrderStatusAccepted            // 拣货完成等待骑手
	//		case ali_logistics_query.LogisticsStatusACCEPT:
	//			orderStatusToLocal.Status = model.WaybillStatusCourierArrived // 兼容骑手取货状态
	//			goodsOrderStatus = model.OrderStatusFinishedPickup
	//		case ali_logistics_query.LogisticsStatusTRANSPORT, ali_logistics_query.LogisticsStatusSEND_ON, ali_logistics_query.LogisticsStatusARRIVE_CITY, ali_logistics_query.LogisticsStatusDELIVERING:
	//			orderStatusToLocal.Status = model.WaybillStatusDelivering // 配送中
	//			goodsOrderStatus = model.OrderStatusDelivering
	//		case ali_logistics_query.LogisticsStatusAGENT_SIGN, ali_logistics_query.LogisticsStatusSIGN, ali_logistics_query.LogisticsStatusSTA_SIGN:
	//			orderStatusToLocal.Status = model.WaybillStatusDelivered // 配送结束
	//			goodsOrderStatus = model.OrderStatusFinished
	//		default: // 剩余状态全部为异常状态,除非新加状态
	//			orderStatusToLocal.Status = model.WaybillStatusUnknown // 异常配送
	//			goodsOrderStatus = model.OrderStatusDeliverFailed      // 投递失败
	//		}
	//		orderStatusToLocal.StatusTime = utils.Timestamp2Time(v.Time)
	//		orderStatus = append(orderStatus, orderStatusToLocal)
	//	}
	//
	//	if len(statusList) == 0 || statusList == nil { // 本地订单状态为空不存在
	//		for _, v := range orderStatus {
	//			if err := dao.CreateEntity(db, v); err != nil {
	//				errList = append(errList, err)
	//				continue
	//			}
	//		}
	//	} else {
	//		for _, v := range orderStatus {
	//			if statusList[len(statusList)-1].StatusTime.Unix() > v.StatusTime.Unix() && checkOrderStatus(statusList[len(statusList)-1].VendorStatus) {
	//				continue
	//			}
	//			if err := dao.CreateEntity(db, v); err != nil {
	//				errList = append(errList, err)
	//				continue
	//			}
	//		}
	//	}
	//
	//	// 获取当前订单运单状态
	//	wayBill, err := dao.GetWaybills(db, logistics.OrderId, nil)
	//	if err != nil {
	//		errList = append(errList, err)
	//		continue
	//	}
	//	status := orderStatus[len(orderStatus)-1].Status
	//	vendorStatus := orderStatus[len(orderStatus)-1].VendorStatus
	//	statusTime := orderStatus[len(orderStatus)-1].StatusTime
	//	if len(wayBill) == 0 || wayBill == nil {
	//		wayBillObj := &model.Waybill{
	//			VendorWaybillID:   logistics.LogisticId,
	//			WaybillVendorID:   model.VendorIDTotalWl,
	//			VendorOrderID:     logistics.OrderId,
	//			OrderVendorID:     model.VendorIDJX,
	//			CourierName:       logisticsList.Info[0].Courier,
	//			CourierMobile:     logisticsList.Info[0].CourierPhone,
	//			Status:            status,
	//			VendorStatus:      vendorStatus,
	//			ActualFee:         logistics.LogisticFee,
	//			DesiredFee:        logistics.LogisticFee,
	//			DeliveryFlag:      model.OrderDeliveryFlagMaskScheduleDisabled,
	//			WaybillCreatedAt:  time.Now(),
	//			StatusTime:        statusTime,
	//			ModelTimeInfo:     model.ModelTimeInfo{CreatedAt: time.Now(), UpdatedAt: time.Now()},
	//			WaybillFinishedAt: time.Now(),
	//		}
	//		if err := dao.CreateEntity(db, wayBillObj); err != nil {
	//			errList = append(errList, err)
	//			continue
	//		}
	//	} else {
	//		wayBill[0].UpdatedAt = time.Now()
	//		wayBill[0].Status = status
	//		wayBill[0].VendorStatus = vendorStatus
	//		wayBill[0].StatusTime = statusTime
	//		wayBill[0].WaybillFinishedAt = time.Now()
	//		if _, err := dao.UpdateEntity(db, wayBill[0], "Status", "UpdatedAt", "VendorStatus", "StatusTime"); err != nil {
	//			errList = append(errList, err)
	//			continue
	//		}
	//	}
	//
	//	// 更新订单状态
	//	goodsOrder, err := partner.CurOrderManager.LoadOrder(logistics.OrderId, model.VendorIDJX)
	//	if err != nil {
	//		errList = append(errList, err)
	//		continue
	//	}
	//	goodsOrder.Status = goodsOrderStatus
	//	goodsOrder.VendorStatus = vendorStatus
	//	goodsOrder.StatusTime = statusTime
	//	if orderStatus[len(orderStatus)-1].Status >= model.OrderStatusEndBegin {
	//		goodsOrder.OrderFinishedAt = time.Now()
	//	}
	//	if _, err := dao.UpdateEntity(db, goodsOrder, "Status", "VendorStatus", "StatusTime", "OrderFinishedAt"); err != nil {
	//		errList = append(errList, err)
	//		continue
	//	}
	//}
	//
	//return errList
}

func checkOrderStatus(orderStatus string) bool {
	switch orderStatus {
	case ali_logistics_query.LogisticsStatusRECEVIE:
		return true
	case ali_logistics_query.LogisticsStatusWAIT_ACCEPT:
		return true
	case ali_logistics_query.LogisticsStatusACCEPT:
		return true
	case ali_logistics_query.LogisticsStatusTRANSPORT, ali_logistics_query.LogisticsStatusSEND_ON, ali_logistics_query.LogisticsStatusARRIVE_CITY, ali_logistics_query.LogisticsStatusDELIVERING:
		return true
	case ali_logistics_query.LogisticsStatusAGENT_SIGN, ali_logistics_query.LogisticsStatusSIGN, ali_logistics_query.LogisticsStatusSTA_SIGN:
		return true
	case ali_logistics_query.LogisticsStatusSTA_INBOUND, ali_logistics_query.LogisticsStatusRETURN_SIGN, ali_logistics_query.LogisticsStatusFAILED, ali_logistics_query.LogisticsStatusREFUSE_SIGN, ali_logistics_query.LogisticsStatusDELIVER_ABNORMAL:
		return true
	case ali_logistics_query.LogisticsStatusRETENTION, ali_logistics_query.LogisticsStatusISSUE, ali_logistics_query.LogisticsStatusRETURN, ali_logistics_query.LogisticsStatusDAMAGE, ali_logistics_query.LogisticsStatusCANCEL_ORDER:
		return true
	default:
		return false
	}
}

// GetLogisticOrder 查询未完成的物料订单,更新物流信息
func GetLogisticOrder() []*model.UpdateMaterialLogistic {
	var (
		timeNow   = time.Now()
		startTime = timeNow.AddDate(0, -1, 0)
		endTime   = timeNow
		goodsList = make([]*model.GoodsOrder, 0, 0)
	)

	sql := ` SELECT * FROM goods_order g WHERE g.order_created_at >= ? AND g.order_created_at < ? AND g.store_id = ? AND order_type = ? AND g.status < ?  ` // 一个月内状态未完成的订单
	sqlParam := []interface{}{
		startTime, endTime, "666666", 1, model.OrderStatusEndBegin,
	}
	if err := dao.GetRows(dao.GetDB(), &goodsList, sql, sqlParam...); err != nil {
		globals.SugarLogger.Debugf("loading jx material order err :%s", err)
		return nil
	}

	if len(goodsList) == 0 {
		return nil
	}

	logisticsList := make([]*model.UpdateMaterialLogistic, 0, len(goodsList))
	for _, v := range goodsList {
		logistics := &model.UpdateMaterialLogistic{
			OrderId:     v.VendorOrderID,
			LogisticId:  v.VendorWaybillID,
			LogisticFee: v.BaseFreightMoney,
		}
		logisticsList = append(logisticsList, logistics)
	}
	return logisticsList
}
