package com.neusoft.smart.pos.order.service;


import com.google.common.collect.Lists;
import com.neusoft.smart.pos.constants.DictionaryConstant;
import com.neusoft.smart.pos.dto.trade.request.GetShopOrderDetailsForPosRequest;
import com.neusoft.smart.pos.dto.trade.request.GetTradeShopOrderDetailsRequest;
import com.neusoft.smart.pos.dto.trade.response.GetShopOrderDetailsForPosResponse;
import com.neusoft.smart.pos.dto.trade.response.GetShopOrderDetailsResponse;
import com.neusoft.smart.pos.dto.trade.response.GetShopOrderSummaryResponse;
import com.neusoft.smart.pos.framework.bean.PaginationExtendBean;
import com.neusoft.smart.pos.framework.exception.BusinessCommonException;
import com.neusoft.smart.pos.framework.utils.*;
import com.neusoft.smart.pos.order.constants.TradeErrorCode;
import com.neusoft.smart.pos.order.persistent.domain.OrderMasterExample;
import com.neusoft.smart.pos.order.persistent.domain.OrderMasterExt;
import com.neusoft.smart.pos.order.persistent.domain.OrderMasterExtExample;
import com.neusoft.smart.pos.order.repository.OrderMasterRepository;
import com.neusoft.smart.pos.order.repository.OrderTransactionRepository;
import com.neusoft.smart.pos.payorder.persistent.domain.PayOrder;
import com.neusoft.smart.pos.payorder.service.PayOrderService;
import com.neusoft.smart.pos.redis.bean.DeviceInfo;

import com.neusoft.smart.pos.utils.PosDeviceRedisUtils;
import lombok.val;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;

@Service("orderStatisticsService")
public class OrderStatisticsService {
    private final static Logger logger = LoggerFactory.getLogger(OrderStatisticsService.class);
    @Autowired
    private OrderMasterRepository orderMasterRepository;
    @Autowired
    private PayOrderService payOrderService;

    @Autowired
    private OrderTransactionRepository orderTransactionRepository;

    /**
     * 门店订单汇总查询方法
     *
     * @return
     */
    public PaginationExtendBean<GetShopOrderSummaryResponse> queryShopOrderSummary(Integer orgId, List<Integer> shopIds, String startDate, String endDate, Integer offset, Integer limit, Boolean isPage) {
        val paginationExtendBean = new PaginationExtendBean<GetShopOrderSummaryResponse>();
        //1.获取数据查询条件
        Date startTime = null;
        Date endTime = null;
        if(StringUtils.isEmpty(startDate)){
            startTime = LocalDateTimeUtils.convertLocalDateTimeToDate(LocalDateTimeUtils.getCurrentDayStart());
        }else{
            startTime = DateUtils.getDayStartTime(DateUtils.parse(startDate,DateUtils.FORMAT_SHORT));
        }
        if(StringUtils.isEmpty(endDate)){
            endTime = LocalDateTimeUtils.convertLocalDateTimeToDate(LocalDateTimeUtils.getCurrentDayEnd());
        }else{
            endTime = DateUtils.getDayEndTime(DateUtils.parse(endDate,DateUtils.FORMAT_SHORT));
        }
        //2.查询门店订单统计信息
        val example = new OrderMasterExtExample();
        example.createCriteria()
                .andOrgIdEqualTo(orgId)
                .andOrderCreatedAtGreaterThanOrEqualTo(startTime)
                .andOrderCreatedAtLessThan(endTime);
        // //统计所有状态订单
//                .andOrderTypeNotEqualTo(DictionaryConstant.ORDER_TYPE_HYCZ.getCode());
        if (null != shopIds && shopIds.size() >= 0) {
            example.getOredCriteria().get(0).andShopIdIn(shopIds);
        }
        if (isPage) {
            example.setLimit(limit);
            example.setOffset(offset);
        }

        List<OrderMasterExt> orderMasterExts = orderMasterRepository.queryShopOrderSummary(example);
        paginationExtendBean.setTotal(shopIds.size());

        //2.进行数据整理
        List<GetShopOrderSummaryResponse> shopOrders = convertOrderMaster2ShopOrderSummary(orderMasterExts);

        //3.整理返回数据,将订单中不存在的门店ID也添加至返回数据中
        if (isPage && shopOrders.size() < limit) {
            //获取在订单表中存在订单的门店Id列表
            example.clear();
            example.createCriteria()
                    .andOrgIdEqualTo(orgId)
                    .andOrderCreatedAtGreaterThanOrEqualTo(startTime)
                    .andOrderCreatedAtLessThan(endTime);
            //统计所有状态订单
//                    .andOrderTypeNotEqualTo(DictionaryConstant.ORDER_TYPE_HYCZ.getCode());
            val orderMasterTemps = orderMasterRepository.queryShopOrderSummary(example);
            List<Integer> existShopId = Lists.newArrayList();    //存储订单中已存在的门店ID
            orderMasterTemps.forEach(temps -> {
                existShopId.add(temps.getShopId());
            });
            //从传入的门店ID中排除已存在的门店ID
            shopIds.removeAll(existShopId);
            //再排除已显示过的门店ID数
            Integer removeCount = offset - existShopId.size();
            if (shopIds.size() <= removeCount) {
                shopIds.clear();
            } else {
                for (int z = 0; z < removeCount; z++) {
                    shopIds.remove(0);
                }
            }

        }
        //排除后遍历剩下的门店ID数，直至与返回数据条数相等
        for (int i = 0; i < shopIds.size(); i++) {
            if (!isPage) {
                val shopOrderSummaryResponse = new GetShopOrderSummaryResponse();
                shopOrderSummaryResponse.setOrgId(orgId);
                shopOrderSummaryResponse.setShopId(shopIds.get(i));
                shopOrders.add(shopOrderSummaryResponse);
            } else if (shopOrders.size() < limit) {
                val shopOrderSummaryResponse = new GetShopOrderSummaryResponse();
                shopOrderSummaryResponse.setOrgId(orgId);
                shopOrderSummaryResponse.setShopId(shopIds.get(i));
                shopOrders.add(shopOrderSummaryResponse);
            } else {
                break;
            }
        }
        paginationExtendBean.setRows(shopOrders);
        return paginationExtendBean;
    }

