package com.iformall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iformall.common.ErrorCode;
import com.iformall.common.IdWorker;
import com.iformall.common.ResultData;
import com.iformall.domain.dto.WxSharingOrderDto;
import com.iformall.domain.po.*;
import com.iformall.domain.vo.*;
import com.iformall.enums.*;
import com.iformall.exception.MallinkException;
import com.iformall.mapper.*;
import com.iformall.service.*;
import com.iformall.utils.DateUtils;
import com.iformall.utils.PressUtils;
import com.iformall.utils.RedisLock;
import com.iformall.utils.Utility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class WxOrderServiceImpl implements WxOrderService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    RedisLock redisLock;

    @Autowired
    WxAppinfoMapper wxAppinfoMapper;

    @Autowired
    WxPayAccountMapper wxPayAccountMapper;

    @Autowired
    WxMallMapper wxMallMapper;

    @Autowired
    WxMerchantMapper wxMerchantMapper;

    @Autowired
    WxCUserMapper wxCUserMapper;

    @Autowired
    WxCouponMapper wxCouponMapper;

    @Autowired
    WxOrderMapper wxOrderMapper;

    @Autowired
    WxCouponOrderMapper wxCouponOrderMapper;

    @Autowired
    WxCUserService wxCUserService;

    @Autowired
    WxPayOrderMapper wxPayOrderMapper;

    @Autowired
    WxMerchantBUserMapper wxMerchantBUserMapper;

    @Autowired
    WxAppinfoService wxAppinfoService;

    @Autowired
    WxPayOrderService wxPayOrderService;

    @Autowired
    WxScoreRulesService wxScoreRulesService;

    @Autowired
    WxCUserTagsService wxCUserTagsService;

    @Autowired
    WxCouponActionLogService wxCouponActionLogService;

    @Autowired
    WxProfitSharingOrderService wxProfitSharingOrderService;

    @Autowired
    WxCouponMerchantMapper wxCouponMerchantMapper;

    @Autowired
    WxCardInfoMapper wxCardInfoMapper;

    @Autowired
    WxCouponSendService wxCouponSendService;

    @Autowired
    WxOrderPressMapper wxOrderPressMapper;

    @Autowired
    WxOrderGroupMapper wxOrderGroupMapper;

    @Override
    public PageInfo<WxOrder> listAsPage(WxOrder record, Integer pageIndex, Integer pageSize) {
        return PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo(() -> wxOrderMapper.findList(record));
    }

    @Override
    public ResultData microPayListOnDateAsPage(Long bUserId, Integer type, String date, Integer pageIndex, Integer pageSize) {
        WxMerchantBUser wxMerchantBUser = wxMerchantBUserMapper.selectByPrimaryKey(bUserId.longValue());
        if (wxMerchantBUser == null) {
            logger.error("B端用户不存在:" + bUserId);
            throw new MallinkException(ErrorCode.MERCHANT_INFO_NOT_FOUND);
        }

        WxMerchant wxMerchant = wxMerchantMapper.selectByPrimaryKey(wxMerchantBUser.getMerchantId());
        if (wxMerchant == null) {
            logger.error("商户不存在:" + bUserId);
            throw new MallinkException(ErrorCode.MERCHANT_INFO_NOT_FOUND);
        }

        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        String dateString;
        Date startDate;
        Date endDate;

        if (date == null) {
            endDate = new Date();
            dateString = fmt.format(new Date());
            try {
                startDate = fmt.parse(dateString);
            } catch (ParseException e) {
                return new ResultData(ErrorCode.SYS_PARAMETER_CAST_ERROR);
            }
        } else {
            try {
                startDate = fmt.parse(date);
            } catch (ParseException e) {
                return new ResultData(ErrorCode.SYS_PARAMETER_CAST_ERROR);
            }
            Calendar cal = Calendar.getInstance();
            cal.setTime(startDate);
            cal.add(Calendar.DATE, 1);
            endDate = cal.getTime();
        }

        Map dateMap = new HashMap();
        dateMap.put("startDate", startDate);
        dateMap.put("endDate", endDate);
        dateMap.put("merchantId", wxMerchant.getId());
        dateMap.put("type", type);

        Map resultMap = new HashMap();

        if (pageIndex == null || pageSize == null) {
            List<WxOrderPayVo> list;
            list = wxOrderMapper.findListOfMicroPayOrderByDate(dateMap);
            logger.info("find " + list.size() + " order from " + startDate + " to " + new Date());
            int total_price = 0;
            for (WxOrder order : list) {
                total_price = total_price + order.getPayment();
            }
            resultMap.put("amount", total_price);
        } else {
            resultMap.put("list", PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo(() -> wxOrderMapper.findListOfMicroPayOrderByDate(dateMap)));
        }
        return new ResultData(resultMap);
    }


    private int getUserCouponOrderCount(WxCUser user, WxCoupon counpon) {
        // 用户购买的券包数量
        // + Order 待支付
        // + couponOrder ---待使用
        int countOrder = 0, countCouponOrder = 0;

        //拼团
        if (counpon.getType().equals(EnumCouponType.COUPON_GROUP.getCode())) {
            try {
                WxOrder orderQ = new WxOrder();
                orderQ.setTenantId(user.getTenantId());
                orderQ.setProductId(counpon.getId());
                orderQ.setType(EnumOrderType.COUPON.getCode());
                orderQ.setcUserId(user.getId());
                List<Integer> statusS = new ArrayList<>();
                statusS.add(EnumOrderStatus.ORDER_STATUS_COOPERATING.getCode());
                statusS.add(EnumOrderStatus.ORDER_STATUS_COOPERATING_COMPLETE.getCode());
                statusS.add(EnumOrderStatus.ORDER_STATUS_PENDING_PAYMENT.getCode());
                orderQ.setStatusS(statusS);
                return wxOrderMapper.countList(orderQ);
            } catch (Exception e) {
                logger.error("购买是否超限-DB, couponId: " + counpon.getId() + ", e:" + e.getMessage());
                throw new MallinkException(ErrorCode.ORDER_IS_FAIL);
            }
        }

        try {
            WxOrder orderQ = new WxOrder();
            orderQ.setTenantId(user.getTenantId());
            orderQ.setProductId(counpon.getId());
            orderQ.setType(EnumOrderType.COUPON.getCode());
            orderQ.setcUserId(user.getId());
            List<Integer> statusS = new ArrayList<Integer>();
            statusS.add(EnumOrderStatus.ORDER_STATUS_PRESSING.getCode());
            statusS.add(EnumOrderStatus.ORDER_STATUS_PRESS_COMPLETE.getCode()); //砍价券专有状态
            statusS.add(EnumOrderStatus.ORDER_STATUS_PENDING_PAYMENT.getCode());//砍价券专有状态
            orderQ.setStatusS(statusS);
            countOrder = wxOrderMapper.countList(orderQ);
        } catch (Exception e) {
            logger.error("购买是否超限-DB, couponId: " + counpon.getId() + ", e:" + e.getMessage());
            throw new MallinkException(ErrorCode.ORDER_IS_FAIL);
        }

        try {
            WxCouponOrder couponOrderQ = new WxCouponOrder();
            couponOrderQ.setTenantId(user.getTenantId());
            couponOrderQ.setCouponId(counpon.getId());
            couponOrderQ.setcUserId(user.getId());
            if (counpon.getSendType().equals(EnumCouponSendType.PASSIVE))
                couponOrderQ.setCouponOrderStatus(EnumCouponOrderStatus.COUPON_ORDER_USE_WAIT.getCode());
            countCouponOrder = wxCouponOrderMapper.countList(couponOrderQ);
        } catch (Exception e) {
            logger.error("购买是否超限-DB, couponId: " + counpon.getId() + ", e:" + e.getMessage());
            throw new MallinkException(ErrorCode.ORDER_IS_FAIL);
        }

        return countOrder + countCouponOrder;
    }

    private void stockReduce(WxCUser user, WxCoupon coupon, String couponIdStr) {
        long time = System.currentTimeMillis() + RedisLock.TIMEOUT;
        String timeStr = String.valueOf(time);
        // 库存加锁
        if (!redisLock.lock(couponIdStr, timeStr)) {
            logger.error("此券被锁定, couponId: " + couponIdStr);
            throw new MallinkException(ErrorCode.TOO_MANY_REQUEST);
        }

        // 检查 优惠券 库存
        if (coupon.getRemainInventory() <= 0) {
            //解锁
            redisLock.unlock(couponIdStr, timeStr);
            logger.error("此券库存为0, couponId: " + couponIdStr);
            throw new MallinkException(ErrorCode.REMAIN_IS_EMPTY);
        }

        // check 购买是否超限
        int count = 0;
        try {
            count = getUserCouponOrderCount(user, coupon);
        } catch (Exception e) {
            //解锁
            redisLock.unlock(couponIdStr, timeStr);
            throw new MallinkException(ErrorCode.DB_FAIL);
        }

        if (count >= coupon.getUseLimitQuantity()) {
            //解锁
            redisLock.unlock(couponIdStr, timeStr);
            logger.error("此券购买数量已超限, couponId: " + couponIdStr + ", count: " + count);
            throw new MallinkException(ErrorCode.ORDER_IS_LIMITED);
        }


        try {
            WxCoupon updateRecord = new WxCoupon();
            updateRecord.setId(coupon.getId());
            updateRecord.setRemainInventory(coupon.getRemainInventory() - 1);
            updateRecord.setUpdateDate(new Date());
            // 减库存
            wxCouponMapper.updateByPrimaryKeySelective(updateRecord);
        } catch (RuntimeException e) {
            logger.error("此券减库存失败, couponId: " + couponIdStr);
            throw new MallinkException(ErrorCode.ORDER_IS_FAIL);
        } finally {
            //解锁
            redisLock.unlock(couponIdStr, timeStr);
        }
    }

    @Override
    public void stockBack(WxOrder updateOrder) {
        // 已取消/已退款，库存加1
        // 获取订单相关coupon
        Long couponId = updateOrder.getProductId();
        String couponIdStr = "" + couponId;
        //加锁
        long time = System.currentTimeMillis() + RedisLock.TIMEOUT;
        String timeStr = String.valueOf(time);

        if (!redisLock.lock(couponIdStr, timeStr)) {
            logger.error("此券被锁定, couponId: " + couponIdStr);
            throw new MallinkException(ErrorCode.TOO_MANY_REQUEST);
        }
        WxCoupon coupon = null;
        try {
            coupon = wxCouponMapper.selectByPrimaryKey(couponId);
        } catch (Exception e) {
            logger.error("券未找到, e:" + e.getMessage());
            throw new MallinkException(ErrorCode.COUPON_IS_EMPTY);
        }
        if (coupon == null) {
            logger.error("券未找到, " + couponIdStr);
            throw new MallinkException(ErrorCode.COUPON_IS_EMPTY);
        }

        WxCoupon updateRecord = new WxCoupon();
        updateRecord.setId(coupon.getId());
        updateRecord.setRemainInventory(coupon.getRemainInventory() + 1);
        updateRecord.setUpdateDate(new Date());

        try {
            wxCouponMapper.updateByPrimaryKeySelective(updateRecord);
        } catch (Exception e) {
            logger.error("数据库更新失败，库存+1失败, e:" + e.getMessage());
            throw new MallinkException(ErrorCode.DB_FAIL.getCode(), "库存恢复失败");
        } finally {
            //解锁
            redisLock.unlock(couponIdStr, timeStr);
        }
    }

    private boolean isCouponMerchantValid(Long couponId) {
        Map paramMap = new HashMap<>();
        paramMap.put("productId",couponId);
        List<WxMerchantVo> merchantVoList = wxCouponMerchantMapper.findMerchantNameList(paramMap);
        if (merchantVoList.stream().anyMatch((cm->cm.getMerchantStatus().equals(EnumMerchantStatus.VALID.getCode())))){
            return true;
        }
        return false;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = {Exception.class})
    public WxOrder saveCouponOrder(WxCUser user, Long couponChannelId, Long couponId, boolean isPress, Long orderGroupId) {
        // 检查用户
        if (user == null) {
            logger.error("用户不存在");
            throw new MallinkException(ErrorCode.USER_IS_EMPTY);
        }
        // 获取券信息
        String couponIdStr = String.valueOf(couponId);
        WxCoupon coupon = wxCouponMapper.selectByPrimaryKey(couponId);
        if (coupon == null) {
            logger.error("券不存在, couponId: " + couponIdStr);
            throw new MallinkException(ErrorCode.COUPON_IS_EMPTY);
        }

        if (coupon.getStatus().equals(EnumCouponStatus.COUPON_STATUS_TAKE_OFFF.getCode())) {
            logger.error("券已下架, couponId: " + couponIdStr);
            throw new MallinkException(ErrorCode.COUPON_ORDER_IS_INVALID);
        }

        if (!isCouponMerchantValid(couponId)) {
            logger.error("商户不存在, couponId: " + couponIdStr);
            throw new MallinkException(ErrorCode.MERCHANT_INFO_NOT_FOUND);
        }
        // 拼团
        if (orderGroupId != null && !orderGroupId.equals(0L)) {
            WxOrderGroup group = wxOrderGroupMapper.selectByPrimaryKey(orderGroupId);
            if (group.getStatus().equals(EnumOrderStatus.ORDER_STATUS_COOPERATING_COMPLETE.getCode())) {
                logger.error("下订单拼团人数已满>>>" + orderGroupId);
                throw new MallinkException(ErrorCode.ORDER_GROUP_COOPERATING_FINISHED);
            }
        }

        // 减库存操作
        stockReduce(user, coupon, couponIdStr);

        Date curr = new Date();

        int payment = coupon.getSalePrice();
        if (isPress || coupon.getType().equals(EnumCouponType.COUPON_PRESS.getCode())) {
            // 砍价券 初始是全价即面额
            payment = coupon.getPrice();
        }

        if (orderGroupId == null && coupon.getType().equals(EnumCouponType.COUPON_GROUP.getCode())) {
            // 拼团券 初始是全价即面额
            payment = coupon.getPrice();
        }

        final IdWorker idWorker = IdWorker.get();
        Long orderNumber = idWorker.nextId();

        // body
        // tenant_id + merchant_id + title + subtitle
        String bodyStr = "";
        try {
            bodyStr =// Utility.substring(wxMerchant.getName(), Math.min(64, wxMerchant.getName().getBytes().length), "utf-8") +
                    Utility.substring(coupon.getTitle(), Math.min(62, coupon.getTitle().getBytes().length), "utf-8");
        } catch (Exception e) {
            logger.error("body:" + e.getMessage());
            bodyStr = /*wxMerchant.getName() + */ "-" + EnumCouponType.getEnum(coupon.getType());
        }

        WxOrder record = new WxOrder();
        record.setId(orderNumber);
        record.setTenantId(user.getTenantId());
        record.setOrderNumber(orderNumber);
        record.setCouponChannelId(couponChannelId);
        record.setProductId(couponId);
        record.setType(EnumOrderType.COUPON.getCode());
        record.setcUserId(user.getId());
        record.setPaymentType(EnumPayType.PAY_PAYMENT.getCode());
        record.setPayment(payment);
        record.setOrderStatus(EnumOrderStatus.ORDER_STATUS_PENDING_PAYMENT.getCode());
        record.setDetail(bodyStr);
        record.setCreateDate(curr);
        record.setUpdateDate(curr);
        record.setOrderGroupId(orderGroupId);

        if (isPress) {
            // 初始砍价信息
            record.setPressCurrentNum(0);
            // 砍价券过期时间取券的过期时间和砍价限制时间中时间小的那个
            Date pressEndDate = DateUtils.getHourTimeAfter(coupon.getPressLimitHours(), new Date());
            if(pressEndDate.after(coupon.getValidEndDate()))
                pressEndDate = coupon.getValidEndDate();
            record.setPressEndDate(pressEndDate);
            record.setPressCurrentValue(coupon.getPrice() - coupon.getSalePrice());
        }

        try {
            // 保存订单
            wxOrderMapper.insertSelective(record);
        } catch (RuntimeException e) {
            // 库存恢复
            stockBack(record);
            logger.error("保存订单：" + e.getMessage());
            throw new MallinkException(ErrorCode.ORDER_SAVE_ERR);
        }

        if (isPress) {
            // 初始砍价
            // 添加 wx_order_press
            int total = coupon.getPrice() - coupon.getSalePrice();
            int left_total = total;
            WxOrderPress orderPress = new WxOrderPress();
            orderPress.setId(idWorker.nextId());
            orderPress.setOrderId(orderNumber);
            orderPress.setUserId(user.getId());
            orderPress.setCreateDate(new Date());
            orderPress.setFirst(EnumOrderPressType.FIRST.getCode());
            int lPressValue = PressUtils.stateLessPressValue(total, left_total, coupon.getPressLimitNum(), 0);
            orderPress.setPressValue(lPressValue);

            try {
                // 保存订单
                wxOrderPressMapper.insertSelective(orderPress);
            } catch (RuntimeException e) {
                // 库存恢复
                stockBack(record);
                logger.error("保存砍价记录Err：" + e.getMessage());
                throw new MallinkException(ErrorCode.ORDER_SAVE_ERR);
            }

            // 更新砍价信息
            WxOrder orderUpdatePress = new WxOrder();
            orderUpdatePress.setId(record.getId());
            orderUpdatePress.setPressCurrentNum(1);
            orderUpdatePress.setPressCurrentValue(left_total - orderPress.getPressValue());
            orderUpdatePress.setOrderStatus(EnumOrderStatus.ORDER_STATUS_PRESSING.getCode());
            orderUpdatePress.setUpdateDate(new Date());
            try {
                // 保存订单
                wxOrderMapper.updateByPrimaryKeySelective(orderUpdatePress);
            } catch (RuntimeException e) {
                // 库存恢复
                stockBack(record);
                logger.error("更新订单记录Err：" + e.getMessage());
                throw new MallinkException(ErrorCode.ORDER_SAVE_ERR);
            }
        }

        // couponActionLog
        try {
            wxCouponActionLogService.addOne(user.getTenantId(), couponId, orderNumber, EnumCouponSendSendType.ACTIVE.getCode(), couponChannelId);
        } catch (Exception e) {
            // 库存恢复
            stockBack(record);
            logger.error("保存订单：" + e.getMessage());
            throw new MallinkException(ErrorCode.ORDER_SAVE_ERR);
        }


        return record;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = {Exception.class})
    public WxOrder saveMicroPayOrder(WxMerchantBUser user, String totalFeeStr) {
        // 检查用户
        if (user == null) {
            logger.error("用户不存在");
            throw new MallinkException(ErrorCode.USER_IS_EMPTY);
        }

        WxMerchant wxMerchant = wxMerchantMapper.selectByPrimaryKey(user.getMerchantId());
        if (wxMerchant == null) {
            logger.error("商户不存在, merchantId: " + user.getMerchantId());
            throw new MallinkException(ErrorCode.MERCHANT_INFO_NOT_FOUND);
        }
        if (wxMerchant.getStatus() == EnumMerchantStatus.NOT_VALID.getCode()) {
            logger.error("商户已禁用, merchantId: " + user.getMerchantId());
            throw new MallinkException(ErrorCode.MERCHANT_INFO_NOT_VALID);
        }

        Date curr = new Date();

        BigDecimal totalFee = new BigDecimal(totalFeeStr);
        totalFee.setScale(2, BigDecimal.ROUND_HALF_UP); // 第一个变量是小数位数，第二个变量是取舍方法(四舍五入)

        int payment = totalFee.multiply(new BigDecimal(100)).intValue();

        final IdWorker idWorker = IdWorker.get();
        Long orderNumber = idWorker.nextId();

        // body
        // tenant_id + merchant_id + title + subtitle
        String bodyStr = "刷卡支付, 金额:" + totalFeeStr;


        WxOrder record = new WxOrder();
        record.setId(orderNumber);
        record.setTenantId(user.getTenantId());
        record.setOrderNumber(orderNumber);
        record.setType(EnumOrderType.MICROPAY.getCode());
        record.setProductId(user.getId());
        record.setPaymentType(EnumPayType.PAY_PAYMENT.getCode());
        record.setPayment(payment);
        record.setOrderStatus(EnumOrderStatus.ORDER_STATUS_PENDING_PAYMENT.getCode());
        record.setDetail(bodyStr);
        record.setCreateDate(curr);
        record.setUpdateDate(curr);

        try {
            // 保存订单
            wxOrderMapper.insertSelective(record);
        } catch (RuntimeException e) {
            logger.error("保存订单：" + e.getMessage());
            throw new MallinkException(ErrorCode.ORDER_SAVE_ERR);
        }
        return record;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = {Exception.class})
    public WxOrder saveCardPayOrder(WxMerchant merchant, WxCUser cUser, String totalFeeStr, Integer payment) {
        Date curr = new Date();

        final IdWorker idWorker = IdWorker.get();
        Long orderNumber = idWorker.nextId();

        // body
        // tenant_id + merchant_id + title + subtitle
        String bodyStr = "C扫B储值卡支付, 金额:" + totalFeeStr;

        WxOrder record = new WxOrder();
        record.setId(orderNumber);
        record.setTenantId(merchant.getTenantId());
        record.setOrderNumber(orderNumber);
        record.setType(EnumOrderType.PREPAIDCARD.getCode());
        record.setProductId(merchant.getId());
        record.setcUserId(cUser.getId());
        record.setPaymentType(EnumPayType.PAY_PAYMENT.getCode());
        record.setPayment(payment);
        record.setOrderStatus(EnumOrderStatus.ORDER_STATUS_PENDING_PAYMENT.getCode());
        record.setDetail(bodyStr);
        record.setCreateDate(curr);
        record.setUpdateDate(curr);

        try {
            // 保存订单
            wxOrderMapper.insertSelective(record);
        } catch (RuntimeException e) {
            logger.error("保存订单：" + e.getMessage());
            throw new MallinkException(ErrorCode.ORDER_SAVE_ERR);
        }
        return record;
    }

    /**
     * 创建 couponOrder
     *
     * @param user
     * @param order
     * @param coupon
     */
    private WxCouponOrder createCouponOrder(WxCUser user, WxOrder order, WxCoupon coupon) {
        Date curr = new Date();
        Date valid_date = null;
        if (coupon.getValidType().equals(EnumValidStatus.VALID_RANGE.getCode()) ||
                coupon.getType().equals(EnumCouponType.COUPON_TINGCHE.getCode())){
            valid_date = coupon.getValidEndDate();
        }
        else {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(curr);
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.add(Calendar.DAY_OF_MONTH, 1+coupon.getValidDays());
            valid_date = calendar.getTime();
        }
        boolean isCard = false;
        // 检查是否是储值卡
        if(coupon.getType().equals(EnumCouponType.CARD_MULTIMCH.getCode())) {
            isCard = true;
        }
        final IdWorker idWorker = IdWorker.get();

        WxCouponOrder couponOrder = new WxCouponOrder();
        couponOrder.setId(idWorker.nextId());
        couponOrder.setTenantId(user.getTenantId());
        couponOrder.setCouponId(order.getProductId());
        couponOrder.setCouponType(coupon.getType());
        couponOrder.setcUserId(user.getId());
        couponOrder.setOwnerId(user.getId());
        couponOrder.setAutoRefund(coupon.getAutoRefund());
        couponOrder.setOrderId(order.getOrderNumber());
        couponOrder.setExpiredTime(valid_date);
        if(!isCard) {
            couponOrder.setCouponOrderStatus(EnumCouponOrderStatus.COUPON_ORDER_USE_WAIT.getCode());
        } else {
            couponOrder.setCouponOrderStatus(EnumCouponOrderStatus.CARD_USING.getCode());
        }
        couponOrder.setCreateDate(curr);
        couponOrder.setUpdateDate(curr);
        couponOrder.setCouponPrice(order.getPayment());

        wxCouponOrderMapper.insertSelective(couponOrder);

        /// 储值卡信息添加
        if(isCard) {
            WxPayOrder payOrder = null;
            try {
                WxPayOrder payOrderQ = new WxPayOrder();
                payOrderQ.setTenantId(user.getTenantId());
                payOrderQ.setOrderId(order.getId());
                payOrderQ.setPayOrderStatus(EnumPayStatus.PAY_STATUS_SUCCESS.getCode());
                payOrder = wxPayOrderMapper.selectOne(payOrderQ);
            } catch (Exception e) {
                logger.error("payOrder not found:" + e.getMessage());
            }

            Integer fee = payOrder.getPayAmount() - payOrder.getShareAmount();

            WxCardInfo cardInfo = new WxCardInfo();
            cardInfo.setId(couponOrder.getId());
            cardInfo.setTenantId(user.getTenantId());
            cardInfo.setCouponId(order.getProductId());
            cardInfo.setTransactionId(payOrder.getTransactionId());
            cardInfo.setAmount(coupon.getPrice());
            cardInfo.setSaleAmount(coupon.getSalePrice());
            cardInfo.setRemainingAmount(coupon.getPrice());
            cardInfo.setServiceFeeAmount(fee);
            cardInfo.setShareFeeAmount(payOrder.getShareAmount());
            cardInfo.setRemainingShareFeeAmount(payOrder.getShareAmount());
            cardInfo.setCreateDate(curr);
            cardInfo.setUpdateDate(curr);
            cardInfo.setSupportTransfer(coupon.getSupportTransfer());
            wxCardInfoMapper.insertSelective(cardInfo);
        }

        wxCUserTagsService.triggerAssignTags(EnumAssignTagsTrigger.ASSIGN_TAGS_TRIGGER_BUY, user);
        return couponOrder;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = {Exception.class})
    public WxOrder saveFreeCouponOrder(Long userId, Long couponChannelId, Long couponId) {
        // check 用户状态
        WxCUser user = null;
        try {
            user = wxCUserMapper.selectByPrimaryKey(userId);
        } catch (Exception e) {
            logger.error("userId : " + userId + ", e: " + e.getMessage());
        }
        if (user == null) {
            logger.error("用户不存在, userId: " + userId);
            throw new MallinkException(ErrorCode.USER_IS_EMPTY);
        }

        // 检查券状态
        String couponIdStr = String.valueOf(couponId);
        WxCoupon coupon = wxCouponMapper.selectByPrimaryKey(couponId);
        if (coupon == null) {
            logger.error("券不存在, couponId: " + couponIdStr);
            throw new MallinkException(ErrorCode.COUPON_IS_EMPTY);
        }
        if (coupon.getStatus() == EnumCouponStatus.COUPON_STATUS_TAKE_OFFF.getCode()) {
            logger.error("券已下架, couponId: " + couponIdStr);
            throw new MallinkException(ErrorCode.COUPON_IS_TAKE_OFF);
        }
        if (coupon.getSalePrice() != 0) {
            logger.error("券不免费, couponId: " + couponIdStr);
            throw new MallinkException(ErrorCode.COUPON_IS_NOT_FREE);
        }

        // 减库存操作
        try {
            stockReduce(user, coupon, couponIdStr);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }


        int payment = coupon.getSalePrice();

        Date curr = new Date();

        final IdWorker idWorker = IdWorker.get();
        Long orderNumber = idWorker.nextId();

        // body
        // tenant_id + merchant_id + title + subtitle
        String bodyStr = coupon.getTitle() + "/" + coupon.getSubTitle();

        WxOrder record = new WxOrder();
        record.setId(orderNumber);
        record.setTenantId(user.getTenantId());
        record.setOrderNumber(orderNumber);
        record.setCouponChannelId(couponChannelId);
        record.setProductId(couponId);
        record.setType(EnumOrderType.COUPON.getCode());
        record.setcUserId(user.getId());
        record.setPaymentType(EnumPayType.PAY_PAYMENT.getCode());
        record.setPayment(payment);
        record.setOrderStatus(EnumOrderStatus.ORDER_STATUS_PAYMENT_SUCCESS.getCode());
        record.setDetail(bodyStr);
        record.setCreateDate(curr);
        record.setUpdateDate(curr);

        // 保存订单
        try {
            wxOrderMapper.insertSelective(record);
        } catch (Exception e) {
            logger.error("保存订单：" + e.getMessage());
            // 库存恢复
            stockBack(record);
            throw new MallinkException(ErrorCode.ORDER_SAVE_ERR);
        }

        //  创建couponOrder
        try {
            WxCouponOrder couponOrder = createCouponOrder(user, record, coupon);
        } catch (Exception e) {
            logger.error("保存订单：" + e.getMessage());
            // 库存恢复
            stockBack(record);
            throw new MallinkException(ErrorCode.COUPON_ORDER_SAVE_ERR);
        }

        return record;
    }

    @Override
    @Transactional(propagation = Propagation.NESTED, readOnly = false, rollbackFor = {Exception.class})
    public WxCouponOrder sendFreeCouponToUser(Long userId, Long couponId) {
        // check 用户状态
        WxCUser user = null;
        try {
            user = wxCUserMapper.selectByPrimaryKey(userId);
        } catch (Exception e) {
            logger.error("userId : " + userId + ", e: " + e.getMessage());
        }
        if (user == null) {
            logger.error("用户不存在, userId: " + userId);
            throw new MallinkException(ErrorCode.USER_IS_EMPTY);
        }

        // 检查券状态
        String couponIdStr = String.valueOf(couponId);
        WxCoupon coupon = wxCouponMapper.selectByPrimaryKey(couponId);
        if (coupon == null) {
            logger.error("券不存在, couponId: " + couponIdStr);
            throw new MallinkException(ErrorCode.COUPON_IS_EMPTY);
        }
        if (coupon.getStatus() == EnumCouponStatus.COUPON_STATUS_TAKE_OFFF.getCode()) {
            logger.error("券已下架, couponId: " + couponIdStr);
            throw new MallinkException(ErrorCode.COUPON_IS_TAKE_OFF);
        }
        if (coupon.getSalePrice() != 0) {
            logger.error("券不免费, couponId: " + couponIdStr);
            throw new MallinkException(ErrorCode.COUPON_IS_NOT_FREE);
        }

        // 减库存操作
        stockReduce(user, coupon, couponIdStr);

        int payment = coupon.getSalePrice();

        Date curr = new Date();

        final IdWorker idWorker = IdWorker.get();
        Long orderNumber = idWorker.nextId();

        // body
        // tenant_id + merchant_id + title + subtitle
        String bodyStr = coupon.getTitle() + "/" + coupon.getSubTitle();

        WxOrder record = new WxOrder();
        record.setId(orderNumber);
        record.setTenantId(user.getTenantId());
        record.setOrderNumber(orderNumber);
        record.setProductId(couponId);
        record.setType(EnumOrderType.COUPON.getCode());
        record.setcUserId(user.getId());
        record.setPaymentType(EnumPayType.PAY_PAYMENT.getCode());
        record.setPayment(payment);
        record.setOrderStatus(EnumOrderStatus.ORDER_STATUS_PAYMENT_SUCCESS.getCode());
        record.setDetail(bodyStr);
        record.setCreateDate(curr);
        record.setUpdateDate(curr);

        // 保存订单
        try {
            wxOrderMapper.insertSelective(record);
        } catch (Exception e) {
            logger.error("保存订单：" + e.getMessage());
            // 库存恢复
            stockBack(record);
            throw new MallinkException(ErrorCode.ORDER_SAVE_ERR);
        }

        //  创建couponOrder
        WxCouponOrder couponOrder = null;
        try {
            couponOrder = createCouponOrder(user, record, coupon);
        } catch (Exception e) {
            logger.error("保存订单：" + e.getMessage());
            // 库存恢复
            stockBack(record);
            throw new MallinkException(ErrorCode.COUPON_ORDER_SAVE_ERR);
        }

        return couponOrder;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = {Exception.class})
    public int couponOrderSuccess(WxOrder updateOrder) {
        Date currentDate = new Date();
        WxCoupon coupon = wxCouponMapper.selectByPrimaryKey(updateOrder.getProductId());
        if (coupon == null) {
            logger.error("券不存在, couponId: " + updateOrder.getProductId());
            throw new MallinkException(ErrorCode.COUPON_IS_EMPTY);
        }
        if (coupon.getStatus() == EnumCouponStatus.COUPON_STATUS_TAKE_OFFF.getCode()) {
            logger.error("券已下架, couponId: " + updateOrder.getProductId());
            throw new MallinkException(ErrorCode.COUPON_IS_TAKE_OFF);
        }
        WxCUser user = wxCUserMapper.selectByPrimaryKey(updateOrder.getcUserId());
        if (user == null) {
            logger.error("用户不存在, userId: " + updateOrder.getcUserId());
            throw new MallinkException(ErrorCode.USER_IS_EMPTY);
        }
        // 已支付,更新支付时间
        WxOrder updateT = new WxOrder();
        updateT.setId(updateOrder.getId());
        updateT.setPaymentTime(currentDate);
        //拼团到此处为已完成状态
        if (updateOrder.getOrderGroupId().equals(0L)) {
            updateT.setOrderStatus(EnumOrderStatus.ORDER_STATUS_PAYMENT_SUCCESS.getCode());
        } else {
            updateT.setOrderStatus(EnumOrderStatus.ORDER_STATUS_COOPERATING_COMPLETE.getCode());
        }
        updateT.setUpdateDate(currentDate);
        int ret = 0;
        try {
            wxOrderMapper.updateByPrimaryKeySelective(updateT);
        } catch (Exception e) {
            logger.error("订单更新失败：" + e.getMessage());
            throw new MallinkException(ErrorCode.ORDER_UPDATE_ERR);
        }

        //  创建couponOrder
        try {
            createCouponOrder(user, updateOrder, coupon);
        } catch (Exception e) {
            logger.error("保存订单：" + e.getMessage());
            throw new MallinkException(ErrorCode.COUPON_ORDER_SAVE_ERR);
        }

        //  发券couponOrder
        try {
            wxCouponSendService.sendCouponToUser(EnumCouponSendSendType.C_ORDER,updateOrder);
        } catch (Exception e) {
            logger.error("订单发券：" + e.getMessage());
        }


        // 成长值 计算
        try {
            wxScoreRulesService.addScore2(EnumScoreType.CONSUMPTION, updateOrder, coupon.getBusiness());
        } catch (Exception e) {
            logger.error("成长值:" + e.getMessage());
        }
        return ret;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = {Exception.class})
    public int microPayOrderSuccess(WxOrder updateOrder) {
        Date currentDate = new Date();
        // C端用户
        WxCUser user = wxCUserMapper.selectByPrimaryKey(updateOrder.getcUserId());
        if (user == null) {
            logger.error("用户不存在, userId: " + updateOrder.getcUserId());
            throw new MallinkException(ErrorCode.USER_IS_EMPTY);
        }
        // B端用户
        WxMerchantBUser bUser = wxMerchantBUserMapper.selectByPrimaryKey(updateOrder.getProductId());
        if(bUser == null) {
            logger.error("B端用户不存在, bUserId: " + updateOrder.getProductId());
            throw new MallinkException(ErrorCode.USER_IS_EMPTY);
        }
        // 基于B端User查找merchant
        WxMerchant wxMerchant = wxMerchantMapper.selectByPrimaryKey(bUser.getMerchantId());
        if(wxMerchant == null) {
            logger.error("商户不存在, merchantId: " + bUser.getMerchantId());
            throw new MallinkException(ErrorCode.MERCHANT_INFO_NOT_FOUND);
        }
        // 已支付,更新支付时间
        updateOrder.setPaymentTime(currentDate);
        updateOrder.setOrderStatus(EnumOrderStatus.ORDER_STATUS_PAYMENT_SUCCESS.getCode());
        updateOrder.setUpdateDate(currentDate);
        int ret = 0;
        try {
            ret = wxOrderMapper.updateByPrimaryKey(updateOrder);
        } catch (Exception e) {
            logger.error("订单更新失败：" + e.getMessage());
            throw new MallinkException(ErrorCode.ORDER_UPDATE_ERR);
        }

        // 成长值 计算
        try {
            wxScoreRulesService.addScore2(EnumScoreType.CONSUMPTION, updateOrder, wxMerchant.getBusinessId());
        } catch (Exception e) {
            logger.error("成长值:" + e.getMessage());
        }

        return ret;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = {Exception.class})
    public int updateOrderStatus(WxOrder updateOrder, EnumOrderStatus enumOrderStatus) {
        Date currentDate = new Date();
        switch (enumOrderStatus) {
            case ORDER_STATUS_OVERTIME_CANCEL:
            case ORDER_STATUS_REFUND_SUCCESS: {
                try {
                    stockBack(updateOrder);
                } catch (Exception e) {
                    logger.error("库存+1失败, e:" + e.getMessage());
                    throw new MallinkException(ErrorCode.REMAIN_BACK_FAIL);
                }
                break;
            }
            case ORDER_STATUS_COOPERATING_OVERTIME: {
                try {
                    stockBack(updateOrder);
                } catch (Exception e) {
                    logger.error("库存+1失败, e:" + e.getMessage());
                    throw new MallinkException(ErrorCode.REMAIN_BACK_FAIL);
                }
                break;
            }
            case ORDER_STATUS_COOPERATING_CANCEL: {
                try {
                    stockBack(updateOrder);
                } catch (Exception e) {
                    logger.error("库存+1失败, e:" + e.getMessage());
                    throw new MallinkException(ErrorCode.REMAIN_BACK_FAIL);
                }
                break;
            }
            case ORDER_STATUS_COOPERATING_COMPLETE: {
                try {
                    stockBack(updateOrder);
                } catch (Exception e) {
                    logger.error("库存+1失败, e:" + e.getMessage());
                    throw new MallinkException(ErrorCode.REMAIN_BACK_FAIL);
                }
                break;
            }
        }
        updateOrder.setOrderStatus(enumOrderStatus.getCode());
        updateOrder.setUpdateDate(currentDate);
        int ret = 0;
        try {
            ret = wxOrderMapper.updateByPrimaryKey(updateOrder);
        } catch (Exception e) {
            logger.error("订单状态更新失败, e:" + e.getMessage());
            throw new MallinkException(ErrorCode.ORDER_UPDATE_ERR);
        }
        return ret;
    }


    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = {Exception.class})
    public void updateOrderStatus(WxOrder updateOrder) {
        if (updateOrder.getOrderStatus().equals(EnumOrderStatus.ORDER_STATUS_COOPERATING_OVERTIME.getCode()) ||
                updateOrder.getOrderStatus().equals(EnumOrderStatus.ORDER_STATUS_COOPERATING_CANCEL.getCode()) ||
                updateOrder.getOrderStatus().equals(EnumOrderStatus.ORDER_STATUS_COOPERATING_COMPLETE.getCode()) ||
                updateOrder.getOrderStatus().equals(EnumOrderStatus.ORDER_STATUS_COOPERATING_FAILD.getCode())) {
            try {
                stockBack(updateOrder);
            } catch (Exception e) {
                logger.error("拼团库存+1失败, e:" + e.getMessage());
                throw new MallinkException(ErrorCode.REMAIN_BACK_FAIL);
            }
        }
    }

    /**
     * 微信关闭订单
     */
    @Override
    public ResultData orderClose(WxOrder order) {
        // 1. get c appid
        WxAppinfo appInfo = wxAppinfoService.getCAppInfo(order.getTenantId());
        // 2. get pay order
        WxPayOrder payOrderQ = new WxPayOrder();
        payOrderQ.setTenantId(order.getTenantId());
        payOrderQ.setOrderId(order.getId());
        payOrderQ.setPayOrderStatus(EnumPayStatus.PAY_STATUS_WAIT.getCode());
        List<WxPayOrder> payOrders = wxPayOrderMapper.select(payOrderQ);

        // 3. wx pay order close
        for(WxPayOrder payOrder: payOrders) {
            try {
                wxPayOrderService.payOrderClose(appInfo, payOrder);
            } catch (Exception e) {
                logger.error("微信关单失败：" + e.getMessage());
                throw new MallinkException(ErrorCode.PAY_ORDER_ERROR);
            }
        }

        return new ResultData();
    }

    @Override
    public WxOrder getById(Long id) {
        return wxOrderMapper.selectByPrimaryKey(id);
    }

    @Override
    public void saveOrUpdate(WxOrder record) {
        if (record.getId() == null) {
            //record.setId(UUID.randomUUID().toString().replaceAll("-", ""));
            final IdWorker idWorker = IdWorker.get();
            record.setId(idWorker.nextId());
            wxOrderMapper.insertSelective(record);
        } else {
            wxOrderMapper.updateByPrimaryKeySelective(record);
        }
    }

    @Override
    public void deleteById(Long id) {
        wxOrderMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<WxOrder> findList(WxOrder record) {
        return wxOrderMapper.findList(record);
    }

    @Override
    public PageInfo<WxOrderCouponVo> listCUserVoAsPage(WxOrder record, Integer pageIndex, Integer pageSize) {
        return PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo(() -> wxOrderMapper.findListOfCUser(record));
    }

    @Override
    public WxOrderCouponVo detailCUserVo(WxOrder record) {
        return wxOrderMapper.selectDetailOfCUser(record);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = {Exception.class})
    public void shareForMicroPay(String tenantId, Long orderId, Long payOrderId) {
        // 微信分账
        try {
            WxPayOrder wxPayOrder = new WxPayOrder();
            wxPayOrder.setTenantId(tenantId);
            wxPayOrder.setId(payOrderId);
            wxPayOrder.setOrderId(orderId);
            wxPayOrder.setPayOrderStatus(EnumPayStatus.PAY_STATUS_SUCCESS.getCode());
            wxPayOrder = wxPayOrderMapper.selectOne(wxPayOrder);
            WxOrder wxOrder = wxOrderMapper.selectByPrimaryKey(orderId);
            WxMerchantBUser wxMerchantBUser = wxMerchantBUserMapper.selectByPrimaryKey(wxOrder.getProductId());

            if (wxPayOrder != null && wxMerchantBUser != null &&
                    wxPayOrder.getShare().equals(EnumPayShare.YES.getCode())) {
                WxSharingOrderDto sharingOrder = new WxSharingOrderDto();
                sharingOrder.setcUserId(wxPayOrder.getcUserId());
                sharingOrder.setMerchantId(wxMerchantBUser.getMerchantId());
                sharingOrder.setType(EnumProfitSharingOrderType.PROFIT_SHARING_SINGLE.getCode());
                sharingOrder.setPayAmount(wxPayOrder.getPayAmount());
                sharingOrder.setOrderId(wxPayOrder.getId());
                sharingOrder.setPayTimeStart(wxPayOrder.getPayTimeStart());
                sharingOrder.setPayTimeEnd(wxPayOrder.getPayTimeEnd());
                sharingOrder.setTenantId(wxPayOrder.getTenantId());
                sharingOrder.setTransactionId(wxPayOrder.getTransactionId());
                sharingOrder.setShareAmount(wxPayOrder.getShareAmount());
                ResultData resultData = wxProfitSharingOrderService.createSharingOrder(sharingOrder);
            } else {
                logger.error("微信分账: 未找到payorder or merchant at orderid-" + orderId);
            }
        } catch (MallinkException e) {
            logger.error("微信分账: " + e.getMessage());
        }
    }

    @Override
    public PageInfo<WxOrder> listOrderAsPage(WxOrderQueryVo record, Integer pageIndex, Integer pageSize) {
        return PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo(() -> wxOrderMapper.findListOrder(record));
    }

    @Override
    public Map<String, Object> queryOrderSummary(String tenantId) {
        Map<String, Object> result = new HashMap<>();
        queryMerchantCount(tenantId, result);
        queryOrderSummary(tenantId,result);
        return result;
    }

    public void queryMerchantCount(String tenantId, Map<String, Object> result) {
        String systemTime = DateUtils.getSystemTime("yyyy-MM-dd");
        //全部商户个数
        Map<String, Object> params = new HashMap<>();
        params.put("tenantId", tenantId);
        String thirtyTime = DateUtils.getTimeBefore(29, new Date());
        params.put("startdate", thirtyTime + " 00:00:00");
        params.put("enddate", systemTime + " 23:59:59");
        Long allMerchantCount=wxOrderMapper.queryOrderForMerchantCount(params);
        result.put("allMerchantCount",allMerchantCount);
        //今日
        params.put("startdate", systemTime + " 00:00:00");
        params.put("enddate", systemTime + " 23:59:59");
        Long todayMerchantCount=wxOrderMapper.queryOrderForMerchantCount(params);
        result.put("todayMerchantCount",todayMerchantCount);
        //昨日
        String yesterday = DateUtils.getTimeBefore(1, new Date());
        params.put("startdate", yesterday + " 00:00:00");
        params.put("enddate", yesterday + " 23:59:59");
        Long yesterdayMerchantCount=wxOrderMapper.queryOrderForMerchantCount(params);
        result.put("yesterdayMerchantCount",yesterdayMerchantCount);
        //上周
        String lastweek = DateUtils.getTimeBefore(7, new Date());
        params.put("startdate", lastweek + " 00:00:00");
        params.put("enddate", lastweek + " 23:59:59");
        Long lastweekMerchantCount=wxOrderMapper.queryOrderForMerchantCount(params);
        result.put("lastweekMerchantCount",lastweekMerchantCount);
        //商户数日环比
        if (yesterdayMerchantCount > 0) {
            double hbd = (double) (todayMerchantCount - yesterdayMerchantCount) / yesterdayMerchantCount * 100;
            double hb = new BigDecimal(hbd).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            result.put("increasedPercentMerchant", hb+"%");
        } else {
            result.put("increasedPercentMerchant", "--");
        }
        //商户数周同比
        if (lastweekMerchantCount > 0) {
            double hbd = (double) (todayMerchantCount - lastweekMerchantCount) / lastweekMerchantCount * 100;
            double hb = new BigDecimal(hbd).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            result.put("increasedPercentWeekMerchant", hb+"%");
        } else {
            result.put("increasedPercentWeekMerchant", "--");
        }
    }

    public void queryOrderSummary(String tenantId, Map<String, Object> result) {
        String systemTime = DateUtils.getSystemTime("yyyy-MM-dd");
        //总数
        Map<String, Object> params = new HashMap<>();
        params.put("tenantId", tenantId);
        String thirtyTime = DateUtils.getTimeBefore(29, new Date());
        params.put("startdate", thirtyTime + " 00:00:00");
        params.put("enddate", systemTime + " 23:59:59");
        params.put("order_status", "1");
        Long allPayOrderSummary=wxOrderMapper.queryOrderForSum(params);
        params.put("order_status", "4");
        Long allRefundOrderSummary=wxOrderMapper.queryOrderForSum(params);
        result.put("allRefundOrderSummary", allRefundOrderSummary);
        Long allOrderSummary = allPayOrderSummary - allRefundOrderSummary;
        result.put("allOrderSummary",allPayOrderSummary);
        //今日
        params.put("startdate", systemTime + " 00:00:00");
        params.put("enddate", systemTime + " 23:59:59");
        params.put("order_status", "1");
        Long todayPayOrderSummary=wxOrderMapper.queryOrderForSum(params);
        params.put("order_status", "4");
        Long todayRefundOrderSummary=wxOrderMapper.queryOrderForSum(params);
        result.put("todayRefundOrderSummary", todayRefundOrderSummary);
        result.put("todayOrderSummary",todayPayOrderSummary);
        //昨日
        String yesterday = DateUtils.getTimeBefore(1, new Date());
        params.put("startdate", yesterday + " 00:00:00");
        params.put("enddate", yesterday + " 23:59:59");
        params.put("order_status", "1");
        Long yesterdayPayOrderSummary=wxOrderMapper.queryOrderForSum(params);
        params.put("order_status", "4");
        Long yesterdayRefundOrderSummary=wxOrderMapper.queryOrderForSum(params);
        result.put("yesterdayRefundOrderSummary", yesterdayRefundOrderSummary);
        result.put("yesterdayOrderSummary",yesterdayPayOrderSummary);
        //上周
        String lastweek = DateUtils.getTimeBefore(7, new Date());
        params.put("startdate", lastweek + " 00:00:00");
        params.put("enddate", lastweek + " 23:59:59");
        params.put("order_status", "1");
        Long lastweekPayOrderSummary=wxOrderMapper.queryOrderForSum(params);
        params.put("order_status", "4");
        Long lastweekRefundOrderSummary=wxOrderMapper.queryOrderForSum(params);
        result.put("lastweekRefundOrderSummary", lastweekRefundOrderSummary);
        result.put("lastweekOrderSummary",lastweekPayOrderSummary);
        //商户数日环比
        if (yesterdayPayOrderSummary > 0) {
            double hbd = (double) (todayPayOrderSummary - yesterdayPayOrderSummary) / yesterdayPayOrderSummary * 100;
            double hb = new BigDecimal(hbd).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            result.put("increasedPercentSummary", hb+"%");
        } else {
            result.put("increasedPercentSummary", "--");
        }
        //商户数周同比
        if (lastweekPayOrderSummary > 0) {
            double hbd = (double) (todayPayOrderSummary - lastweekPayOrderSummary) / lastweekPayOrderSummary * 100;
            double hb = new BigDecimal(hbd).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            result.put("increasedPercentWeekSummary", hb+"%");
        } else {
            result.put("increasedPercentWeekSummary", "--");
        }
    }

    /** 砍价 */
    @Override
    public PageInfo<WxOrderCouponPressVo> listPressVoAsPage(WxOrder record, Integer pageIndex, Integer pageSize) {
        return PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo(() -> wxOrderMapper.findListOfPress(record));
    }

    @Override
    public WxOrderCouponPressVo detailPressVo(WxOrder record) {
        return wxOrderMapper.selectDetailOfPress(record);
    }

    @Override
    public void updateStatusByPressCouponId(Long couponId, String tenantId, int orderStatus) {
        WxOrder updateOrder = new WxOrder();
        updateOrder.setTenantId(tenantId);
        updateOrder.setOrderStatus(orderStatus);
        updateOrder.setProductId(couponId);
        updateOrder.setUpdateDate(new Date());
        wxOrderMapper.updateStatusByPressCouponId(updateOrder);
    }

}
