package com.gic.haoban.manage.web.controller.order;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.gic.api.base.commons.BasePageInfo;
import com.gic.api.base.commons.Page;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.business.order.dto.member.MemberStoreInfoDTO;
import com.gic.business.order.dto.ordermanage.ListOrderDTO;
import com.gic.business.order.dto.ordermanage.ListOrderItemDTO;
import com.gic.business.order.dto.ordermanage.OrderDetailDTO;
import com.gic.business.order.dto.ordermanage.OrderInfoDTO;
import com.gic.business.order.dto.ordermanage.OrderNodeDTO;
import com.gic.business.order.dto.ordermanage.OrderStatusDTO;
import com.gic.business.order.dto.setting.MallOrderSettingDTO;
import com.gic.business.order.enums.OrderEnum;
import com.gic.business.order.enums.OrderEnum.DeliveryOptTypeEnum;
import com.gic.business.order.enums.OrderEnum.SearchOrderTypeEnum;
import com.gic.business.order.qdto.OperationUserQDTO;
import com.gic.business.order.qdto.ordermanage.CountOrderStatusQDTO;
import com.gic.business.order.qdto.ordermanage.ListOrderManageQDTO;
import com.gic.business.order.qdto.ordermanage.OrderItemShipmentQDTO;
import com.gic.business.order.qdto.ordermanage.OrderShipmentQDTO;
import com.gic.business.order.qdto.ordermanage.QueryOrderDetailQDTO;
import com.gic.business.order.qdto.ordermanage.SelfPickOffQDTO;
import com.gic.business.order.qdto.ordermanage.UpdateOrderLogisticsQDTO;
import com.gic.business.order.service.activity.MemberReferClerkApiService;
import com.gic.business.order.service.ordermanage.WebOrderManageApiService;
import com.gic.business.order.service.setting.OrderSettingApiService;
import com.gic.clerk.api.dto.ClerkDTO;
import com.gic.clerk.api.service.ClerkService;
import com.gic.commons.util.DateUtil;
import com.gic.commons.util.EntityUtil;
import com.gic.commons.util.PageHelperUtils;
import com.gic.commons.webapi.reponse.RestResponse;
import com.gic.evaluate.manage.api.dto.EvaluateRuleScoreDTO;
import com.gic.evaluate.manage.api.dto.StoreEvaluateInfoDTO;
import com.gic.evaluate.manage.api.service.EvaluateDataApiService;
import com.gic.haoban.app.aggregation.api.service.evaluation.OrderVerificationRecordApiService;
import com.gic.haoban.manage.web.errCode.HaoBanErrCode;
import com.gic.haoban.manage.web.vo.order.EvaluateVO;
import com.gic.haoban.manage.web.vo.order.MemberInfoVO;
import com.gic.haoban.manage.web.vo.order.OrderCountVO;
import com.gic.haoban.manage.web.vo.order.OrderDetailItemVO;
import com.gic.haoban.manage.web.vo.order.OrderDetailVO;
import com.gic.haoban.manage.web.vo.order.OrderListItemVO;
import com.gic.haoban.manage.web.vo.order.OrderListVO;
import com.gic.haoban.manage.web.vo.order.integral.HxOrderCountVO;
import com.gic.integralmall.api.service.IntegralmallService;
import com.gic.store.goods.dto.stock.GoodsStockBaseQDTO;
import com.gic.store.goods.service.ProductStockApiService;

@RestController
@RequestMapping("/order")
public class GicOrderController {

    private static final org.apache.logging.log4j.Logger logger = LogManager.getLogger(GicOrderController.class);

    @Autowired
    private WebOrderManageApiService webOrderManageApiService;
    @Autowired
    private ClerkService clerkService;
    @Autowired
    private MemberReferClerkApiService memberReferClerkApiService;
    @Autowired
    private IntegralmallService integralmallService;
    @Autowired
    private OrderVerificationRecordApiService orderVerificationRecordApiService;
    @Autowired
    private ProductStockApiService productStockApiService;
    @Autowired
    private OrderSettingApiService orderSettingApiService;
    @Autowired
    private EvaluateDataApiService evaluateDataApiService;