    private List<GetShopOrderSummaryResponse> convertOrderMaster2ShopOrderSummary(List<OrderMasterExt> orderMasterExts) {
        List<GetShopOrderSummaryResponse> rs = new ArrayList<>();
        for (OrderMasterExt ome : orderMasterExts
        ) {
            GetShopOrderSummaryResponse item = new GetShopOrderSummaryResponse();
            item.setOrderCount(ome.getOrderCount());
            item.setOrgId(ome.getOrgId());
            item.setRechargeAmount(new BigDecimal(ome.getRechargeAmount()));
            item.setRechargeCount(ome.getRechargeCount());
            item.setShopId(ome.getShopId());
            item.setTotalAmount(new BigDecimal(ome.getTotalAmount()));
            rs.add(item);
        }
        return rs;
    }

    /**
     * 门店订单详情查询方法
     * WEB端门店流水
     * @return
     */
    public GetShopOrderDetailsResponse queryShopOrderDetails(GetTradeShopOrderDetailsRequest tradeShopOrderDetailsRequest) {
        //1.校验参数信息
        if (StringUtils.isEmpty(tradeShopOrderDetailsRequest.getTimeMode())) {
            throw new BusinessCommonException(TradeErrorCode.ORDER_STATISTICS_TIME_MODE_EMPTY);
        }
        if (!tradeShopOrderDetailsRequest.getTimeMode().equals("1") && !tradeShopOrderDetailsRequest.getTimeMode().equals("2")) {
            throw new BusinessCommonException(TradeErrorCode.ORDER_STATISTICS_TIME_MODE_ERROR);
        }
        if (tradeShopOrderDetailsRequest.getTimeMode().equals("1")) {
            if (StringUtils.isEmpty(tradeShopOrderDetailsRequest.getStartTime()) && StringUtils.isEmpty(tradeShopOrderDetailsRequest.getEndTime())) {

            } else if (StringUtils.isEmpty(tradeShopOrderDetailsRequest.getStartTime()) || StringUtils.isEmpty(tradeShopOrderDetailsRequest.getEndTime())) {
                throw new BusinessCommonException(TradeErrorCode.ORDER_STATISTICS_START_END_TIME_EMPTY);
            }
        }
        if (tradeShopOrderDetailsRequest.getTimeMode().equals("2")) {
            if (StringUtils.isEmpty(tradeShopOrderDetailsRequest.getDateTime())) {
                throw new BusinessCommonException(TradeErrorCode.ORDER_STATISTICS_DATE_TIME_EMPTY);
            }
        }

        List<Map> orderMasters;
        Map totalMap;
        Integer orderCount;
        //2.整理查询条件
        val example4JoinO = shopOrderDetails4WebExampleHandle(tradeShopOrderDetailsRequest, true);
        if (StringUtils.isEmpty(tradeShopOrderDetailsRequest.getPayType())) {
            val example = shopOrderDetails4WebExampleHandle(tradeShopOrderDetailsRequest, false);
            //3.查询门店订单详情信息
            //example.getOredCriteria().get(0).andOrderStatusGreaterThan(DictionaryConstant.ORDER_UPDATE_STATUS_ZFZ.getCode());
            orderCount = orderMasterRepository.queryShopOrderDetailsCount(example);
            totalMap = orderMasterRepository.queryShopOrderDetailsTotalAmount(example);//查询满足条件的总记录条数
            if (tradeShopOrderDetailsRequest.getIsPage()) {
                example4JoinO.setLimit(tradeShopOrderDetailsRequest.getLimit());
                example4JoinO.setOffset(tradeShopOrderDetailsRequest.getOffset());
            }
            example4JoinO.setDeviceStatus(tradeShopOrderDetailsRequest.getDeviceStatus());
            if(orderCount>0) {
                orderMasters = orderMasterRepository.queryShopOrderDetails4Web(example4JoinO);
            }
            else {
                orderMasters = new ArrayList<>();
            }
        }
        else
        {
            orderCount = orderMasterRepository.countShopOrderDetailsLeftJoinPayOrderCount(example4JoinO);
            totalMap = orderMasterRepository.queryShopOrderDetailsLeftJoinPayOrderTotalAmount(example4JoinO);
            if (tradeShopOrderDetailsRequest.getIsPage()) {
                example4JoinO.setLimit(tradeShopOrderDetailsRequest.getLimit());
                example4JoinO.setOffset(tradeShopOrderDetailsRequest.getOffset());
            }
            example4JoinO.setDeviceStatus(tradeShopOrderDetailsRequest.getDeviceStatus());
            List<String> pagedOrderNumbers = orderMasterRepository.querySpecialPayTypeShopOrderNumbers4Web(example4JoinO);
            example4JoinO.clear();
            if(pagedOrderNumbers.size()>0) {
                example4JoinO.createCriteria().andOrderNumberIn(pagedOrderNumbers);
                orderMasters = orderMasterRepository.queryShopOrderDetails4Web(example4JoinO);
            }
            else {
                orderMasters = new ArrayList<>();
            }
        }


        //4.进行数据整理
        List<GetShopOrderDetailsResponse.ShopOrderDetail> shopOrderDetails = convertOrderMaster2ShopOrderDetail(orderMasters);

        val paginationExtendBean = new PaginationExtendBean<GetShopOrderDetailsResponse.ShopOrderDetail>();

        //5.查询系统支付渠道信息
        if (null != shopOrderDetails && shopOrderDetails.size() > 0) {
            shopOrderDetails.forEach(shopOrder -> {
                //5.2处理订单状态名称
                //订单状态(9状态)
                shopOrder.setOrderStatusName(getOrderStatusName(shopOrder.getOrderStatus()));
                //5.3如果已退款，则设置获得积分为0
                if (DictionaryConstant.ORDER_STATUS_YTK.getCode().equals(shopOrder.getOrderStatus())) {
                    shopOrder.setScore(0);
                }
            });
        }

        paginationExtendBean.setRows(shopOrderDetails);
        paginationExtendBean.setTotal(orderCount);

        val shopOrderDetailsResponse = new GetShopOrderDetailsResponse();
        shopOrderDetailsResponse.setTotalAmount(new BigDecimal(totalMap.get("orderAmount").toString()));    //存入订单总金额
        shopOrderDetailsResponse.setTotalMemberPoint(new BigDecimal(totalMap.get("score").toString()));
        shopOrderDetailsResponse.setPaginationExtendBean(paginationExtendBean);
        return shopOrderDetailsResponse;
    }

