package com.hfkj.service.order.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hfkj.common.exception.BaseException;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.utils.DateUtil;
import com.hfkj.common.utils.RandomUtils;
import com.hfkj.common.utils.RedisUtil;
import com.hfkj.dao.BsOrderMapper;
import com.hfkj.entity.*;
import com.hfkj.model.order.OrderChildModel;
import com.hfkj.model.order.OrderModel;
import com.hfkj.mqtopic.OrderTopic;
import com.hfkj.qianzhu.CinemaService;
import com.hfkj.service.BsProductConfigService;
import com.hfkj.service.discount.CouponDiscountService;
import com.hfkj.service.discount.CouponDiscountUserRelService;
import com.hfkj.service.goods.BsOrderCinemaService;
import com.hfkj.service.goods.BsOrderStarbucksService;
import com.hfkj.service.order.*;
import com.hfkj.service.user.UserIntegralService;
import com.hfkj.sysenum.UserIntegralRecordOpUserTypeEnum;
import com.hfkj.sysenum.UserIntegralRecordSourceTypeEnum;
import com.hfkj.sysenum.order.OrderChildProductTypeEnum;
import com.hfkj.sysenum.order.OrderChildStatusEnum;
import com.hfkj.sysenum.order.OrderStatusEnum;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @className: BsOrderServiceImpl
 * @author: HuRui
 * @date: 2024/4/29
 **/
@Service("orderService")
public class BsOrderServiceImpl implements BsOrderService {
    // 缓存前缀KEY
    public final static String CACHE_KEY = "ORDER:";
    // 订单缓存时间 7天
    public final static Integer CACHE_TIME = 60*60*24*7;

    @Autowired
    private RedisUtil redisUtil;
    @Resource
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private RedisTemplate redisTemplate;
    @Resource
    private BsOrderMapper orderMapper;
    @Resource
    private BsOrderChildService orderChildService;
    @Resource
    private BsOrderDeductionService orderDeductionService;
    @Resource
    private OrderPayBeforeService orderPayBeforeService;
    @Resource
    private OrderCreateService orderCreateService;
    @Resource
    private OrderCancelService orderCancelService;
    @Resource
    private OrderPaySuccessService orderPaySuccessService;
    @Resource
    private UserIntegralService userIntegralService;
    @Resource
    private CouponDiscountUserRelService couponDiscountUserRelService;
    @Resource
    private CouponDiscountService couponDiscountService;
    @Resource
    private BsOrderCinemaService bsOrderCinemaService;
    @Resource
    private BsProductConfigService productConfigService;
    @Resource
    private BsOrderStarbucksService orderStarbucksService;


    @Override
    public BsOrder editData(BsOrder order) {
        order.setUpdateTime(new Date());
        if (order.getId() == null) {
            order.setCreateTime(new Date());
            orderMapper.insert(order);
        } else {
            orderMapper.updateByPrimaryKey(order);
        }
        return order;
    }

    @Override
    public OrderModel cache(OrderModel order) {
        // 缓存
        redisUtil.set(CACHE_KEY + order.getOrderNo(), order, CACHE_TIME);
        return order;
    }

    @Override
    public void cacheDelete(String orderNo) {
        // 缓存
        redisUtil.del(CACHE_KEY + orderNo);
    }