    // 1 虚拟商品； 2实物商品  3优惠券
    // -1 全部  1   2 待发货 3已发货 4完成 关闭 0
    @RequestMapping("list-member-integral-order")
    public RestResponse<Object> listMemberIntegralOrder(String enterpriseId, String memberId,
                                          @RequestParam(defaultValue = "2") Integer type,
                                          @RequestParam(defaultValue = "-1") int status, BasePageInfo pageInfo) {
        ListOrderManageQDTO qdto = new ListOrderManageQDTO();
        qdto.setEnterpriseId(enterpriseId);
        qdto.setOrderStep(status+"");
        qdto.setGoodsType(type);
        qdto.setMemberId(memberId);
        qdto.setBusinessType(2);
        logger.info("积分商城订单查询,qdto={}", JSON.toJSONString(qdto));
        return this.orderListSelect(qdto, pageInfo, false);
    }

    // 发货订单列表 (0全部,待发货2+待收货3,部分发货7)
    @RequestMapping("list-order")
    public RestResponse<Object> orderList(String enterpriseId, String storeId, String clerkId, String search,
                                          @RequestParam(required = false) Integer businessType,
            @RequestParam(defaultValue = "0") int status, BasePageInfo pageInfo) {
        String strStatus = "" + status;
        if (status == 0) {
            strStatus = "2,3,7";
        }
        if (status == 2) {
            strStatus = "2,7";
        }
        // 查询门店
        ListOrderManageQDTO qdto = new ListOrderManageQDTO();
        qdto.setEnterpriseId(enterpriseId);
        qdto.setOrderStep(strStatus);
        // 配送方式 -1：所有 2：门店自提 1：快递发货
        qdto.setDeliveryChannel(1);
        // 库存 - 门店库存2
        qdto.setDeliveryMode(2);
        qdto.setBusinessType(businessType);
        if (StringUtils.isNotEmpty(search)) {
            qdto.setSearchOrderType(SearchOrderTypeEnum.GOODS_NAME_OR_ORDER_NUMBER.getType());
            qdto.setSearchOrderParam(search);
        }
        qdto.setBelongStoreId(storeId);
        logger.info("发货订单查询,qdto={}", JSON.toJSONString(qdto));
        return this.orderListSelect(qdto, pageInfo, false);
    }

    // 数量查询(待发货+待收货)
    // orderType:2待发货 3待收货
    @RequestMapping("order-deliver-count")
    public RestResponse<Object> orderCount(String enterpriseId, String storeId,@RequestParam(required = false) Integer businessType) {
        OrderCountVO vo = new OrderCountVO();
        if (StringUtils.isEmpty(storeId)) {
            return RestResponse.successResult(vo);
        }
        CountOrderStatusQDTO qdto = new CountOrderStatusQDTO();
        qdto.setEnterpriseId(enterpriseId);
        // 配送方式 -1：所有 2：门店自提 1：快递发货
        qdto.setDeliveryChannel(1);
        // 库存 - 门店库存2
        qdto.setDeliveryMode(2);
        qdto.setBelongStoreId(storeId);
        qdto.setBusinessType(businessType);
        ServiceResponse<List<OrderStatusDTO>> resp = this.webOrderManageApiService.countOrderStatus(qdto);
        List<OrderStatusDTO> list = resp.getResult();
        if (CollectionUtils.isNotEmpty(list)) {
            long noDeliver = 0, deliver = 0;
            for (OrderStatusDTO item : list) {
                if (item.getOrderStep() == 3) {
                    deliver = item.getTotal();
                }
                if (item.getOrderStep() == 2 || item.getOrderStep() == 7) {
                    noDeliver = noDeliver + item.getTotal();
                }
            }
            vo.setDeliverCount((int) deliver);
            vo.setNoDeliverCount((int) noDeliver);
            vo.setTotal((int) (deliver + noDeliver));
        }
        return RestResponse.successResult(vo);
    }