    private List<GetShopOrderDetailsResponse.ShopOrderDetail> convertOrderMaster2ShopOrderDetail(List<Map> orderMasters) {
        List<GetShopOrderDetailsResponse.ShopOrderDetail> rs = new ArrayList<>();
        for (Map order : orderMasters
        ) {
            GetShopOrderDetailsResponse.ShopOrderDetail detail = new GetShopOrderDetailsResponse.ShopOrderDetail();
            MapBeanUtils.mapToBean(order, detail);
            detail.setOrgId(Integer.parseInt(order.get("orgId").toString()));
            detail.setShopId(Integer.parseInt(order.get("shopId").toString()));
            detail.setOrderNumber(order.get("orderNumber").toString());
            detail.setSerialNo(order.get("serialNo").toString());
            detail.setDeviceName(order.get("deviceName")+"");
            //detail.setMemberCardNo(order.)
            //detail.setmemberName (order.get);
            //detail.setcardNum (order.getN);
            detail.setCustomerName((order.get("createdBy").toString()));
            detail.setOrderAmount(new BigDecimal(order.get("orderAmount").toString()));
            detail.setDiscountAmount(new BigDecimal(order.get("discount").toString()));
            detail.setRealPayAmount(new BigDecimal(order.get("paidAmount").toString()));
            detail.setPayAmount(new BigDecimal(order.get("shouldAmount").toString()));
            //detail.setdiscountAmount;
            //if(order.get("payTypeName")!=null)
            detail.setPayTypeName(order.get("payTypeName").toString());
            if(detail.getPayTypeName().equals("to query"))
            {
                detail.setPayTypeName(getOrderPayDetailString(order.get("orderNumber").toString()));
            }
            detail.setPayType(detail.getPayTypeName());
            detail.setOrderStatus(order.get("orderStatus").toString());
            //detail.setorderStatusName;//一会儿加
            //detail.setOrderType(order.get("orderType").toString());//没有这一列
            //detail.setOrderTypeName = "";//没有这一列
            detail.setMemberPoint(Integer.parseInt(order.get("score").toString()));
            detail.setCreatedAt(DateUtils.parse(order.get("createdAt").toString(), DateUtils.FORMAT_LONG));
            rs.add(detail);
        }
        return rs;
    }

