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

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
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.alibaba.fastjson.JSONArray;
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.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.dto.evaluation.CreateRecordRequest;
import com.gic.haoban.app.aggregation.api.dto.evaluation.OrderProductRequest;
import com.gic.haoban.app.aggregation.api.dto.evaluation.OrderVerificationRecordDTO;
import com.gic.haoban.app.aggregation.api.service.evaluation.OrderVerificationRecordApiService;
import com.gic.haoban.common.utils.HaobanResponse;
import com.gic.haoban.manage.web.errCode.HaoBanErrCode;
import com.gic.haoban.manage.web.qo.order.integral.ClerkQo;
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.CheckVO;
import com.gic.haoban.manage.web.vo.order.integral.HxOrderCountVO;
import com.gic.haoban.manage.web.vo.order.integral.ProductSku;
import com.gic.haoban.manage.web.vo.order.integral.ProductVO;
import com.gic.haoban.manage.web.vo.order.integral.ScanVO;
import com.gic.integralmall.api.dto.IntegralMallExchangeLogDTO;
import com.gic.integralmall.api.enums.IntegralMallExchangeLogStatusEnums;
import com.gic.integralmall.api.service.IntegralmallService;
import com.gic.integralmall.api.service.result.DubboResult;
import com.gic.store.goods.dto.stock.GoodsStockBaseQDTO;
import com.gic.store.goods.enums.ProductStockChannelType;
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;

    // 发货订单列表 (0全部,待发货2+待收货3,部分发货7)
    @RequestMapping("list-order")
    public RestResponse<Object> orderList(String enterpriseId, String storeId, String clerkId, String search,
            @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);
        // 微商城
        qdto.setBusinessType(OrderEnum.BusinessTypeEnum.MICRO_MALL.getType());
        // 配送方式 -1：所有 2：门店自提 1：快递发货
        qdto.setDeliveryChannel(1);
        // 库存 - 门店库存2
        qdto.setDeliveryMode(2);
        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) {
        OrderCountVO vo = new OrderCountVO();
        if (StringUtils.isEmpty(storeId)) {
            return RestResponse.successResult(vo);
        }
        CountOrderStatusQDTO qdto = new CountOrderStatusQDTO();
        qdto.setEnterpriseId(enterpriseId);
        qdto.setBusinessType(OrderEnum.BusinessTypeEnum.MICRO_MALL.getType());
        // 配送方式 -1：所有 2：门店自提 1：快递发货
        qdto.setDeliveryChannel(1);
        // 库存 - 门店库存2
        qdto.setDeliveryMode(2);
        qdto.setBelongStoreId(storeId);
        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(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.setBusinessType(OrderEnum.BusinessTypeEnum.MICRO_MALL.getType());
        qdto.setSearchOrderParam(search);
        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", "核销码为空");
        }
        // 微商城
        if (writeOffCode.startsWith("M")) {
            // 通过核销码查询
            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);
                return RestResponse.successResult(orderDetailVO);
            } else {
                return RestResponse.failure("9999", ret.getMessage());
            }
        } else {
            // 积分商城
            DubboResult<IntegralMallExchangeLogDTO> integralResult = integralmallService
                    .getIntegralMallExchangeLogByWriteOffCode(enterpriseId, writeOffCode);
            if (null != integralResult && null != integralResult.getData()) {
                ScanVO vo = integralMallScan(integralResult.getData());
                return RestResponse.successResult(vo);
            }
        }
        return RestResponse.failure("9999", "订单查询不到");
    }

    // 单笔订单发货商品列表
    @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(ProductStockChannelType.MALL.getCode());
                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());
                }
                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) {
        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);
        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(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(OrderEnum.BusinessTypeEnum.MICRO_MALL.getType());
        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,
            @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);
        return RestResponse.successResult();
    }

    /**
     * 核销订单
     */
    @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 (writeOffCode.startsWith("M")) {
            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());
        } else {
            ClerkQo clerkQo = new ClerkQo();
            clerkQo.setClerkCode(clerkDTO.getClerkCode());
            clerkQo.setClerkId(clerkDTO.getClerkId());
            clerkQo.setStoreId(clerkDTO.getStoreId());
            clerkQo.setClerkName(clerkDTO.getClerkName());
            clerkQo.setEnterpriseId(enterpriseId);
            logger.info("积分商城订单核销开始，核销码：{} ,核销人：{} ", writeOffCode, clerkQo.getClerkId());
            enterpriseId = clerkDTO.getEnterpriseId();
            DubboResult<Boolean> check = integralmallService.haobanVerificationExchangeLog(enterpriseId, writeOffCode,
                    clerkQo.getClerkCode(), clerkQo.getClerkName(), clerkQo.getStoreId());
            logger.info("核销结果：{} ", JSON.toJSONString(check));
            CheckVO checkVO = new CheckVO();
            if (check.getSuccess()) {
                // 积分商城核销成功-添加核销记录
                String recordId = createIntegralRecord(enterpriseId, 1, clerkQo, writeOffCode);
                checkVO.setId(recordId);
                checkVO.setSuccess(Boolean.TRUE);
                checkVO.setCode(HaoBanErrCode.ERR_1.getCode());
                return RestResponse.successResult(checkVO);
            }
            /*
             * 核销失败情况 10001 兑换记录不存在 10002 当前订单状态无法核销 10003 该订单已经核销 10004 订单已经取消
             * 10005 10006 超期核销
             */
            checkVO.setCode(check.getErrorCode());
            checkVO.setMessage(check.getErrMessage());
            checkVO.setSuccess(Boolean.FALSE);
            if (check.getErrorCode() == HaoBanErrCode.ERR_100010.getCode()) {
                // 订单已核销
                OrderVerificationRecordDTO record = orderVerificationRecordApiService
                        .getRecordByClerkIdAndWriteOffCode(clerkQo.getClerkId(), writeOffCode);
                if (Objects.nonNull(record)) {
                    checkVO.setSuccess(Boolean.TRUE);
                    checkVO.setId(record.getRecordId());
                    return RestResponse.successResult(checkVO);
                }
                // 超期核销
                checkVO.setCode(HaoBanErrCode.ERR_100014.getCode());
                checkVO.setMessage(HaoBanErrCode.ERR_100014.getMsg());
            }
            if (!checkVO.getSuccess()) {
                HaobanResponse response = new HaobanResponse();
                response.setMessage(checkVO.getMessage());
                response.setErrorCode(checkVO.getCode());
                response.setResult(checkVO.getId());
                response.setDetailError("");
                return RestResponse.failure("9999", checkVO.getMessage());
            }
            return RestResponse.successResult(checkVO) ;
        }
    }

    // 核销数量
    @RequestMapping("/verification-count")
    public RestResponse<Object> verificationCountNew(String enterpriseId, String storeId, String clerkId) {
        Page<IntegralMallExchangeLogDTO> page = new Page<IntegralMallExchangeLogDTO>();
        page.setPageSize(1);
        page.setCurrentPage(1);
        Map<String, Object> params = new HashMap<>();
        params.put("enterpriseId", enterpriseId);
        params.put("proType", 2);
        params.put("changeType", 4);
        // 订单状态
        params.put("orderStatus", 1);
        params.put("goodsPointStoreId", storeId);
        page.setParams(params);
        page = integralmallService.listOnlineByPage(page);
        int integralUndoneCount = page.getTotalCount();
        int integralDoneCount = this.orderVerificationRecordApiService.countByGicClerkId(clerkId);
        // 查询微商城
        int mallDoneCount = this.count(enterpriseId, storeId, clerkId, 4);
        int mallUndoneCount = this.count(enterpriseId, storeId, clerkId, 2);
        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) {
        // 查询门店
        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.setBusinessType(OrderEnum.BusinessTypeEnum.MICRO_MALL.getType());
        qdto.setPageNum(1);
        qdto.setPageSize(1);
        ServiceResponse<Page<ListOrderDTO>> ret = webOrderManageApiService.listOrder(qdto);
        logger.info("核销订单数={}");
        return ret.getResult().getTotalCount();
    }

    // 订单详情
    private OrderDetailVO getOrderDetail(String enterpriseId, OrderInfoDTO orderInfo,
            List<ListOrderItemDTO> orderItemDTOList, String storeId) {
        OrderDetailVO orderDetailVO = EntityUtil.changeEntityByJSON(OrderDetailVO.class, orderInfo);
        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());
        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());
                    // 核销导购
                    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());
    }

    private String createIntegralRecord(String enterpriseId, int status, ClerkQo clerkDTO, String writeOffCode) {
        DubboResult<IntegralMallExchangeLogDTO> integralResult = integralmallService
                .getIntegralMallExchangeLogByWriteOffCode(enterpriseId, writeOffCode);
        IntegralMallExchangeLogDTO data = integralResult.getData();
        CreateRecordRequest record = new CreateRecordRequest();
        record.setRecordId(data.getIntegralMallProExchangeId());
        record.setStatus(status);
        record.setEnterpriseId(data.getEnterpriseId());
        record.setExchangeId(data.getIntegralMallProExchangeId());
        record.setFinishTime(data.getFinishTime());
        record.setWriteOffCode(data.getWriteOffCode());
        // 提货人
        record.setConsignee(data.getGoodsPerson());
        record.setConsigneePhone(data.getGoodsPhone());
        record.setPoint(data.getGoodsPoint());
        record.setAddress(data.getGoodsAddress());
        record.setTakeTime(data.getGoodsTime());
        record.setFetchCode(writeOffCode);
        // 核销人
        record.setClerkId(clerkDTO.getClerkId());
        record.setClerkCode(clerkDTO.getClerkCode());
        record.setClerkName(clerkDTO.getClerkName());
        record.setHaobanClerkId(clerkDTO.getHaobanClerkId());
        record.setHaobanEnterpriseId(clerkDTO.getHaobanEnterpriseId());
        // 商品信息

        OrderProductRequest productDTO = new OrderProductRequest();
        productDTO.setProName(data.getProName());
        productDTO.setProImage(data.getPhotoUrl());
        productDTO.setProCode(data.getProCode());
        productDTO.setProNumber(data.getGoodsNum());

        productDTO.setProSku(
                StringUtils.isBlank(data.getSku()) ? "[]" : JSONArray.parseArray(data.getSku()).toJSONString());
        productDTO.setProPrice((data.getCashShouldPay() / data.getGoodsNum()));
        productDTO.setProIntegral((data.getIntegralShouldPay() / data.getGoodsNum()));

        List<OrderProductRequest> productDTOS = new ArrayList<>(2);
        productDTOS.add(productDTO);
        record.setProducts(productDTOS);
        record.setCreateTime(data.getCreateTime());
        record.setUpdateTime(new Date());
        // 订单信息
        record.setAllCostIntegral(data.getAllCostIntegral());
        record.setPayCost(data.getPayCost());
        record.setOrderNo(data.getDefinedCode());
        record.setPayNumber(data.getPayNumber());
        record.setPayTime(data.getPayTime());
        record.setOrigin(2);
        return orderVerificationRecordApiService.createRecord(record);
    }

    private ScanVO integralMallScan(IntegralMallExchangeLogDTO exchangeLogDTO) {
        ScanVO scanVO = new ScanVO();
        scanVO.setHasOrder(1);
        scanVO.setOrderNo(exchangeLogDTO.getDefinedCode());
        scanVO.setEnterpriseId(exchangeLogDTO.getEnterpriseId());
        scanVO.setExchangeId(exchangeLogDTO.getIntegralMallProExchangeId());
        scanVO.setAllCostIntegral(exchangeLogDTO.getAllCostIntegral());
        scanVO.setPayCost(exchangeLogDTO.getPayCost());
        scanVO.setPayNumber(exchangeLogDTO.getPayNumber());
        scanVO.setPayTime(exchangeLogDTO.getPayTime());

        ProductVO productVO = new ProductVO();
        productVO.setProName(exchangeLogDTO.getProName());
        productVO.setProCode(exchangeLogDTO.getProCode());
        productVO.setProSku(StringUtils.isBlank(exchangeLogDTO.getSku()) ? new ArrayList<>()
                : JSONArray.parseArray(exchangeLogDTO.getSku(), ProductSku.class));
        productVO.setProNumber(exchangeLogDTO.getGoodsNum());
        productVO.setProImage(exchangeLogDTO.getPhotoUrl());
        productVO.setProPrice((exchangeLogDTO.getCashShouldPay() / exchangeLogDTO.getGoodsNum()));
        productVO.setProIntegral((exchangeLogDTO.getIntegralShouldPay() / exchangeLogDTO.getGoodsNum()));

        scanVO.pushProduct(productVO);

        scanVO.setWriteOffCode(exchangeLogDTO.getWriteOffCode());
        scanVO.setFetchCode(exchangeLogDTO.getWriteOffCode());

        scanVO.setConsignee(exchangeLogDTO.getGoodsPerson());
        scanVO.setConsigneePhone(exchangeLogDTO.getGoodsPhone());
        scanVO.setPoint(exchangeLogDTO.getGoodsPoint());
        scanVO.setAddress(exchangeLogDTO.getGoodsAddress());
        scanVO.setTakeTime(exchangeLogDTO.getGoodsTime());
        scanVO.setCreateTime(exchangeLogDTO.getCreateTime());
        // 兑换状态 -2兑换取消(退货) -1兑换无效 0兑换取消(礼品未付款) 11兑换中(加钱购待支付) 3已发货(礼品) 1兑换功成
        // 2领取(卡券) 4成功
        // 其实只需要 1 2 4
        scanVO.setStatus(exchangeLogDTO.getStatus() == 4 ? 1 : 0);
        scanVO.setChecked(0);
        if (scanVO.getStatus() == 1) {
            scanVO.setRecordId(exchangeLogDTO.getIntegralMallProExchangeId());
            OrderVerificationRecordDTO info = orderVerificationRecordApiService.recordInfo(scanVO.getRecordId());
            if (null != info) {
                // 说明已经核销了
                scanVO.setFinishTime(info.getFinishTime());
                scanVO.setChecked(1);
            }
            if (exchangeLogDTO.getStatus() == IntegralMallExchangeLogStatusEnums.CONFIRM.getStatus()) {
                scanVO.setFinishTime(exchangeLogDTO.getFinishTime());
                scanVO.setChecked(1);
            }
        }
        return scanVO;
    }
}