    // 核销订单查询
    // status 0全部 1待核销 2已核销
    @RequestMapping("list-verification-order")
    public RestResponse<Object> mallOrderList(String enterpriseId, String storeId, String clerkId,
                                              @RequestParam(required = false) Integer businessType,
            @RequestParam(defaultValue = "0") int status, String search, BasePageInfo pageInfo) {
        // 查询门店
        ListOrderManageQDTO qdto = new ListOrderManageQDTO();
        qdto.setEnterpriseId(enterpriseId);
        // 配送方式 -1：所有 2：门店自提 1：快递发货
        qdto.setDeliveryChannel(2);
        qdto.setPickUpStoreId(storeId);
        if (status == 1) {
            qdto.setOrderStep("2");
        }
        if (status == 2) {
            qdto.setWriteOffClerkId(clerkId);
            qdto.setOrderStep("4");
            qdto.setDeliveryOptType(1);
        }
        qdto.setSearchOrderParam(search);
        qdto.setBusinessType(businessType);
        return this.orderListSelect(qdto, pageInfo, false);
    }

    // 订单详情 (客户信息+收货地址+商品详情+订单信息 + 订单状态)
    @RequestMapping("order-detail")
    public RestResponse<Object> orderDetail(String enterpriseId, String clerkId, String searchParams,
            @RequestParam(defaultValue = "1") int orderType, String orderId, String storeId) {
        QueryOrderDetailQDTO queryOrderDetailQDTO = new QueryOrderDetailQDTO();
        queryOrderDetailQDTO.setOrderId(orderId);
        queryOrderDetailQDTO.setEnterpriseId(enterpriseId);
        ServiceResponse<OrderDetailDTO> ret = webOrderManageApiService.getOrderDetail(queryOrderDetailQDTO);
        if (!ret.isSuccess()) {
            return RestResponse.failure(ret.getCode(), ret.getMessage());
        }
        logger.info("订单信息={}", JSON.toJSONString(ret, true));
        OrderDetailVO detail = this.getOrderDetail(enterpriseId, ret.getResult().getOrderInfo(),
                ret.getResult().getOrderItemList(), storeId);
        if (CollectionUtils.isNotEmpty(ret.getResult().getOrderWrapList())) {
            List<String> idList = ret.getResult().getOrderWrapList().stream().map(o -> o.getMallOrderLogisticsId())
                    .collect(Collectors.toList());
            detail.setOrderLogisticsIdList(idList);
        }
        detail.setCreateTime(OrderDetailDTO.getNodeTimeStatic(OrderEnum.OrderNodeEnum.PLACE_AN_ORDER,
                ret.getResult().getOrderNodeList()));
        detail.setPayTime(OrderDetailDTO.getNodeTimeStatic(OrderEnum.OrderNodeEnum.PAY_ORDER,
                ret.getResult().getOrderNodeList()));
        // 如果是自提
        if (null != detail.getDeliveryChannel() && detail.getDeliveryChannel() == 2) {
            detail.setPickUpTime(OrderDetailDTO.getNodeTimeStatic(OrderEnum.OrderNodeEnum.SUCCESSFUL,
                    ret.getResult().getOrderNodeList()));
        }
        // 自动收货时间
        List<OrderNodeDTO> stepList = ret.getResult().getOrderNodeList();
        if (CollectionUtils.isNotEmpty(stepList)) {
            stepList.forEach(item -> {
                if (item.getOrderStep() == 3) {
                    ServiceResponse<MallOrderSettingDTO> setResp = this.orderSettingApiService
                            .getOrderSetting(enterpriseId);
                    int autoDay = setResp.getResult().getAutoConfirm();
                    if (0 != autoDay) {
                        detail.setAutoTaskOverTime(DateUtil.addNumForDay(item.getCreateTime(), autoDay));
                        return;
                    }
                }
            });
        }
        return RestResponse.successResult(detail);
    }