    private String getOrderPayDetailString(String orderNumber) {
        String rs = "";
        List<Map> details = orderMasterRepository.getOrderPayDetail(orderNumber);
        if(details.size()==1)
        {
            rs = rs.concat(details.get(0).get("payTypeName").toString());
        }
        else if(details.size() > 1) {
            for (Map detail : details
            ) {
                rs = rs.concat(detail.get("payTypeName").toString());
                rs = rs.concat(detail.get("payTypeAmountString").toString());
                rs = rs.concat(",");
            }
            rs = rs.substring(0, rs.length() - 1);
        }
        return rs;
    }



    private Long getOrderRealPayAmount(String orderNumber) {
        Long hasPayAmountSum = orderMasterRepository.queryHasPayAmountSum(orderNumber);
        Long hasRefuntAmountSum = orderMasterRepository.queryHasRefundAmountSum(orderNumber);
        return hasPayAmountSum-hasRefuntAmountSum;
    }

    /**
     * 整理查询条件信息
     *
     * @param tradeShopOrderDetailsRequest
     * @return
     */
    private OrderMasterExample shopOrderDetails4WebExampleHandle(GetTradeShopOrderDetailsRequest tradeShopOrderDetailsRequest, Boolean joinO) {
        val example = new OrderMasterExample();
        val criteria = example.createCriteria();

        ConditionUtils.setWithCondition(tradeShopOrderDetailsRequest.getOrgId(), v-> (v != null), criteria::andOrgIdEqualTo);

        //1.处理门店ID
        if (null != tradeShopOrderDetailsRequest.getShopIds() && tradeShopOrderDetailsRequest.getShopIds().size() > 0) {
           if (joinO) example.getOredCriteria().get(0).andOdotShopIdIn(tradeShopOrderDetailsRequest.getShopIds());
           else example.getOredCriteria().get(0).andShopIdIn(tradeShopOrderDetailsRequest.getShopIds());
        }
        //2.处理订单编号
        if (!StringUtils.isEmpty(tradeShopOrderDetailsRequest.getOrderNumber())) {
            if (joinO) example.getOredCriteria().get(0).andOdotOrderNumberLike(tradeShopOrderDetailsRequest.getOrderNumber());
            else example.getOredCriteria().get(0).andOrderNumberLike("%"+tradeShopOrderDetailsRequest.getOrderNumber()+"%");
        }
        //3.处理POS编码
        if (!StringUtils.isEmpty(tradeShopOrderDetailsRequest.getSerialNo())) {
            if (joinO) example.getOredCriteria().get(0).andOdotSerialNoLike(tradeShopOrderDetailsRequest.getSerialNo());
            else example.getOredCriteria().get(0).andSerialNoLike("%"+tradeShopOrderDetailsRequest.getSerialNo()+"%");
        }
        //4.处理收银员编号
        if (!StringUtils.isEmpty(tradeShopOrderDetailsRequest.getCustomerNumber())) {
            if (joinO) example.getOredCriteria().get(0).andOdotCustomerNumberEqualTo(tradeShopOrderDetailsRequest.getCustomerNumber());
            else example.getOredCriteria().get(0).andCustomerNumberEqualTo(tradeShopOrderDetailsRequest.getCustomerNumber());
        }
//        //5.处理支付方式
        if (!StringUtils.isEmpty(tradeShopOrderDetailsRequest.getPayType())) {
            example.getOredCriteria().get(0).andPdotPayTypeEqualTo(tradeShopOrderDetailsRequest.getPayType());
        }
        //6.处理订单类型
        if (!StringUtils.isEmpty(tradeShopOrderDetailsRequest.getOrderType())) {
            if (joinO) example.getOredCriteria().get(0).andOdotOrderTypeEqualTo(tradeShopOrderDetailsRequest.getOrderType());
            else example.getOredCriteria().get(0).andOrderTypeEqualTo(tradeShopOrderDetailsRequest.getOrderType());
        } else {
            if (joinO) example.getOredCriteria().get(0).andOdotOrderTypeNotEqualTo(DictionaryConstant.ORDER_TYPE_HYCZ.getCode());
            else example.getOredCriteria().get(0).andOrderTypeNotEqualTo(DictionaryConstant.ORDER_TYPE_HYCZ.getCode());
        }
        //7.处理订单状态
        if (!StringUtils.isEmpty(tradeShopOrderDetailsRequest.getOrderStatus())) {
//            //代付款状态查询状态为1且失效时间大于等于当前时间的数据
//            if (tradeShopOrderDetailsRequest.getOrderStatus().equals(DictionaryConstant.ORDER_UPDATE_STATUS_DFK.getCode())) {
//                example.getOredCriteria().get(0).andTimeExpireGreaterThanOrEqualTo(new Date());
//            }
//            //订单取消状态，查询订单状态为未支付且失效时间小于当前时间或状态为取消状态
//            if (tradeShopOrderDetailsRequest.getOrderStatus().equals(DictionaryConstant.ORDER_STATUS_DDQX.getCode())) {
//                example.getOredCriteria().get(0).andOrCancelStatus(tradeShopOrderDetailsRequest.getOrderStatus());
//                example.getOredCriteria().get(0).andPayStatusEqualTo(DictionaryConstant.PAY_STATUS_WFK.getCode());
//            } else {
//                example.getOredCriteria().get(0).andOrderStatusEqualTo(tradeShopOrderDetailsRequest.getOrderStatus());
//            }
            if (joinO) example.getOredCriteria().get(0).andOdotOrderStatusEqualTo(tradeShopOrderDetailsRequest.getOrderStatus());
            else example.getOredCriteria().get(0).andOrderStatusEqualTo(tradeShopOrderDetailsRequest.getOrderStatus());
        }
        //8.处理查询时间
        if (!StringUtils.isEmpty(tradeShopOrderDetailsRequest.getTimeMode())) {
            Date startTime = null;
            Date endTime = null;
            //时间模式(@1:按开始及结束时间查询@2:按年月查询)
            if (("1").equals(tradeShopOrderDetailsRequest.getTimeMode())) {
                if (StringUtils.isEmpty(tradeShopOrderDetailsRequest.getStartTime()) && StringUtils.isEmpty(tradeShopOrderDetailsRequest.getEndTime())) {
//                    startTime = DateUtils.getDayStartTime(new Date());
//                    endTime = DateUtils.getDayEndTime(new Date());
                } else {
                    if(tradeShopOrderDetailsRequest.getStartTime().length() == 10){
                        tradeShopOrderDetailsRequest.setStartTime(tradeShopOrderDetailsRequest.getStartTime()+" 00:00:00");
                    }
                    startTime = DateUtils.parse(tradeShopOrderDetailsRequest.getStartTime(), DateUtils.FORMAT_LONG);
                    if(tradeShopOrderDetailsRequest.getEndTime().length() == 10){
                        tradeShopOrderDetailsRequest.setEndTime(tradeShopOrderDetailsRequest.getEndTime()+" 23:59:59");
                    }
                    endTime = DateUtils.parse(tradeShopOrderDetailsRequest.getEndTime(), DateUtils.FORMAT_LONG);


                }
            } else if (("2").equals(tradeShopOrderDetailsRequest.getTimeMode())) {
                startTime = DateUtils.getMonthFirstDay(DateUtils.parse(tradeShopOrderDetailsRequest.getDateTime(), DateUtils.FORMAT_SHORTER));
                endTime = DateUtils.getDayEndTime(DateUtils.getMonthLastDay(DateUtils.parse(tradeShopOrderDetailsRequest.getDateTime(), DateUtils.FORMAT_SHORTER)));
            }
            if(joinO) {
                if (!StringUtils.isEmpty(startTime)) {
                    example.getOredCriteria().get(0).andOdotCreatedAtGreaterThanOrEqualTo(startTime);
                }
                if (!StringUtils.isEmpty(endTime)) {
                    example.getOredCriteria().get(0).andOdotCreatedAtLessThan(endTime);
                }
            }else
            {
                if (!StringUtils.isEmpty(startTime)) {
                    example.getOredCriteria().get(0).andCreatedAtGreaterThanOrEqualTo(startTime);
                }
                if (!StringUtils.isEmpty(endTime)) {
                    example.getOredCriteria().get(0).andCreatedAtLessThan(endTime);
                }
            }

        }
//        //9.处理会员卡号、东软员工号
//        if (!StringUtils.isEmpty(tradeShopOrderDetailsRequest.getMemberCardNo())) {
//            example.getOredCriteria().get(0).andMemberCardNoEqualTo(tradeShopOrderDetailsRequest.getMemberCardNo());
//        }
//        //10.会员名称、员工姓名
//        if (!StringUtils.isEmpty(tradeShopOrderDetailsRequest.getMemberName())) {
//            example.getOredCriteria().get(0).andMemberNameLike(tradeShopOrderDetailsRequest.getMemberName());
//        }
//        //11.会员卡编号(印刷,沈阳食堂使用)
//        if (!StringUtils.isEmpty(tradeShopOrderDetailsRequest.getCardNum())) {
//            example.getOredCriteria().get(0).andCardNumEqualTo(tradeShopOrderDetailsRequest.getCardNum());
//        }
        //11.设备名称
        if (!StringUtils.isEmpty(tradeShopOrderDetailsRequest.getDeviceName())) {
            example.getOredCriteria().get(0).andDeviceNameEqualTo(tradeShopOrderDetailsRequest.getDeviceName());
        }

        //12.处理收银员名
        if (!StringUtils.isEmpty(tradeShopOrderDetailsRequest.getCreatedBy())) {
            if (joinO) example.getOredCriteria().get(0).andOdotCreatedByEqualTo(tradeShopOrderDetailsRequest.getCreatedBy());
            else example.getOredCriteria().get(0).andCreatedByEqualTo(tradeShopOrderDetailsRequest.getCreatedBy());
        }

        //13.处理订单子类型
        if (!StringUtils.isEmpty(tradeShopOrderDetailsRequest.getOrderSubType())) {
            if (joinO) example.getOredCriteria().get(0).addEqualTo(OrderMasterExample.PROP_ODotOrderSubType,tradeShopOrderDetailsRequest.getOrderSubType());
            else example.getOredCriteria().get(0).addEqualTo(OrderMasterExample.PROP_OrderSubType,tradeShopOrderDetailsRequest.getOrderSubType());
        }

        example.setOrderByClause("created_at desc");
        return example;
    }

