
package com.tmerclub.cloud.search.controller.admin;

import cn.hutool.core.collection.CollUtil;
import com.tmerclub.cloud.api.dto.EsPageDTO;
import com.tmerclub.cloud.api.vo.EsPageVO;
import com.tmerclub.cloud.common.constant.Constant;
import com.tmerclub.cloud.common.order.dto.OrderRefundSearchDTO;
import com.tmerclub.cloud.common.order.vo.EsOrderRefundVO;
import com.tmerclub.cloud.common.order.vo.EsOrderVO;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.security.AuthUserContext;
import com.tmerclub.cloud.search.manager.OrderRefundSearchManager;
import com.tmerclub.cloud.search.manager.OrderSearchManager;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 商品搜索
 *
 * @author tmerclub
 * @date 2020/11/16
 */
@RestController("adminOrderRefundSearchController")
@RequestMapping("/mp/search/orderRefund")
@Tag(name = "admin-退款订单搜索接口")
public class OrderRefundSearchController {

    @Autowired
    private OrderRefundSearchManager orderRefundSearchManager;

    @Autowired
    private OrderSearchManager orderSearchManager;

    @GetMapping("/page")
    @Operation(summary = "退款订单搜索接口", description = "退款订单搜索接口")
    public ServerResponseEntity<EsPageVO<EsOrderRefundVO>> pcPage(@Valid EsPageDTO pageDTO, OrderRefundSearchDTO orderRefundSearchDTO) {
        Long shopId = AuthUserContext.get().getTenantId();
        if (!Objects.equals(shopId, Constant.PLATFORM_SHOP_ID)) {
            orderRefundSearchDTO.setShopId(shopId);
        }
        orderRefundSearchDTO.setSysType(AuthUserContext.get().getSysType());
        EsPageVO<EsOrderRefundVO> orderRefundPage = orderRefundSearchManager.page(pageDTO, orderRefundSearchDTO);
        if (CollUtil.isNotEmpty(orderRefundPage.getList())) {
            insertOrderStatus(orderRefundPage.getList());
        }
        return ServerResponseEntity.success(orderRefundPage);
    }

    private void insertOrderStatus(List<EsOrderRefundVO> list) {
        List<Long> orderIds = list.stream().map(EsOrderRefundVO::getOrderId).collect(Collectors.toList());
        List<EsOrderVO> orderList = orderSearchManager.listByOrderIds(orderIds);
        Map<Long, Integer> orderMap = orderList.stream().collect(Collectors.toMap(EsOrderVO::getOrderId, EsOrderVO::getStatus));
        for (EsOrderRefundVO orderRefund : list) {
            orderRefund.setOrderStatus(orderMap.get(orderRefund.getOrderId()));
        }
    }

}