    /**
     * 扫码二维码
     */
    @RequestMapping("/scan")
    public RestResponse<Object> scan(String enterpriseId, String writeOffCode, String storeId) {
        if (StringUtils.isEmpty(writeOffCode)) {
            return RestResponse.failure("9999", "核销码为空");
        }
        // 通过核销码查询
        QueryOrderDetailQDTO qdto = new QueryOrderDetailQDTO();
        qdto.setEnterpriseId(enterpriseId);
        qdto.setWriteOffCode(writeOffCode);
        ServiceResponse<OrderDetailDTO> ret = webOrderManageApiService.getOrderDetail(qdto);
        OrderDetailDTO detail = ret.getResult();
        logger.info("订单信息={}", JSON.toJSONString(ret, true));
        if (ret.isSuccess()) {
            // 已核销,且不是好办核销的
            if (null != detail.getOrderInfo().getDeliveryOptType()
                    && detail.getOrderInfo().getDeliveryOptType() != 1) {
                logger.info("已核销,且不是好办核销的={}", writeOffCode);
                return RestResponse.failure("9999", "此自提点无法核销");
            }
            if (!storeId.equals(detail.getOrderInfo().getPickUpStoreId())) {
                return RestResponse.failure("9999", "此自提点无法核销");
            }
            OrderDetailVO orderDetailVO = this.getOrderDetail(enterpriseId, ret.getResult().getOrderInfo(),
                    ret.getResult().getOrderItemList(), storeId);
            if(!(orderDetailVO.getOrderStep().equals("2") || orderDetailVO.getOrderStep().equals("4"))) {
                return RestResponse.failure("9999", "核销订单不存在");
            }
            Date pickOverTime = detail.getOrderInfo().getPickUpOverTime() ;
            if(null != pickOverTime && pickOverTime.before(new Date())) {
                return RestResponse.failure("9999", "此订单自提时间已截止");
            }
            return RestResponse.successResult(orderDetailVO);
        } else {
            return RestResponse.failure("9999", ret.getMessage());
        }
    }

    // 单笔订单发货商品列表
    @RequestMapping("order-deliver-list")
    public RestResponse<Object> orderDeliverList(String enterpriseId, String storeId, String orderId) {
        QueryOrderDetailQDTO qdto = new QueryOrderDetailQDTO();
        qdto.setEnterpriseId(enterpriseId);
        qdto.setOrderId(orderId);
        ServiceResponse<OrderDetailDTO> resp = webOrderManageApiService.getOrderDetail(qdto);
        List<ListOrderItemDTO> list = resp.getResult().getOrderItemList();
        List<OrderListItemVO> voList = new ArrayList<>();
        for (ListOrderItemDTO item : list) {
            if (StringUtils.isEmpty(item.getLogisticsId())) {
                OrderListItemVO vo = EntityUtil.changeEntityByJSON(OrderListItemVO.class, item);

                GoodsStockBaseQDTO stockQDTO = new GoodsStockBaseQDTO();
                stockQDTO.setEnterpriseId(enterpriseId);
                stockQDTO.setGoodsId(vo.getMallProId());
                stockQDTO.setSkuId(vo.getMallProSkuId());
                stockQDTO.setStoreId(storeId);
                stockQDTO.setChannelType(resp.getResult().getOrderInfo().getBusinessType());
                ServiceResponse<Integer> stockResp = this.productStockApiService.queryGoodsStock(stockQDTO);
                logger.info("门店库存查询orderId={},qdto={},result={}", orderId, JSON.toJSONString(stockQDTO),
                        JSON.toJSONString(stockResp));
                if (stockResp.isSuccess() && null != stockResp.getResult()) {
                    vo.setStoreStock(stockResp.getResult());
                }else {
                    vo.setErrorMsg(stockResp.getMessage());
                }
                voList.add(vo);
            }
        }
        return RestResponse.successResult(voList);
    }