    /**
     * POS端门店交易流水查询方法
     * POS端门店流水
     * @return
     */
    public GetShopOrderDetailsForPosResponse queryShopOrderDetailsForPos(GetShopOrderDetailsForPosRequest shopOrderDetailsForPosRequest) {
        //1.校验参数信息
        if (StringUtils.isEmpty(shopOrderDetailsForPosRequest.getSerialNo())) {
            throw new BusinessCommonException(TradeErrorCode.POS_SN_EMPTY);
        }
//        if (StringUtils.isEmpty(shopOrderDetailsForPosRequest.getDateTime())) {
//            throw new BusinessCommonException(TradeErrorCode.TRADE_STATISTICS_TIME_EMPTY);
//        }

        if (shopOrderDetailsForPosRequest.getTimeMode().equals("1")) {
            if (StringUtils.isEmpty(shopOrderDetailsForPosRequest.getStartTime()) && StringUtils.isEmpty(shopOrderDetailsForPosRequest.getEndTime())) {

            } else if (StringUtils.isEmpty(shopOrderDetailsForPosRequest.getStartTime()) || StringUtils.isEmpty(shopOrderDetailsForPosRequest.getEndTime())) {
                throw new BusinessCommonException(TradeErrorCode.ORDER_STATISTICS_START_END_TIME_EMPTY);
            }
        }
        if (shopOrderDetailsForPosRequest.getTimeMode().equals("2")) {
            if (StringUtils.isEmpty(shopOrderDetailsForPosRequest.getDateTime())) {
                throw new BusinessCommonException(TradeErrorCode.ORDER_STATISTICS_DATE_TIME_EMPTY);
            }
        }

        //2.整理查询条件
        val example = shopOrderDetailsForPosExampleHandle(shopOrderDetailsForPosRequest);

        //3.查询门店订单详情信息
        val orderCount = orderMasterRepository.queryShopOrderDetailsCount(example);    //查询满足条件的总记录条数
        if (shopOrderDetailsForPosRequest.getIsPage()) {
            example.setLimit(shopOrderDetailsForPosRequest.getLimit());
            example.setOffset(shopOrderDetailsForPosRequest.getOffset());
        }

        val orderMasters = orderMasterRepository.queryShopOrderDetails(example);
        val totalMap = orderMasterRepository.queryShopOrderDetailsTotal(example);

        //处理订单状态
        //orderStatusHandle(orderMasters);

        //4.进行数据整理
        val shopOrderDetails = ListUtils.convertListToList(orderMasters, GetShopOrderDetailsForPosResponse.ShopOrderDetail.class);
        val paginationExtendBean = new PaginationExtendBean<GetShopOrderDetailsForPosResponse.ShopOrderDetail>();

        //5.查询系统支付渠道信息
        //val tradePayTypeDicts = payTypeRepository.queryPayTypes(null, null);
        if (null != shopOrderDetails && shopOrderDetails.size() > 0) {
            shopOrderDetails.forEach(shopOrder -> {
                shopOrder.setOrderStatusName(getOrderStatusName(shopOrder.getOrderStatus()));
            });
        }

        paginationExtendBean.setRows(shopOrderDetails);
        paginationExtendBean.setTotal(orderCount);

        val shopOrderDetailsForPosResponse = new GetShopOrderDetailsForPosResponse();
        shopOrderDetailsForPosResponse.setTotalAmount(new BigDecimal(totalMap.get("realAmount").toString()).divide(new BigDecimal(100)));    //存入订单总金额
        shopOrderDetailsForPosResponse.setPaginationExtendBean(paginationExtendBean);
        return shopOrderDetailsForPosResponse;
    }

