package order

import (
	"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/factory"
	"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"
	"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/utils"
	"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol"
	"time"
)

func Template(header *protocol.RequestHeader, request *protocol.OrderDetailRequest) (rsp *protocol.OrderDetailResponse, err error) {
	var (
		transactionContext, _ = factory.CreateTransactionContext(nil)
		//OrderResponsitory,_ =factory.CreateOrderRepository(transactionContext)

	)
	if err = transactionContext.StartTransaction(); err != nil {
		return nil, err
	}
	defer func() {
		transactionContext.RollbackTransaction()
	}()
	err = transactionContext.CommitTransaction()
	return
}

//订单详情
func OrderDetail(header *protocol.RequestHeader, request *protocol.OrderDetailRequest) (rsp *protocol.OrderDetailResponse, err error) {
	var (
		transactionContext, _ = factory.CreateTransactionContext(nil)
		OrderResponsitory, _  = factory.CreateOrderRepository(transactionContext)
		OrderDao, _           = factory.CreateOrderDao(transactionContext)
		order                 *domain.Order
	)
	if err = transactionContext.StartTransaction(); err != nil {
		return nil, err
	}
	defer func() {
		transactionContext.RollbackTransaction()
	}()

	rsp = &protocol.OrderDetailResponse{}
	if order, err = OrderResponsitory.FindOne(utils.ObjectJsonToMap(request)); err != nil {
		return
	}
	rsp.Order = protocol.OrderDetail{
		Id:                order.Id,
		OrderNo:           order.OrderCode,
		OrderName:         order.OrderName,
		OrderStatus:       order.OrderStatus,
		CreateTime:        order.CreateAt.Unix() * 1000,
		UpdateTime:        order.UpdateAt.Unix() * 1000,
		OrderQuantity:     order.OrderActualCount,
		OrderAmount:       order.OrderActualAmount,
		OrderAmountCancel: order.OrderAmountCancel(),
		OrderUpdateReason: order.Reason,
		OrderDistrict:     map[string]interface{}{"id": order.OrderRegionInfo.RegionId, "name": order.OrderRegionInfo.RegionName},
		Customer:          protocol.Customer{Uname: order.Buyer.BuyerName, Phone: order.Buyer.ContactInfo},
		MyDividend:        order.OrderTotalBonus(),
		MyDividendPercent: order.PartnerBonusPercent,
	}
	if header.UserId == order.PartnerId && order.UpdateAt.After(order.LastViewTime) {
		if err = OrderDao.UpdateLastViewTime(order.Id, time.Now()); err != nil {
			return
		}
	}
	err = transactionContext.CommitTransaction()
	return
}

//订单统计
func OrderStatistics(header *protocol.RequestHeader, request *protocol.OrderStatisticsRequest) (rsp *protocol.OrderStatisticsResponse, err error) {
	var (
		transactionContext, _ = factory.CreateTransactionContext(nil)
		OrderDao, _           = factory.CreateOrderDao(transactionContext)
	)
	if err = transactionContext.StartTransaction(); err != nil {
		return nil, err
	}
	defer func() {
		transactionContext.RollbackTransaction()
	}()
	rsp = &protocol.OrderStatisticsResponse{Statistics: protocol.OrderStatics{}}
	if rsp.Statistics.TodayIntentionQuantity, rsp.Statistics.TodayIntentionMoney, err = OrderDao.OrderStatics(&domain.OrderStaticQuery{
		BeginTime: utils.GetDayBegin().Unix() * 1000,
		EndTime:   utils.GetDayEnd().Unix() * 1000,
		OrderType: domain.OrderIntention,
		PartnerId: header.UserId,
	}); err != nil {
		return
	}
	if rsp.Statistics.TodayRealQuantity, rsp.Statistics.TodayRealMoney, err = OrderDao.OrderStatics(&domain.OrderStaticQuery{
		BeginTime: utils.GetDayBegin().Unix() * 1000,
		EndTime:   utils.GetDayEnd().Unix() * 1000,
		OrderType: domain.OrderReal,
		PartnerId: header.UserId,
	}); err != nil {
		return
	}
	if rsp.Statistics.CumulativeQuantity, rsp.Statistics.CumulativeMoney, err = OrderDao.OrderStatics(&domain.OrderStaticQuery{
		EndTime:   time.Now().Unix() * 1000,
		OrderType: domain.OrderReal,
		PartnerId: header.UserId,
	}); err != nil {
		return
	}
	err = transactionContext.CommitTransaction()
	return
}