    // 订单-发货
    @RequestMapping("order-logistics-deliver")
    public RestResponse<Object> orderDeliver(String enterpriseId, String orderId, String storeId, String orderItemIds,
            String companyCode, String logisticsNo, String companyId, String companyName , String clerkId) {
        OrderShipmentQDTO qdto = new OrderShipmentQDTO();
        qdto.setEnterpriseId(enterpriseId);
        qdto.setLogisticsCompanyCode(companyCode);
        qdto.setLogisticsCompanyName(companyName);
        qdto.setLogisticsCompanyId(companyId);
        qdto.setCourierNumber(logisticsNo);
        qdto.setOrderId(orderId);
        // 门店发货
        qdto.setDeliveryMode(2);
        // 好办后台发货
        qdto.setSource(DeliveryOptTypeEnum.HAOBAN.getCode());
        List<String> orderItemIdList = Arrays.asList(orderItemIds.split(","));
        List<OrderItemShipmentQDTO> list = new ArrayList<>();
        orderItemIdList.forEach(o -> {
            OrderItemShipmentQDTO item = new OrderItemShipmentQDTO();
            item.setOrderItemId(o);
            item.setStoreId(storeId);
            list.add(item);
        });
        qdto.setOrderItemShipment(list);
        qdto.setOperationUserQDTO(this.getOper(clerkId));
        ServiceResponse<Boolean> resp = webOrderManageApiService.orderShipment(qdto);
        if (!resp.isSuccess()) {
            /*
             * String code = resp.getCode(); if (Arrays.asList("900001",
             * "300105", "200001").contains(code)) { return
             * RestResponse.failure(HaoBanErrCode.ERR_9600.getCode() + "",
             * "请刷新页面"); }
             */
            return RestResponse.failure(HaoBanErrCode.ERR_9600.getCode() + "", "请刷新页面");
        }
        return RestResponse.successResult(resp.getResult());
    }

    // 我的客户-会员订单列表
    // deliveryChannel 0全部 1快递 2自提
    // -1全部 1待付款 2待发货 7部分发货 4已完成 0已取消 5售后中
    // orderType -1 全部 0:会员自行购买 1导购推荐订单
    @RequestMapping("list-member-order")
    public RestResponse<Object> orderList(String enterpriseId, String memberId, String search,
            @RequestParam(defaultValue = "-1") int status, @RequestParam(defaultValue = "0") int deliveryChannel,
            @RequestParam(required = false) Integer businessType,
            @RequestParam(defaultValue = "-1") int orderType, BasePageInfo pageInfo, String startTime, String endTime) {
        if (StringUtils.isEmpty(memberId)) {
            return RestResponse.failure("9999", "memberId为空");
        }
        String strStatus = "" + status;
        // 全部
        if (status == -1) {
            strStatus = null;
        }
        // 售后中
        if (status == 5) {
            strStatus = "11";
        }
        Date startDate = null;
        if (StringUtils.isNotEmpty(startTime)) {
            startDate = DateUtil.strToDate(startTime, "yyyy-MM-dd");
        }
        Date endDate = null;
        if (StringUtils.isNotEmpty(endTime)) {
            endDate = DateUtil.strToDate(endTime, "yyyy-MM-dd");
            endDate = DateUtil.getEndTimeOfDay(endDate);
        }
        // 查询门店
        ListOrderManageQDTO qdto = new ListOrderManageQDTO();
        qdto.setEnterpriseId(enterpriseId);
        qdto.setOrderStep(strStatus);
        qdto.setMemberId(memberId);
        qdto.setStartDate(startDate);
        qdto.setEndDate(endDate);
        qdto.setBusinessType(businessType);
        if (StringUtils.isNotEmpty(search)) {
            qdto.setSearchOrderType(SearchOrderTypeEnum.ORDER_NUMBER.getType());
            qdto.setSearchOrderParam(search);
        }
        return this.orderListSelect(qdto, pageInfo, true);
    }