    /**
     * 整理查询条件信息
     * POS端门店流水
     * @return
     */
    private OrderMasterExample shopOrderDetailsForPosExampleHandle(GetShopOrderDetailsForPosRequest shopOrderDetailsForPosRequest) {
        val deviceInfo = PosDeviceRedisUtils.getDeviceInfoBySerialNo(shopOrderDetailsForPosRequest.getSerialNo());
        if (null == deviceInfo) {
            throw new BusinessCommonException(TradeErrorCode.DEVICE_ORG_EMPTY);
        }
        val orgId = deviceInfo.getOrganizationId();
        val shopId = deviceInfo.getStoreId();
        logger.info("####shopOrderDetailsForPosExampleHandle###################################### SN:"+ shopOrderDetailsForPosRequest.getSerialNo());
        logger.info("####shopOrderDetailsForPosExampleHandle###################################### orgId:"+ orgId);
        logger.info("####shopOrderDetailsForPosExampleHandle###################################### shopId:"+ shopId);

        val example = new OrderMasterExample();
        example.createCriteria()
                .andOrgIdEqualTo(orgId)
                .andShopIdEqualTo(shopId);
                //.andOrderTypeNotEqualTo(DictionaryConstant.ORDER_TYPE_HYCZ.getCode());

        //8.处理查询时间
        if (!StringUtils.isEmpty(shopOrderDetailsForPosRequest.getTimeMode())) {
            Date startTime = null;
            Date endTime = null;
            //时间模式(@1:按开始及结束时间查询@2:按年月查询)
            if (("1").equals(shopOrderDetailsForPosRequest.getTimeMode())) {
                if (StringUtils.isEmpty(shopOrderDetailsForPosRequest.getStartTime()) && StringUtils.isEmpty(shopOrderDetailsForPosRequest.getEndTime())) {
//                    startTime = DateUtils.getDayStartTime(new Date());
//                    endTime = DateUtils.getDayEndTime(new Date());
                } else {
                    if (shopOrderDetailsForPosRequest.getStartTime().length() == 10) {
                        shopOrderDetailsForPosRequest.setStartTime(shopOrderDetailsForPosRequest.getStartTime() + " 00:00:00");
                    }
                    startTime = DateUtils.parse(shopOrderDetailsForPosRequest.getStartTime(), DateUtils.FORMAT_LONG);
                    if (shopOrderDetailsForPosRequest.getEndTime().length() == 10) {
                        shopOrderDetailsForPosRequest.setEndTime(shopOrderDetailsForPosRequest.getEndTime() + " 23:59:59");
                    }
                    endTime = DateUtils.parse(shopOrderDetailsForPosRequest.getEndTime(), DateUtils.FORMAT_LONG);
                }
            } else if (("2").equals(shopOrderDetailsForPosRequest.getTimeMode())) {
                startTime = DateUtils.getDayStartTime(DateUtils.parse(shopOrderDetailsForPosRequest.getDateTime(), DateUtils.FORMAT_SHORT));
                endTime = DateUtils.getDayEndTime(DateUtils.parse(shopOrderDetailsForPosRequest.getDateTime(), DateUtils.FORMAT_SHORT));
            }
            if (!StringUtils.isEmpty(startTime)) {
                example.getOredCriteria().get(0).andCreatedAtGreaterThanOrEqualTo(startTime);
            }
            if (!StringUtils.isEmpty(endTime)) {
                example.getOredCriteria().get(0).andCreatedAtLessThanOrEqualTo(endTime);
            }
        }

        example.setOrderByClause("created_at desc");
        return example;
    }