    @Override
    @Transactional(
            propagation= Propagation.REQUIRES_NEW,
            isolation = Isolation.READ_COMMITTED,
            timeout = 20,
            rollbackFor = Exception.class)
    public OrderModel create(OrderModel order) throws Exception {
        // 生成交易单号，共18位，时间 + 6位随机数
        order.setOrderNo(DateUtil.date2String(new Date(), "yyMMddHHmmss") + RandomUtils.number(6, false));
        editData(order);

        // 订单总金额
        BigDecimal totalPrice = new BigDecimal("0");
        // 商品总金额
        BigDecimal productTotalPrice = new BigDecimal("0");

        /************** 处理业务 ***************/
        for (OrderChildModel child : order.getOrderChildList()) {
            child.setOrderNo(order.getOrderNo());
            // 子订单号 交易id + 4位随机数
            child.setChildOrderNo(order.getId()+RandomUtils.number(4, false));
            // 提交订单前实物商品处理
            if (child.getProductType().equals(OrderChildProductTypeEnum.type1.getCode())) {
                child = orderCreateService.goods(order, child);
                // todo 1.0阶段暂时需要返回收货地址使用
                order.setBusiness(child.getBusiness());
            } else if (child.getProductType().equals(OrderChildProductTypeEnum.type2.getCode())) {
                // 提交订单虚拟商品处理
                child = orderCreateService.product(order, child);
            }else if (child.getProductType().equals(OrderChildProductTypeEnum.type3.getCode())) {
                child = orderCreateService.cinema(order, child);
            }else if (child.getProductType().equals(OrderChildProductTypeEnum.type4.getCode())) {
                child = orderCreateService.starbucks(order, child);
            }
            child.setProductTotalPrice(child.getProductPrice().multiply(new BigDecimal(child.getProductCount().toString())));
            child.setStatus(OrderChildStatusEnum.status1.getCode());

            productTotalPrice = productTotalPrice.add(child.getProductTotalPrice());
        }

        totalPrice = productTotalPrice;
        order.setTotalPrice(totalPrice);
        order.setProductTotalPrice(productTotalPrice);

        /************ 交易优惠 **************/
        BsOrderDeduction deduction = order.getDeduction()==null?new BsOrderDeduction():order.getDeduction();
        deduction.setOrderId(order.getId());
        deduction.setOrderNo(order.getOrderNo());
        deduction.setIntegralDiscountPrice(deduction.getIntegralDiscountPrice()==null?0L: deduction.getIntegralDiscountPrice());
        if (deduction.getUserCouponDiscountId() != null) {
            // 使用优惠券
            useDeduction(order, deduction, order.getDeduction().getUserCouponDiscountId());
            // 使用优惠券限制
            Map<String, Object> param = new HashMap<>();
            param.put("discountId", deduction.getCouponDiscountId());
            List<CouponDiscountGoodsRel> couponDiscountGoodsRelList = couponDiscountService.getListGoodsRel(param);
            for(OrderChildModel orderChild : order.getOrderChildList()) {
                List<CouponDiscountGoodsRel> collect = couponDiscountGoodsRelList.stream()
                        .filter(o -> o.getSpecsId() != null && o.getSpecsId().equals(o.getSpecsId())).collect(Collectors.toList());
                if (collect.isEmpty()) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, orderChild.getProductName()+"【"+orderChild.getProductSpecName()+"】"+"无法使用此优惠券");
                }
            }

        } else {
            deduction.setCouponDiscountPrice(new BigDecimal("0"));
            deduction.setCouponDiscountActualPrice(new BigDecimal("0"));
        }
        // 优惠券优惠金额 + 积分抵扣实际金额
        deduction.setTotalDeductionPrice(deduction.getCouponDiscountActualPrice()
                .add(new BigDecimal(deduction.getIntegralDiscountPrice().toString()).divide(new BigDecimal("100"))));
        orderDeductionService.editData(deduction);
        order.setDeduction(deduction);

        // 使用积分抵扣
        if (order.getDeduction().getIntegralDiscountPrice() > 0) {
            Map<String,Object> opUser = new HashMap<>();
            opUser.put("opUserType", UserIntegralRecordOpUserTypeEnum.type3.getCode());
            opUser.put("opUserId", order.getUserId());
            opUser.put("opUserName", order.getUserName());
            opUser.put("opUserPhone", order.getUserPhone());

            Map<String,Object> source = new HashMap<>();
            source.put("sourceType", UserIntegralRecordSourceTypeEnum.type1.getCode());
            source.put("sourceId", order.getId());
            source.put("sourceOrderNo", order.getOrderNo());
            source.put("sourceContent", "交易积分抵扣");

            // 扣除用户积分
            userIntegralService.consume(
                    order.getUserId(),
                    order.getDeduction().getIntegralDiscountPrice(),
                    opUser,
                    source
            );
        }
        /************ 交易优惠 **************/

        BigDecimal payRealPrice = totalPrice.subtract(order.getDeduction().getTotalDeductionPrice());
        order.setPayRealPrice(payRealPrice.compareTo(new BigDecimal("0")) > 0 ? payRealPrice : new BigDecimal("0"));
        order.setOrderStatus(order.getPayRealPrice().compareTo(new BigDecimal("0")) == 0?OrderStatusEnum.status2.getCode():OrderStatusEnum.status1.getCode());
        BigDecimal totalChildDiscountPrice = new BigDecimal("0");
        Long totalIntegralDiscountPrice = 0L;
        // 订单入库前处理
        for (int i = 0; i < order.getOrderChildList().size();i++) {
            OrderChildModel childOrder = order.getOrderChildList().get(i);
            childOrder.setSurplusRefundCount(childOrder.getProductCount());

            // 计算 子订单 在交易订单金额中的占比
            BigDecimal ratio = childOrder.getProductTotalPrice().divide(order.getTotalPrice(), 4, BigDecimal.ROUND_DOWN);

            // 优惠券优惠
            if (order.getDeduction().getCouponDiscountActualPrice().compareTo(BigDecimal.ZERO) > 0) {
                childOrder.setCouponDiscountPrice(order.getDeduction().getCouponDiscountActualPrice().multiply(ratio).setScale(2, BigDecimal.ROUND_DOWN));
            } else {
                childOrder.setCouponDiscountPrice(new BigDecimal("0"));
            }
            totalChildDiscountPrice = totalChildDiscountPrice.add(childOrder.getCouponDiscountPrice());

            // 积分
            if (order.getDeduction().getIntegralDiscountPrice() > 0) {
                childOrder.setIntegralDiscountPrice(new BigDecimal(order.getDeduction().getIntegralDiscountPrice().toString()).multiply(ratio).setScale(2, BigDecimal.ROUND_DOWN).longValue());
            } else {
                childOrder.setIntegralDiscountPrice(0L);
            }
            totalIntegralDiscountPrice = totalIntegralDiscountPrice + childOrder.getIntegralDiscountPrice();

            // 如果是循环的最后一笔商品订单
            if ((i+1) == order.getOrderChildList().size()) {
                // 优惠券差值
                BigDecimal couponDiscountDifference = order.getDeduction().getCouponDiscountActualPrice().subtract(totalChildDiscountPrice);
                if (couponDiscountDifference.compareTo(BigDecimal.ZERO) > 0) {
                    // 大于0
                    childOrder.setCouponDiscountPrice(childOrder.getCouponDiscountPrice().add(couponDiscountDifference));
                } else if (couponDiscountDifference.compareTo(BigDecimal.ZERO) < 0) {
                    // 小于0
                    childOrder.setCouponDiscountPrice(childOrder.getCouponDiscountPrice().subtract(couponDiscountDifference));
                }

                // 积分差值
                Long integralDiscountDifference = order.getDeduction().getIntegralDiscountPrice() - totalIntegralDiscountPrice;
                if (integralDiscountDifference > 0L) {
                    // 大于0
                    childOrder.setIntegralDiscountPrice(childOrder.getIntegralDiscountPrice() + integralDiscountDifference);
                } else if (integralDiscountDifference < 0L) {
                    // 小于0
                    childOrder.setIntegralDiscountPrice(childOrder.getIntegralDiscountPrice() - integralDiscountDifference);
                }
            }

            // 商品订单总优惠
            childOrder.setTotalDeductionPrice(childOrder.getCouponDiscountPrice().add(new BigDecimal(childOrder.getIntegralDiscountPrice()).divide(new BigDecimal("100"))));
            // 可退款金额 产品总价 - 优惠总价
            childOrder.setSurplusRefundPrice(childOrder.getProductTotalPrice().subtract(childOrder.getTotalDeductionPrice()));
            // 可退款积分 积分优惠
            childOrder.setSurplusRefundIntegral(childOrder.getIntegralDiscountPrice());
            // 商品实际价格
            childOrder.setProductActualPrice(childOrder.getSurplusRefundPrice());
            orderChildService.editData(childOrder);
        }

        // TODO 临时多商户支付功能限制