    // 修改物流
    // type : 1: 下单 2：换货
    @RequestMapping("modify-order-logistics")
    public RestResponse<Object> modifyOrderDeliver(String memberId, String enterpriseId, String orderId, String storeId,
            String logisticsId, String companyCode, String logisticsNo, String companyId, String companyName,String clerkId ,
            @RequestParam(defaultValue = "1") int type) {
        logger.info("修改物流={},{}", orderId, type);
        UpdateOrderLogisticsQDTO qdto = new UpdateOrderLogisticsQDTO();
        qdto.setEnterpriseId(enterpriseId);
        qdto.setLogisticsCompanyCode(companyCode);
        qdto.setLogisticsCompanyName(companyName);
        qdto.setLogisticsCompanyId(companyId);
        qdto.setCourierNumber(logisticsNo);
        qdto.setOrderId(orderId);
        qdto.setLogisticsId(logisticsId);
        qdto.setType(type);
        this.webOrderManageApiService.updateOrderLogistics(qdto,this.getOper(clerkId));
        return RestResponse.successResult();
    }
    
    private OperationUserQDTO getOper(String clerkId) {
        ClerkDTO clerk = this.clerkService.getclerkById(clerkId) ;
        OperationUserQDTO dto = new OperationUserQDTO() ;
        dto.setOperatorId(clerk.getClerkId()) ;
        dto.setOperatorType(clerk.getClerkType());
        dto.setOperatorName(clerk.getClerkName());
        dto.setOperatorCode(clerk.getClerkCode());
        return dto ;
    }
    
    /**
     * 核销订单
     */
    @RequestMapping("/verification")
    public RestResponse<Object> verification(String enterpriseId, String clerkId, String writeOffCode, String orderId) {
        if (StringUtils.isEmpty(writeOffCode)) {
            return RestResponse.failure("9999", "核销码为空");
        }
        ClerkDTO clerkDTO = clerkService.getClerkByClerkId(clerkId);
        if (null == clerkDTO) {
            return RestResponse.failure("9999", "核销人不存在");
        }
        // 微商城核销
        if (StringUtils.isEmpty(orderId)) {
            return RestResponse.failure("9999", "订单ID为空");
        }
        SelfPickOffQDTO qdto = new SelfPickOffQDTO();
        qdto.setEnterpriseId(enterpriseId);
        qdto.setWriteOffClerkId(clerkId);
        qdto.setWriteOffCode(writeOffCode);
        qdto.setSource(1);
        qdto.setWriteOffClerkCode(clerkDTO.getClerkCode());
        qdto.setOrderId(orderId);
        ServiceResponse<Boolean> response = webOrderManageApiService.selfPickOff(qdto);
        if (!response.isSuccess()) {
            return RestResponse.failure(response.getCode(), response.getMessage());
        }
        return RestResponse.successResult(response.getResult());
    }

    // 核销数量
    @RequestMapping("/verification-count")
    public RestResponse<Object> verificationCountNew(String enterpriseId, String storeId, String clerkId) {
        int integralDoneCount =  0 ; // this.count(enterpriseId, storeId, clerkId, 4 , 2);
        int integralUndoneCount = 0 ; // this.count(enterpriseId, storeId, clerkId, 2,2);
        // 查询微商城
        int mallDoneCount = this.count(enterpriseId, storeId, clerkId, 4 , 1);
        int mallUndoneCount = this.count(enterpriseId, storeId, clerkId, 2,1);
        HxOrderCountVO vo = new HxOrderCountVO();
        vo.setIntegralDoneCount(integralDoneCount);
        vo.setIntegralUndoneCount(integralUndoneCount);
        vo.setMallDoneCount(mallDoneCount);
        vo.setMallUndoneCount(mallUndoneCount);
        vo.setTotalDoneCount(integralDoneCount + mallDoneCount);
        vo.setTotalUndownCount(integralUndoneCount + mallUndoneCount);
        return RestResponse.successResult(vo);
    }