//订单列表
func OrderList(header *protocol.RequestHeader, request *protocol.OrderListRequest) (rsp *protocol.OrderListResponse, err error) {
	var (
		transactionContext, _ = factory.CreateTransactionContext(nil)
		OrderResponsitory, _  = factory.CreateOrderRepository(transactionContext)
		OrderDao, _           = factory.CreateOrderDao(transactionContext)
		orders                []*domain.Order
	)

	rsp = &protocol.OrderListResponse{
		List:       make([]*protocol.OrderListItem, 0),
		Statistics: make(map[string]interface{}),
	}
	if err = transactionContext.StartTransaction(); err != nil {
		return nil, err
	}
	defer func() {
		transactionContext.RollbackTransaction()
	}()
	queryOption := &domain.OrderQueryOption{
		PartnerId:        header.UserId,
		Limit:            request.PageSize,
		Offset:           request.PageSize * request.PageIndex,
		SortByUpdateTime: domain.DESC,
	}
	if request.OrderAction == 1 {
		queryOption.OrderStatus = domain.OrderStatusDeliverSome
	} else if request.OrderAction == 2 {
		queryOption.OrderStatus = domain.OrderStatusDeliverAll
	}
	if request.StartTime > 0 {
		queryOption.BeginTime = time.Unix(request.StartTime/1000, 0)
	}
	if request.EndTime > 0 {
		queryOption.EndTime = time.Unix(request.EndTime/1000, 0)
	}
	queryOption.OrderType = request.OrderType
	_, orders, _ = OrderResponsitory.Find(utils.ObjectJsonToMap(queryOption))
	//统计数据
	if request.PageIndex == 0 {
		var (
			partShipmentQuantity, allShipmentQuantity int
			cumulativeQuantity, intentionQuantity     int
		)
		//部分发货的订单数量
		partShipmentQuantity, _, err = OrderDao.OrderStatics(&domain.OrderStaticQuery{
			EndTime:     request.EndTime,
			BeginTime:   request.StartTime,
			OrderType:   domain.OrderReal,
			PartnerId:   header.UserId,
			OrderStatus: domain.OrderStatusDeliverSome,
		})
		//全部发货的订单数量
		allShipmentQuantity, _, err = OrderDao.OrderStatics(&domain.OrderStaticQuery{
			EndTime:     request.EndTime,
			BeginTime:   request.StartTime,
			OrderType:   domain.OrderReal,
			PartnerId:   header.UserId,
			OrderStatus: domain.OrderStatusDeliverAll,
		})
		//累计实发订单
		cumulativeQuantity, _, err = OrderDao.OrderStatics(&domain.OrderStaticQuery{
			EndTime: time.Now().Unix() * 1000,
			//BeginTime: request.StartTime,
			OrderType: domain.OrderReal,
			PartnerId: header.UserId,
		})
		//累计意向订单
		intentionQuantity, _, err = OrderDao.OrderStatics(&domain.OrderStaticQuery{
			EndTime: time.Now().Unix() * 1000,
			//BeginTime: request.StartTime,
			OrderType: domain.OrderIntention,
			PartnerId: header.UserId,
		})
		//订单数量
		rsp.Statistics["partShipmentQuantity"] = partShipmentQuantity
		rsp.Statistics["allShipmentQuantity"] = allShipmentQuantity
		rsp.Statistics["orderQuantity"] = partShipmentQuantity + allShipmentQuantity //所有订单 = 部分发货 + 已经发货
		rsp.Statistics["cumulativeQuantity"] = cumulativeQuantity                    //实发订单 = 部分发货 + 全部发货
		rsp.Statistics["intentionQuantity"] = intentionQuantity

	}

	if len(orders) == 0 {
		return
	}
	for i := range orders {
		rsp.List = append(rsp.List, DomainOrderToOrderListItem(orders[i]))
	}

	err = transactionContext.CommitTransaction()
	return
}
func DomainOrderToOrderListItem(order *domain.Order) *protocol.OrderListItem {
	return &protocol.OrderListItem{
		Id:               order.Id,
		OrderType:        order.OrderType,
		OrderNo:          order.OrderCode,
		OrderName:        order.OrderName,
		OrderAmount:      order.OrderActualAmount,
		OrderActualCount: order.OrderActualCount,
		OrderStatus:      order.OrderStatus,
		UpdateTime:       order.UpdateAt.Unix() * 1000,
		MyDividend:       order.OrderTotalBonus(),
		IsRead:           order.IsRead(),
	}
}