    /**
     * 根据订单状态获取订单状态名称
     *
     * @param orderStatus
     * @return
     */
    private String getOrderStatusName(String orderStatus) {
        String orderStatusName = "";
        if (!StringUtils.isEmpty(orderStatus)) {
            DictionaryConstant dict = DictionaryConstant.getEnumByCode(DictionaryConstant.ORDER_UPDATE_STATUS.getCode(), orderStatus);
            orderStatusName = dict.getValue();
        }
        return orderStatusName;
    }

    /**
     * 根据订单状态获取订单状态名称
     *
     * @param orderType
     * @return
     */
    private String getOrderTypeName(String orderType) {
        String orderTypeName = "";
        if (!StringUtils.isEmpty(orderType)) {
            DictionaryConstant dict = DictionaryConstant.getEnumByCode(DictionaryConstant.ORDER_TYPE.getCode(), orderType);
            orderTypeName = dict.getValue();
        }
        return orderTypeName;
    }


    /**
     * 获取设备信息
     *
     * @param serialNo
     * @return
     */
    private DeviceInfo getDeviceInfo(String serialNo) {
        //设备编号不能为空
        if (StringUtils.isEmpty(serialNo)) {
            throw new BusinessCommonException(TradeErrorCode.DEVICE_SN_IS_EMPTY);
        }
        val deviceInfo = PosDeviceRedisUtils.getDeviceInfoBySerialNo(serialNo);
        if (null == deviceInfo || null == deviceInfo.getOrganizationId() || null == deviceInfo.getStoreId()) {
            throw new BusinessCommonException(TradeErrorCode.DEVICE_ORG_EMPTY);
        }
        return deviceInfo;
    }

    public PayOrder getYfkPayOrderInfoByOrderNumber(String orderNumber) {
        val payOrdeList = payOrderService.queryPayOrderList(orderNumber);
        if(payOrdeList != null) {
            for (PayOrder payOrder : payOrdeList) {
                if(payOrder.getPayStatus().equals(DictionaryConstant.PAY_STATUS_YFK.getCode())){
                    return payOrder;
                }
            }
        }
        return null;
    }
}