    private int count(String enterpriseId, String storeId, String clerkId, int step , int businessType) {
        // 查询门店
        ListOrderManageQDTO qdto = new ListOrderManageQDTO();
        qdto.setEnterpriseId(enterpriseId);
        // 配送方式 -1：所有 2：门店自提 1：快递发货
        qdto.setDeliveryChannel(2);
        qdto.setPickUpStoreId(storeId);
        if (step == 4) {
            qdto.setWriteOffClerkId(clerkId);
            qdto.setDeliveryOptType(1);
        }
        qdto.setOrderStep("" + step);
        qdto.setPageNum(1);
        qdto.setPageSize(1);
        // qdto.setBusinessType(businessType);
        ServiceResponse<Page<ListOrderDTO>> ret = webOrderManageApiService.listOrder(qdto);
        logger.info("核销订单数={}");
        return ret.getResult().getTotalCount();
    }

    // 订单详情
    public OrderDetailVO getOrderDetail(String enterpriseId, OrderInfoDTO orderInfo,
            List<ListOrderItemDTO> orderItemDTOList, String storeId) {
        OrderDetailVO orderDetailVO = EntityUtil.changeEntityByJSON(OrderDetailVO.class, orderInfo);
        if(null != orderInfo.getPickUpDetail()) {
            orderDetailVO.setPickUpReserveTime(orderInfo.getPickUpDetail().getGoodsTime());
        }
        orderDetailVO.setUsePoint(orderInfo.getUsePoints());
        orderDetailVO.setBuyerRemark(orderInfo.getRemarks());
        List<OrderDetailItemVO> orderItemList = EntityUtil.changeEntityListNew(OrderDetailItemVO.class,
                orderItemDTOList);
        orderDetailVO.setOrderItemList(orderItemList);
        String memberId = orderInfo.getMemberId();
        MemberInfoVO member = new MemberInfoVO();
        member.setMemberId(memberId);
        if (StringUtils.isNotEmpty(memberId)) {
            ServiceResponse<MemberStoreInfoDTO> memberResp = this.memberReferClerkApiService.getMemberInfo(enterpriseId,
                    memberId);
            MemberStoreInfoDTO memberInfo = memberResp.getResult();
            if (null != memberInfo) {
                member = EntityUtil.changeEntityByJSON(MemberInfoVO.class, memberInfo);
            }
        }
        member.setAddressPhone(orderInfo.getBuyerPhone());
        member.setAddressName(orderInfo.getBuyerName());
        member.setAddressDetail(orderInfo.getFullName() + orderInfo.getAddressInfo());
        orderDetailVO.setAddressInfo(orderInfo.getFullName() + orderInfo.getAddressInfo());
        if(orderInfo.getBusinessType()==1) {
            member.setBelongClerkId(orderInfo.getBelongClerkId());
            member.setBelongClerkCode(orderInfo.getBelongClerkCode());
            member.setBelongClerkName(orderInfo.getBelongClerkName());
            member.setBelongStoreId(orderInfo.getBelongStoreId());
            member.setBelongStoreCode(orderInfo.getBelongStoreCode());
            member.setBelongStoreName(orderInfo.getBelongStoreName());
        }
        orderDetailVO.setMember(member);
        // 判断能否发货
        // 导购发货，一笔订单仅允许单门店发货
        boolean canDeliverFlag = false;
        // 发货操作类型(0后台/1好办门店):用于判断好办操作发货还是后台，防止双边发货
        Integer deliveryOptType = orderInfo.getDeliveryOptType();
        logger.info("发货类型1好办={},orderId={}", deliveryOptType, orderInfo.getOrderId());
        if (null == deliveryOptType) {
            canDeliverFlag = true;
        } else if (deliveryOptType == 1) {
            canDeliverFlag = true;
        }
        orderDetailVO.setCanDeliverFlag(canDeliverFlag);
        // 核销导购
        String verificationClerkName = orderInfo.getWriteOffClerkName();
        orderDetailVO.setVerificationClerkName(verificationClerkName);
        return orderDetailVO;
    }