//        if (order.getOrderChildList().stream().collect(Collectors.groupingBy(BsOrderChild::getMerId, Collectors.toList())).size() > 1) {
//            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "暂不支持多商户商品下单");
//        }

        if (order.getPayRealPrice().compareTo(new BigDecimal("0")) <= 0) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "当前不支持0元购买");
        }

        // 订单入库
        editData(order);


        if (order.getOrderStatus().equals(OrderStatusEnum.status1.getCode())) {
            // 10分钟内未支付，自动取消订单
            Message<OrderModel> rocketMsg = MessageBuilder.withPayload(order).build();
            rocketMQTemplate.syncSend(OrderTopic.ORDER_TOPIC_CANCEL.getTopic(), rocketMsg,1000,14);

        } else if (order.getOrderStatus().equals(OrderStatusEnum.status2.getCode())) {
            // 支付校验
            orderPayBeforeService.payOrderCheck(order);
            // 处理业务
            orderPaySuccessHandle(order);
        }
        // 更新缓存
        cache(order);
        return order;
    }

    /**
     * 订单使用优惠券
     * @param order
     * @param deduction
     * @param userCouponDiscountId
     * @return
     */
    private BsOrderDeduction useDeduction(OrderModel order,BsOrderDeduction deduction, Long userCouponDiscountId) {
        String key = "ORDER_USE_DEDUCTION_" + userCouponDiscountId;
        // 获取锁
        Boolean lock = redisTemplate.opsForValue().setIfAbsent(key, userCouponDiscountId);
        if (Boolean.FALSE.equals(lock)) {
            try {
                Thread.sleep(100);
            } catch (Exception e) {
                e.printStackTrace();
            }
            useDeduction(order, deduction,userCouponDiscountId);
        }
        try {
            // 查询用户优惠券
            CouponDiscountUserRel discountUserRel = couponDiscountUserRelService.getRel(userCouponDiscountId);
            if (discountUserRel == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知优惠券");
            }
            if (discountUserRel.getStatus() != 1) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "优惠券状态不处于待使用");
            }
            discountUserRel.setStatus(2);
            discountUserRel.setUseTime(new Date());
            couponDiscountUserRelService.update(discountUserRel);
            // 查询优惠券
            CouponDiscount discount = couponDiscountService.queryDetail(discountUserRel.getDiscountId());
            if (discount == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知优惠券");
            }
            // 计算优惠
            deduction.setCouponDiscountId(discount.getId());
            deduction.setCouponDiscountType(discount.getType());
            deduction.setCouponDiscountPrice(discount.getPrice());
            // 卡卷类型  1：满减  2：抵扣   3：折扣
            if (1 == discount.getType()) {

                if (order.getProductTotalPrice().compareTo(discount.getCondition()) < 0) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未满足优惠券满减条件");
                }

                deduction.setCouponDiscountActualPrice(discount.getPrice());
            } else if (2 == discount.getType()) {
                deduction.setCouponDiscountActualPrice(discount.getPrice());
            } else if (3 == discount.getType()) {
                deduction.setCouponDiscountPrice(discount.getPercentage());
                deduction.setCouponDiscountActualPrice(
                        order.getTotalPrice().subtract(
                                order.getTotalPrice() .multiply(discount.getPercentage().divide(new BigDecimal("100"))).setScale(2, BigDecimal.ROUND_DOWN))
                );
            } else {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的优惠券优惠类型");
            }
            // 优惠券优惠金额 + 积分抵扣实际金额
            deduction.setTotalDeductionPrice(deduction.getCouponDiscountActualPrice()
                    .add(new BigDecimal(deduction.getIntegralDiscountPrice().toString()).divide(new BigDecimal("100"))));
            orderDeductionService.editData(deduction);
        } catch (BaseException e) {
            throw e;
        } catch (Exception e) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "优惠券使用异常");
        } finally {
            redisTemplate.delete(key);
        }
        return deduction;
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRES_NEW, rollbackFor= {RuntimeException.class}, timeout = 10)
    public OrderModel cancel(String orderNo, boolean system) {
        // 查询订单
        OrderModel order = getDetail(orderNo);
        if (order == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的订单");
        }
        if (!order.getOrderStatus().equals(OrderStatusEnum.status1.getCode())) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "无法取消，订单不处于待支付状态");
        }
        order.setOrderStatus(OrderStatusEnum.status5.getCode());
        order.setCancelTime(new Date());
        editData(order);

        for (BsOrderChild orderChild : order.getOrderChildList()) {
            orderChild.setStatus(OrderChildStatusEnum.status5.getCode());
            orderChildService.editData(orderChild);
        }

        // 退回优惠券
        if (order.getDeduction().getUserCouponDiscountId() != null) {
            // 查询用户优惠券
            CouponDiscountUserRel discountUserRel = couponDiscountUserRelService.getRel(order.getDeduction().getUserCouponDiscountId());
            if (discountUserRel == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知优惠券");
            }
            discountUserRel.setStatus(1);
            discountUserRel.setUseTime(null);
            couponDiscountUserRelService.update(discountUserRel);
        }

        // 退款用户积分
        if (order.getDeduction().getIntegralDiscountPrice() > 0) {
            Map<String,Object> opUser = new HashMap<>();
            if (system) {
                opUser.put("opUserType", UserIntegralRecordOpUserTypeEnum.type1.getCode());
                opUser.put("opUserId", 0);
                opUser.put("opUserName", UserIntegralRecordOpUserTypeEnum.type1.getName());
            } else {
                opUser.put("opUserType", UserIntegralRecordOpUserTypeEnum.type3.getCode());
                opUser.put("opUserId", order.getUserId());
                opUser.put("opUserName", order.getUserName());
                opUser.put("opUserPhone", order.getUserPhone());
            }
            Map<String,Object> source = new HashMap<>();
            source.put("sourceType", UserIntegralRecordSourceTypeEnum.type1.getCode());
            source.put("sourceId", order.getId());
            source.put("sourceOrderNo", order.getOrderNo());
            source.put("sourceContent", "交易取消！退回积分");

            // 扣除用户积分
            userIntegralService.entry(
                    order.getUserId(),
                    order.getDeduction().getIntegralDiscountPrice(),
                    opUser,
                    source
            );
        }

        // 取消订单业务
        orderCancelService.orderBusHandle(order);

        // 更新缓存
        cache(order);
        return order;
    }

    @Override
    public void deleteOrder(BsOrder order) {
        orderMapper.updateByPrimaryKey(order);
    }

    @Override
    public void childOrderComplete(String childOrderNo) {
        BsOrderChild orderChild = orderChildService.getDetail(childOrderNo);
        if (orderChild == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
        }
        // 删除缓存
        cacheDelete(orderChild.getOrderNo());

        orderChild.setFinishTime(new Date());
        orderChild.setStatus(OrderChildStatusEnum.status3.getCode());
        orderChildService.editData(orderChild);

        // 查询未完成的子订单数量
        long count = orderChildService.getUndoneChildOrder(orderChild.getOrderNo());
        if (count == 0) {
            BsOrder order = getOrder(orderChild.getOrderNo());
            if (order != null) {
                order.setOrderStatus(OrderStatusEnum.status3.getCode());
                order.setFinishTime(new Date());
                editData(order);
            }
        }
    }

    @Override
    public void orderPaySuccessHandle(OrderModel order) {
        order.setPayTime(order.getPayTime()==null?new Date():order.getPayTime());
        order.setOrderStatus(OrderStatusEnum.status2.getCode());
        editData(order);

        for (BsOrderChild childOrder : order.getOrderChildList()) {
            childOrder.setStatus(OrderChildStatusEnum.status2.getCode());
            orderChildService.editData(childOrder);
        }
        // 删除缓存
        cacheDelete(order.getOrderNo());
        // 处理业务
        orderPaySuccessService.orderBusHandle(order);
    }

    @Override
    public BsOrder getOrder(String orderNo) {
        BsOrderExample example = new BsOrderExample();
        example.createCriteria().andOrderNoEqualTo(orderNo);
        List<BsOrder> list = orderMapper.selectByExample(example);
        if (!list.isEmpty()) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public OrderModel  getDetail(String orderNo){

        OrderModel orderModel = new OrderModel();
        BeanUtils.copyProperties(getOrder(orderNo), orderModel);
        // 优惠
        orderModel.setDeduction(orderDeductionService.getOrderDeduction(orderNo));
        // 子订单
        orderModel.setOrderChildList(orderChildService.getOrderChildListByOrderNo(orderNo));

        // todo 1.0阶段暂时需要返回收货地址使用
        for (OrderChildModel orderChild : orderModel.getOrderChildList()) {

            if (orderChild.getProductType().equals(OrderChildProductTypeEnum.type1.getCode())) {
                orderModel.setBusiness(orderChild.getBusiness());
            }

           if (orderChild.getProductType().equals(OrderChildProductTypeEnum.type3.getCode())) {

               BsOrderCinema bsOrderCinema = bsOrderCinemaService.findGoodsOrder(orderNo);

               Map<String , Object> map = new HashMap<>();
               map.put("orderNo" , bsOrderCinema.getChannelOrderNo());
               JSONObject object = CinemaService.getByOrderNo(map);
               if (object != null && object.getJSONObject("data") != null) {
                   orderModel.setBusiness(object.getJSONObject("data"));
                   bsOrderCinema.setUpdateTime(new Date());
                   bsOrderCinema.setStatus(object.getJSONObject("data").getInteger("status"));
               }

               orderModel.setBusinessOrder(bsOrderCinema);

               bsOrderCinemaService.update(bsOrderCinema);

               if (bsOrderCinema.getStatus() == 10) {
                   // 子订单完成
                   childOrderComplete(orderChild.getChildOrderNo());
               }
           }
        }

        return orderModel;
    }

    @Override
    public List<BsOrder> getOrderList(Map<String, Object> param) {
        BsOrderExample example = new BsOrderExample();
        BsOrderExample.Criteria criteria = example.createCriteria();

        if (MapUtils.getLong(param, "userId") != null) {
            criteria.andUserIdEqualTo(MapUtils.getLong(param, "userId"));
        }
        if (StringUtils.isNotBlank(MapUtils.getString(param, "orderNo"))) {
            criteria.andOrderNoLike("%"+MapUtils.getString(param, "orderNo")+"%");
        }
        if (StringUtils.isNotBlank(MapUtils.getString(param, "userPhone"))) {
            criteria.andUserPhoneLike("%"+MapUtils.getString(param, "userPhone")+"%");
        }
        if (MapUtils.getInteger(param, "payChannel") != null) {
            criteria.andPayChannelEqualTo(MapUtils.getInteger(param, "payChannel"));
        }
        if (MapUtils.getInteger(param, "payType") != null) {
            criteria.andPayTypeEqualTo(MapUtils.getInteger(param, "payType"));
        }
        if (MapUtils.getInteger(param, "orderStatus") != null) {
            criteria.andOrderStatusEqualTo(MapUtils.getInteger(param, "orderStatus"));
        }
        if (MapUtils.getLong(param, "createTimeS") != null) {
            criteria.andCreateTimeGreaterThanOrEqualTo(new Date(MapUtils.getLong(param, "createTimeS")));
        }
        if (MapUtils.getLong(param, "createTimeE") != null) {
            criteria.andCreateTimeLessThanOrEqualTo(new Date(MapUtils.getLong(param, "createTimeE")));
        }
        if (MapUtils.getLong(param, "payTimeS") != null) {
            criteria.andPayTimeGreaterThanOrEqualTo(new Date(MapUtils.getLong(param, "payTimeS")));
        }
        if (MapUtils.getLong(param, "payTimeE") != null) {
            criteria.andPayTimeLessThanOrEqualTo(new Date(MapUtils.getLong(param, "payTimeE")));
        }
        if (MapUtils.getLong(param, "finishTimeS") != null) {
            criteria.andFinishTimeGreaterThanOrEqualTo(new Date(MapUtils.getLong(param, "finishTimeS")));
        }
        if (MapUtils.getLong(param, "finishTimeE") != null) {
            criteria.andFinishTimeLessThanOrEqualTo(new Date(MapUtils.getLong(param, "finishTimeE")));
        }
        if (MapUtils.getLong(param, "cancelTimeS") != null) {
            criteria.andCancelTimeGreaterThanOrEqualTo(new Date(MapUtils.getLong(param, "cancelTimeS")));
        }
        if (MapUtils.getLong(param, "cancelTimeE") != null) {
            criteria.andCancelTimeLessThanOrEqualTo(new Date(MapUtils.getLong(param, "cancelTimeE")));
        }
        criteria.andOrderStatusNotEqualTo(0);

        example.setOrderByClause("create_time desc");
        return orderMapper.selectByExample(example);
    }

    @Override
    public BigDecimal cinemaComputePrice(JSONArray jsonArray, String[] seatsIdArray , Integer drawMode) {

        BsProductConfig productConfig = productConfigService.queryDetail(OrderChildProductTypeEnum.type3.getCode());

        BigDecimal totalSalePrice = new BigDecimal(0);
        BigDecimal totalDrawModePrice = new BigDecimal(0);

        for (String string : seatsIdArray) {
            Integer seatsId = Integer.valueOf(string);
            for (Object array : jsonArray) {
                JSONArray seats = (JSONArray) array;
                if (!seats.isEmpty()) {
                    for (Object s : seats) {
                        JSONObject jsonObject = (JSONObject) s;
                        if (jsonObject != null) {
                            BigDecimal salePrice = jsonObject.getBigDecimal("price").add(jsonObject.getBigDecimal("fastDrawModePrice").multiply(productConfig.getDiscount()).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP));

                            if (salePrice.compareTo(jsonObject.getBigDecimal("price")) > 0) {
                                jsonObject.put("salePrice", salePrice);
                            } else {
                                jsonObject.put("salePrice", jsonObject.getBigDecimal("price"));
                            }

                            if (Objects.equals(jsonObject.getInteger("id"), seatsId)) {
                                totalSalePrice = totalSalePrice.add(jsonObject.getBigDecimal("salePrice"));
                                totalDrawModePrice = totalDrawModePrice.add(jsonObject.getBigDecimal("fastDrawModePrice"));
                            }

                        }
                    }
                }

            }
        }

        if (drawMode == 0 ) {
            return totalSalePrice;
        } else {
            return totalDrawModePrice;
        }

    }
}