    // 订单列表
    private RestResponse<Object> orderListSelect(ListOrderManageQDTO qdto, BasePageInfo pageInfo, boolean evaluteFlag) {
        qdto.setPageNum(pageInfo.getPageNum());
        qdto.setPageSize(pageInfo.getPageSize());
        ServiceResponse<Page<ListOrderDTO>> ret = webOrderManageApiService.listOrder(qdto);
        logger.info("订单信息={}", JSON.toJSONString(ret, true));
        if (ret.isSuccess()) {
            Page<ListOrderDTO> page = ret.getResult();
            List<OrderListVO> voList = new ArrayList<>();
            List<String> orderIdList = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(page.getResult())) {
                List<ListOrderDTO> orderList = page.getResult();
                for (ListOrderDTO order : orderList) {
                    orderIdList.add(order.getOrderId());
                    OrderListVO vo = EntityUtil.changeEntityByJSON(OrderListVO.class, order);
                    List<ListOrderItemDTO> itemList = order.getOrderItemDTOList();
                    List<OrderListItemVO> voItemList = EntityUtil.changeEntityListNew(OrderListItemVO.class, itemList);
                    vo.setOrderItemList(voItemList);
                    vo.setPickUpTime(order.getWriteOffTime());
                    vo.setUsePoint(order.getUsePoints());
                    // 核销导购
                    String verificationClerkName = order.getWriteOffClerkName();
                    vo.setVerificationClerkName(verificationClerkName);
                    String clerkId = order.getBelongClerkId();
                    if (StringUtils.isNotEmpty(clerkId)) {
                        ClerkDTO clerkDTO = this.clerkService.getclerkById(clerkId);
                        if (null != clerkDTO) {
                            vo.setBelongClerkName(clerkDTO.getClerkName());
                        }
                    }
                    voList.add(vo);
                }
            }
            String enterpriseId = qdto.getEnterpriseId();
            // 评价
            if (evaluteFlag && CollectionUtils.isNotEmpty(orderIdList)) {
                ServiceResponse<List<StoreEvaluateInfoDTO>> evaluateResp = evaluateDataApiService
                        .getEvaluateScoreAndContent(enterpriseId, orderIdList);
                Map<String, List<EvaluateVO>> evaluateMap = Optional.ofNullable(evaluateResp)
                        .map(ServiceResponse::getResult).orElse(new ArrayList<>()).stream().map(data -> {
                            EvaluateVO evaluateVO = new EvaluateVO();
                            String evaluateContent = data.getEvaluateContent();
                            evaluateVO.setEvaluateScoreList(new ArrayList<>());
                            if (CollectionUtils.isNotEmpty(data.getEvaluateRuleScores())) {
                                for (EvaluateRuleScoreDTO evaluateScoresDTO : data.getEvaluateRuleScores()) {
                                    EvaluateVO.EvaluateScore evaluateScore = new EvaluateVO.EvaluateScore();
                                    evaluateScore.setName(evaluateScoresDTO.getRuleName());
                                    evaluateScore.setValue(evaluateScoresDTO.getScore());
                                    evaluateVO.getEvaluateScoreList().add(evaluateScore);
                                }
                            }
                            evaluateVO.setReviews(evaluateContent);
                            evaluateVO.setOrderId(data.getOrderId());
                            return evaluateVO;
                        }).collect(Collectors.groupingBy(EvaluateVO::getOrderId));

                voList.forEach(item -> {
                    if (null != evaluateMap.get(item.getOrderId())) {
                        item.setEvaluateVO(evaluateMap.get(item.getOrderId()).get(0));
                    }
                });
            }
            Page<OrderListVO> retPage = PageHelperUtils.changePageToCurrentPage(ret.getResult(), OrderListVO.class);
            retPage.setResult(voList);
            return RestResponse.successResult(retPage);
        }
        return RestResponse.failure(ret.getCode(), ret.getMessage());
    }
}
