package cn.pluss.platform.merchantOrder.impl;

import cn.hutool.crypto.SecureUtil;
import cn.pluss.platform.IdCardService;
import cn.pluss.platform.PushService;
import cn.pluss.platform.activityConsumReturn.ActivityConsumReturnService;
import cn.pluss.platform.activityRecharge.ActivityRechargeService;
import cn.pluss.platform.api.PageInfo;
import cn.pluss.platform.api.Result;
import cn.pluss.platform.api.ResultCode;
import cn.pluss.platform.api.ResultGenerator;
import cn.pluss.platform.constants.Constant;
import cn.pluss.platform.constants.ProjectConstant;
import cn.pluss.platform.dto.MemberRechargeDTO;
import cn.pluss.platform.dto.MemberScanPayDTO;
import cn.pluss.platform.dto.MerChantOrderDTO;
import cn.pluss.platform.entitiy.SettleTypeEnum;
import cn.pluss.platform.entity.*;
import cn.pluss.platform.enums.UserRoleEnum;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.mapper.*;
import cn.pluss.platform.memberOrder.MemberOrderService;
import cn.pluss.platform.merchant.MerchantCashPlaceService;
import cn.pluss.platform.merchant.MerchantCashPlaceStaffService;
import cn.pluss.platform.merchant.MerchantRateNewService;
import cn.pluss.platform.merchant.move.MerchantMoveRecordsService;
import cn.pluss.platform.merchant.MerchantBaseInfoService;
import cn.pluss.platform.merchantChannelStatus.MerchantChannelStatusService;
import cn.pluss.platform.merchantMemberCode.MerchantMemberCodeService;
import cn.pluss.platform.merchantMenber.MerchantMenberService;
import cn.pluss.platform.merchantMenberRecharge.MerchantMenberRechargeService;
import cn.pluss.platform.merchantOrder.MerchantOrderService;
import cn.pluss.platform.merchantOrderSplit.MerchantOrderSplitService;
import cn.pluss.platform.merchantProfit.MerchantProfitService;
import cn.pluss.platform.merchantStore.MerchantStoreService;
import cn.pluss.platform.notice.NoticeService;
import cn.pluss.platform.notify.NotifyMessageService;
import cn.pluss.platform.officialGoods.exchange.OfficialGoodsExchangeService;
import cn.pluss.platform.pay.PayService;
import cn.pluss.platform.realFans.RealFansService;
import cn.pluss.platform.ryx.RyxConstants;
import cn.pluss.platform.ryx.pay.RyxPayService;
import cn.pluss.platform.suixingfu.SxfConstants;
import cn.pluss.platform.sxf.pay.SxfPayService;
import cn.pluss.platform.sys.QueueDataService;
import cn.pluss.platform.user.UserVoiceService;
import cn.pluss.platform.user.impl.GeneralPushUtil;
import cn.pluss.platform.userApp.UserAppService;
import cn.pluss.platform.userAssess.UserAssessService;
import cn.pluss.platform.userInfo.UserInfoService;
import cn.pluss.platform.userIntegral.UserIntegralService;
import cn.pluss.platform.userIntegralUse.UserIntegralUseService;
import cn.pluss.platform.util.*;
import cn.pluss.platform.vo.*;
import cn.pluss.platform.ys.YsBusinessCodeEnum;
import cn.pluss.platform.ys.YsOldConstants;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.opencsv.CSVReader;
import com.opencsv.CSVReaderBuilder;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;

/**
 * @author admin
 */
@Transactional
@Slf4j
@Service("merchantOrderService")
public class MerchantOrderServiceImpl extends ServiceImpl<MerchantOrderMapper, MerchantOrder> implements MerchantOrderService {

    @Autowired
    private GeneralPushUtil generalPushUtil;


    @Setter(onMethod_ = {@Autowired})
    private MerchantOrderVOMapper merchantOrderVOMapper;
    @Setter(onMethod_ = {@Autowired})
    private UserAppMapper userAppMapper;
    @Setter(onMethod_ = {@Autowired})
    private MemberOrderService memberOrderService;
    @Setter(onMethod_ = {@Autowired})
    private MerchantBaseInfoService merchantBaseInfoService;
    @Setter(onMethod_ = {@Autowired})
    private MerchantOrderMapper merchantOrderMapper;
    @Setter(onMethod_ = {@Autowired,@Lazy})
    private MerchantChannelStatusService merchantChannelStatusService;
    @Setter(onMethod_ = {@Autowired})
    private MerchantStoreMapper merchantStoreMapper;
    @Setter(onMethod_ = {@Autowired})
    private ActivityRechargeService activityRechargeService;
    @Setter(onMethod_ = {@Autowired})
    private NoticeService noticeService;

    @Setter(onMethod_ = {@Autowired})
    private MerchantMenberMapper merchantMenberMapper;

    @Setter(onMethod_ = {@Lazy, @Autowired})
    private IdCardService idCardService;
    @Setter(onMethod_ = {@Autowired, @Lazy})
    private SxfPayService sxfPayService;
    @Setter(onMethod_ = {@Autowired})
    private RyxPayService ryxPayService;

    @Setter(onMethod_ = {@Autowired, @Qualifier("ysPayOldService")})
    private PayService ysPayOldService;

    @Setter(onMethod_ = {@Autowired})
    private UserAppService userAppService;

    @Setter(onMethod_ = {@Lazy, @Autowired})
    private RealFansService realFansService;
    @Setter(onMethod_ = {@Lazy, @Autowired})
    private MerchantIncomeMapper merchantIncomeMapper;

    @Setter(onMethod_ = {@Lazy, @Autowired})
    private ActivityConsumReturnService activityConsumReturnService;
    @Setter(onMethod_ = {@Lazy, @Autowired})
    private MerchantMenberComsumeMapper merchantMenberComsumeMapper;
    @Setter(onMethod_ = {@Lazy, @Autowired})
    private MerchantMenberRechargeMapper merchantMenberRechargeMapper;
    @Setter(onMethod_ = {@Lazy, @Autowired})
    private MerchantRefundOrderMapper merchantRefundOrderMapper;
    @Setter(onMethod_ = {@Lazy, @Autowired})
    private ActivityEnrollMapper activityEnrollMapper;
    @Setter(onMethod_ = {@Lazy, @Autowired})
    private OfficialActivityMapper officialActivityMapper;
    @Setter(onMethod_ = {@Lazy, @Autowired})
    private MerchantMarketMapper merchantMarketMapper;
    @Setter(onMethod_ = {@Lazy, @Autowired})
    private MerchantPluginMapper merchantPluginMapper;
    @Setter(onMethod_ = {@Lazy, @Autowired})
    private MerchantCashPlaceStaffService cashPlaceStaffService;
    @Setter(onMethod_ = {@Lazy, @Autowired})
    private PushService pushService;
    @Setter(onMethod_ = {@Lazy, @Autowired})
    private UserInfoService userInfoService;

    @Setter(onMethod_ = {@Lazy, @Autowired})
    private NotifyMessageService notifyMessageService;

    @Setter(onMethod_ = {@Lazy, @Autowired})
    private MerchantRateNewService merchantRateNewService;

    @Setter(onMethod_ = {@Lazy, @Autowired})
    private MerchantMoveRecordsService merchantMoveRecordsService;

    @Setter(onMethod_ = {@Lazy, @Autowired})
    private MerchantStoreService merchantStoreService;

    @Setter(onMethod_ = {@Lazy, @Autowired})
    private MerchantMenberRechargeService menberRechargeService;

    @Setter(onMethod_ = {@Lazy, @Autowired})
    private MerchantMenberService merchantMenberService;

    @Setter(onMethod_ = {@Lazy, @Autowired})
    private MerchantProfitService merchantProfitService;

    @Setter(onMethod_ = {@Lazy, @Autowired})
    private MerchantCashPlaceService merchantCashPlaceService;

    @Resource
    private OfficialGoodsExchangeService officialGoodsExchangeService;

    @Autowired
    private ExecutorService executorService;

    @Resource
    private QueueDataService queueDataService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Setter(onMethod_ = {@Lazy, @Autowired})
    private UserVoiceService userVoiceService;

    @Resource
    private UserIntegralService userIntegralService;

    @Resource
    private UserIntegralUseService userIntegralUseService;

    @Resource
    private MerchantMemberCodeService merchantMemberCodeService;

    @Resource
    private UserAssessService userAssessService;

    @Resource
    private MerchantOrderSplitService merchantOrderSplitService;


    @Override
    public Map<String, Object> billCollect(MerchantOrder merchantOrder) {
        UserApp tokenUserApp = userAppService.queryUserAppByToken();
        if (!"1".equals(tokenUserApp.getPermissionBill())) {
            merchantOrder.setStaffCode(tokenUserApp.getUserId() + "");
        }

        QueryWrapper<Object> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("ua.userId", tokenUserApp.getUserId());
        tokenUserApp = userAppService.appGetOne(queryWrapper2);

        if ("staff".equals(tokenUserApp.getUserType()) && "0".equals(tokenUserApp.getPermissionBill())) {
            merchantOrder.setStaffCode(tokenUserApp.getUserId() + "");
        }

        if (merchantOrder.getStartTime() == null) {
            merchantOrder.setStartTime(DateUtils.getDayBegin());
        }

        if (merchantOrder.getEndTime() == null) {
            merchantOrder.setEndTime(DateUtils.getDayEnd());
        }

        if (merchantOrder.getSize() == null || merchantOrder.getSize() == 0) {
            merchantOrder.setSize(ProjectConstant.PAGE_SIZE);
        }

        if (merchantOrder.getPage() == null || merchantOrder.getPage() == 0) {
            merchantOrder.setPage(1);
        }

        // 初始化支付方式条件
        String payTypeCode = merchantOrder.getPayTypeCode();
        if (payTypeCode != null) {
            payTypeCode = payTypeCode.replace("wechatPay", "wechatPay,leshuaPay1,leshuaPay-1,leshuaPay,sxfPay1");
            payTypeCode = payTypeCode.replace("aliPay", "aliPay,leshuaPay0,leshuaPay-0,leshuaPay,sxfPay0");
            payTypeCode = payTypeCode.replace("bank", "leshuaPay2,bank,sxfPay2");
            merchantOrder.setPayTypeCode(payTypeCode);
        }

        // 获取通用查询条件
        LambdaQueryWrapper<MerchantOrderVO> queryWrapper = getConditionWrapper(merchantOrder);

        // 计算总数
        LambdaQueryWrapper<MerchantOrderVO> countQueryWrapper = queryWrapper.clone();
        if (StringUtils.isEmpty(merchantOrder.getStatus())) {
            countQueryWrapper.in(MerchantOrder::getStatus, "1");
        }
        Integer orderCount = merchantOrderVOMapper.selectCount(countQueryWrapper);

        // 计算总和
        LambdaQueryWrapper<MerchantOrderVO> queryWrapperTotal = queryWrapper.clone();
        queryWrapperTotal.groupBy(MerchantOrder::getStatus);
        List<Map<String, Object>> feeList = baseMapper.getSumConsumeFee(queryWrapperTotal);
        BigDecimal totalOrderFee = BigDecimal.ZERO;
        for (Map<String, Object> fee : feeList) {
            if ("1".equals(fee.get("status"))) {
                totalOrderFee = totalOrderFee.add(new BigDecimal(fee.get("fee").toString()));
            } else {
                totalOrderFee = totalOrderFee.subtract(new BigDecimal(fee.get("fee").toString()));
            }
        }
        // 添加分页条件后获取订单列表
        LambdaQueryWrapper<MerchantOrderVO> pageQuery = queryWrapper.clone();
        pageQuery.orderByDesc(MerchantOrder::getCreateDt);

        Page<MerchantOrderVO> page = new Page<>(merchantOrder.getPage(), merchantOrder.getSize());
        IPage<MerchantOrderVO> pageMerchantOrder = merchantOrderVOMapper.selectPage(page, pageQuery);

        Integer userId = merchantOrder.getUserId();
        IdCard idCard = new IdCard().setUserId(userId + "").setUserType("01");
        idCard = idCardService.getOne(new QueryWrapper<>(idCard));

        for (MerchantOrderVO item : pageMerchantOrder.getRecords()) {
            if ("2".equals(item.getStatus())) {
                item.setEnterFee(item.getConsumeFee());
            }

            item.setAlias(item.getStoreName());
            MerchantOrder.updateStaffName(item, item.getMerchantCode(), idCard);
            MerchantOrder.updateOrderTypeDesc(item);

            MerchantOrderVO.setD0Fee(item);
        }

        Map<String, Object> resultMap = new HashMap<>();
        PageInfo<MerchantOrderVO> pager = PageUtils.page(pageMerchantOrder);
        resultMap.put("pager", pager);
        resultMap.put("orderCount", orderCount);
        resultMap.put("totalOrderFee", totalOrderFee);

        return resultMap;
    }

    /**
     * 根据实体类信息，包装的查询条件
     *
     * @param merchantOrder
     * @return
     */
    private <E extends MerchantOrder> LambdaQueryWrapper<E> getConditionWrapper(MerchantOrder merchantOrder) {
        LambdaQueryWrapper<E> queryWrapper = Wrappers.lambdaQuery();

        if (StringUtils.isNotEmpty(merchantOrder.getPayTypeCode())) {
            queryWrapper.in(MerchantOrder::getPayTypeCode, merchantOrder.getPayTypeCode().split(","));
        }

        queryWrapper.ge(MerchantOrder::getUpdateTime, merchantOrder.getStartTime());
        queryWrapper.lt(MerchantOrder::getUpdateTime, merchantOrder.getEndTime());
        queryWrapper.eq(merchantOrder.getSettlementType() != null, MerchantOrder::getSettlementType, merchantOrder.getSettlementType());

        if (StringUtils.isEmpty(merchantOrder.getStatus())) {
            queryWrapper.in(MerchantOrder::getStatus, "1", "2");
        } else {
            queryWrapper.in(MerchantOrder::getStatus, merchantOrder.getStatus());
        }

        if (StringUtils.isNotEmpty(merchantOrder.getStaffCode())) {
            queryWrapper.in(MerchantOrder::getStaffCode, merchantOrder.getStaffCode().split(","));
        }

        if (StringUtils.isNotEmpty(merchantOrder.getCashPlaceId())) {
            queryWrapper.in(MerchantOrder::getCashPlaceId, merchantOrder.getCashPlaceId().split(","));
        }

        if (StringUtils.isNotEmpty(merchantOrder.getMerchantCode())) {
            queryWrapper.in(MerchantOrder::getMerchantCode, merchantOrder.getMerchantCode().split(","));
        }

        return queryWrapper;
    }

    @Override
    public Integer queryMerchantOrderPageCountApp(Map map) {
        return baseMapper.queryMerchantOrderPageCountApp(map);
    }

    @Override
    public SummaryOfWaterVO querySummaryOfWater(Map map) {
        return baseMapper.querySummaryOfWater(map);
    }

    @Override
    public List<MerchantOrder> queryMerchantOrderRefundPage(Map map) {
        return baseMapper.queryMerchantOrderRefundPage(map);
    }

    @Override
    public Integer queryMerchantOrderRefundPageCount(Map map) {
        return baseMapper.queryMerchantOrderRefundPageCount(map);
    }

    @Override
    public List<OrderStatisticsVO> queryOrderStatistics(MerchantOrder s) {
        return baseMapper.queryOrderStatistics(s);
    }

    @Override
    public List<PayTypeStatisticsVO> queryPayTypeStatistics(MerchantOrder s) {
        return baseMapper.queryPayTypeStatistics(s);
    }

    @Override
    public List<MerchantMangeOrderVO> queryMerchantOrderPageShuju(Map<String, Object> map) {
        return baseMapper.queryMerchantOrderPageShuju(map);
    }

    @Override
    public Integer queryMerchantOrderPageCountShuju(Map<String, Object> map) {
        return baseMapper.queryMerchantOrderPageCountShuju(map);
    }

    @Override
    public Map<String, Object> platformSum() {
        Map<String, Object> result = new HashMap<>(16);
        // 总的统计
        PlatformSumVO platformSum = baseMapper.PlatformSum(null);
        // 今日数据统计
        PlatformSumVO platformSum2 = baseMapper.PlatformSum("1");
        // 昨日数据统计
        PlatformSumVO platformSum3 = baseMapper.PlatformSum("2");
        Double aliSumPlatformSum = Optional.ofNullable(platformSum.getAliSum()).orElse(0d);
        Double wechatSumPlatformSum = Optional.ofNullable(platformSum.getWechatSum()).orElse(0d);
        Double leshuaSumPlatformSum = Optional.ofNullable(platformSum.getLeshuaSum()).orElse(0d);
        platformSum.setEarnings(aliSumPlatformSum + wechatSumPlatformSum + leshuaSumPlatformSum);
        result.put("platformSum", platformSum);

        Double aliSumPlatformSum2 = Optional.ofNullable(platformSum2.getAliSum()).orElse(0d);
        Double wechatSumPlatformSum2 = Optional.ofNullable(platformSum2.getWechatSum()).orElse(0d);
        Double leshuaSumPlatformSum2 = Optional.ofNullable(platformSum2.getLeshuaSum()).orElse(0d);

        platformSum2.setEarnings(aliSumPlatformSum2 + wechatSumPlatformSum2 + leshuaSumPlatformSum2);
        result.put("platformSumToDay", platformSum2);
        Double aliSumPlatformSum3 = Optional.ofNullable(platformSum3.getAliSum()).orElse(0d);
        Double wechatSumPlatformSum3 = Optional.ofNullable(platformSum3.getWechatSum()).orElse(0d);
        Double leshuaSumPlatformSum3 = Optional.ofNullable(platformSum3.getLeshuaSum()).orElse(0d);
        platformSum3.setEarnings(aliSumPlatformSum3 + wechatSumPlatformSum3 + leshuaSumPlatformSum3);
        result.put("platformSumYesterDay", platformSum3);
        return result;
    }

    @Override
    public Map<String, Object> queryHomePageData(UserApp userApp) {
        UserApp tokenApp = userAppService.queryUserAppByToken();
        Map<String, Object> resultMap = new HashMap<>(16);

        val hasPermission= "1".equals(tokenApp.getPermissionBill()) || "promoter".equals(tokenApp.getUserType());

        if (StringUtils.isEmpty(tokenApp.getMerchantCode())) {
            resultMap.put("todayConsumeFee", 0.00);
            resultMap.put("orderCount", 0);
            resultMap.put("fanCount", 0);

            return resultMap;
        }

        MsgException.checkNull(userApp.getUserId(), "无用户id");

        // 今日订单总金额
        BigDecimal todayConsumeFee = BigDecimal.ZERO;
        int orderCount = 0;// 今日订单数量
        Integer fanCount = 0;// 今日粉丝数量
        

        LambdaQueryWrapper<MerchantOrder> queryWrapperTotal = Wrappers.lambdaQuery();
        Date dayBegin = DateUtils.getDayBegin();
        Date dayEnd = DateUtils.getDayEnd();
        queryWrapperTotal.between(MerchantOrder::getCreateDt, dayBegin, dayEnd)
                .eq(MerchantOrder::getMerchantCode, tokenApp.getMerchantCode())
                .in(MerchantOrder::getStatus, "1")
                .groupBy(MerchantOrder::getStatus);
        if (!hasPermission) {
            queryWrapperTotal.eq(MerchantOrder::getStaffCode, tokenApp.getUserId());
        }

        List<Map<String, Object>> feeList = baseMapper.getSumConsumeFee(queryWrapperTotal);
        for (Map<String, Object> fee : feeList) {
            if ("1".equals(fee.get("status"))) {
                todayConsumeFee = todayConsumeFee.add(new BigDecimal(fee.get("fee").toString()));
            } else {
                todayConsumeFee = todayConsumeFee.subtract(new BigDecimal(fee.get("fee").toString()));
            }
        }

        // 先获取普通订单的笔数
        LambdaQueryWrapper<MerchantOrder> orderCountWrapper = Wrappers.lambdaQuery();
        orderCountWrapper.between(MerchantOrder::getCreateDt, dayBegin, dayEnd)
                .eq(MerchantOrder::getMerchantCode, tokenApp.getMerchantCode())
                .eq(MerchantOrder::getStatus, "1")
                .notIn(MerchantOrder::getOrderType, "3", "5");
        if (!hasPermission) {
            orderCountWrapper.eq(MerchantOrder::getStaffCode, tokenApp.getUserId());
        }

        int merchantOrderCount = baseMapper.selectCount(orderCountWrapper);

        LambdaQueryWrapper<MemberOrder> memberCountWrapper = Wrappers.lambdaQuery();
        memberCountWrapper.between(MemberOrder::getCreateDt, dayBegin, dayEnd)
                .eq(MemberOrder::getMerchantCode, tokenApp.getMerchantCode())
                .eq(MemberOrder::getOrderStatus, "1");
        if (!hasPermission) {
            memberCountWrapper.eq(MemberOrder::getStaffCode, tokenApp.getUserId());
        }

        int memberOrderCount = memberOrderService.count(memberCountWrapper);

        val qWrapperNewMemberCount = new QueryWrapper<MerchantMenber>();
        qWrapperNewMemberCount.between("createDt", dayBegin, dayEnd).eq("merchantCode", tokenApp.getMerchantCode());

        orderCount = merchantOrderCount + memberOrderCount;
        Map<String, Object> queryMap2 = new HashMap<>(16);
        queryMap2.put("merchantCode", tokenApp.getMerchantCode());
        queryMap2.put("startTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(dayBegin));
        queryMap2.put("endTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(dayEnd));
        // 今日粉丝数量
//        fanCount = fansService.queryFansPageCount(queryMap2);

        if ("staff".equals(tokenApp.getUserType())) {
            fanCount = 0;
        } else {
            fanCount = merchantMenberMapper.selectCount(qWrapperNewMemberCount);
        }

        resultMap.put("todayConsumeFee", todayConsumeFee + "");
        resultMap.put("memberOrderCount", memberOrderCount + "");
        resultMap.put("orderCount", orderCount + "");
        resultMap.put("fanCount", fanCount + "");

        return resultMap;
    }

    @Override
    public Map<String, Object> queryCheckOrderData(MerchantOrder merchantOrder) {
        UserApp tokenUa = userAppService.queryUserAppByToken();
        merchantOrder.setMerchantCode(tokenUa.getMerchantCode());

        if (StringUtil.isEmpty(merchantOrder.getMerchantCode())) {
            throw new MsgException("无商家编码");
        }
        MerchantBaseInfo queryMerchantBaseInfo = new MerchantBaseInfo();
        queryMerchantBaseInfo.setMerchantCode(merchantOrder.getMerchantCode());
        // 查询当前的商家信息
        List<MerchantBaseInfo> queryMerchantBaseInfoList = merchantBaseInfoService.queryMerchantBaseInfoList(queryMerchantBaseInfo);
        if (queryMerchantBaseInfoList == null || queryMerchantBaseInfoList.size() == 0) {
            throw new MsgException("商家信息不存在");
        }
//        Map<String, Object> queryMap = new HashMap<>(16);
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        if (StringUtil.isNotEmpty(merchantOrder.getStartTime())) {
//            queryMap.put("startTime", merchantOrder.getStartTime());
//        } else {
//            queryMap.put("startTime", sdf.format(DateUtils.getDayBegin()));
//        }
//        if (StringUtil.isNotEmpty(merchantOrder.getEndTime())) {
//            queryMap.put("endTime", merchantOrder.getEndTime());
//        } else {
//            queryMap.put("endTime", sdf.format(DateUtils.getDayEnd()));
//        }
//        queryMap.put("merchantCode", merchantOrder.getMerchantCode());
//        if (merchantOrder.getStaffCode() != null && !StringUtil.isEmpty(merchantOrder.getStaffCode())) {
//            String[] staffCode = merchantOrder.getStaffCode().split(",");
//            List<String> staffCodeList = new ArrayList<>(Arrays.asList(staffCode));
//            queryMap.put("staffCode", staffCodeList);
//        }
//        queryMap.put("status", 1);// 查询交易成功的交易费用

        Integer consumeCount = getConsumeCount(merchantOrder);
        Integer refundCount = getRefundCount(merchantOrder);
        BigDecimal[] arr = getTotalConsumeAndRefund(merchantOrder);
        // 实付金额（订单的交易额）（交易金额）
        BigDecimal totalConsumeFee = arr[0] == null ? BigDecimal.ZERO : arr[0];
        // 净退款
        BigDecimal totalRefundConsumeFee = arr[1] == null ? BigDecimal.ZERO : arr[1];
        // 实收金额
        BigDecimal totalEnterFee = getTotalEnterFee(merchantOrder);
        // 手续费
        BigDecimal totalCommission = getTotalCommission(totalConsumeFee, totalRefundConsumeFee, totalEnterFee);

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("orderNum", consumeCount == null ? 0 : consumeCount);
        resultMap.put("returnOrderNum", refundCount == null ? 0 : refundCount);
        resultMap.put("enterFee", totalEnterFee);
        resultMap.put("totalConsumFee", totalConsumeFee);
        resultMap.put("totalReceiveFee", totalConsumeFee);
        resultMap.put("commission", totalCommission);
        resultMap.put("returnMoney", totalRefundConsumeFee);

        return resultMap;
    }

    private LambdaQueryWrapper<MerchantOrder> getMerchantQueryWrapper(MerchantOrder merchantOrder) {
        return getMerchantQueryWrapper(merchantOrder, true);
    }

    private LambdaQueryWrapper<MerchantOrder> getMerchantQueryWrapper(MerchantOrder merchantOrder, boolean groupFlag) {
        Date start = merchantOrder.getStartTime() == null ? DateUtils.getDayBegin() : merchantOrder.getStartTime();
        Date end = merchantOrder.getEndTime() == null ? DateUtils.getDayEnd() : merchantOrder.getEndTime();
        LambdaQueryWrapper<MerchantOrder> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.between(MerchantOrder::getCreateDt, start, end)
                .eq(MerchantOrder::getMerchantCode, merchantOrder.getMerchantCode())
                .in(MerchantOrder::getStatus, "1", "2")
                .groupBy(groupFlag, MerchantOrder::getStatus);

        if (StringUtils.isNotEmpty(merchantOrder.getStaffCode())) {
            lambdaQueryWrapper.in(MerchantOrder::getStaffCode, merchantOrder.getStaffCode().split(","));
        }

        return lambdaQueryWrapper;
    }

    /**
     * 获取付款单数
     *
     * @return
     */
    public Integer getConsumeCount(MerchantOrder merchantOrder) {
        LambdaQueryWrapper<MerchantOrder> merchantQueryWrapper = getMerchantQueryWrapper(merchantOrder);
        merchantQueryWrapper.in(MerchantOrder::getStatus, "1");
        return baseMapper.selectCount(merchantQueryWrapper);
    }

    /**
     * 获取退款单数
     *
     * @return
     */
    public Integer getRefundCount(MerchantOrder merchantOrder) {
        LambdaQueryWrapper<MerchantOrder> merchantQueryWrapper = getMerchantQueryWrapper(merchantOrder);
        merchantQueryWrapper.in(MerchantOrder::getStatus, "2");
        return baseMapper.selectCount(merchantQueryWrapper);
    }

    /**
     * 获取实付金额和净退款
     *
     * @return
     */
    public BigDecimal[] getTotalConsumeAndRefund(MerchantOrder merchantOrder) {
        BigDecimal[] result = new BigDecimal[2];
        LambdaQueryWrapper<MerchantOrder> merchantQueryWrapper = getMerchantQueryWrapper(merchantOrder);
        List<Map<String, Object>> data = baseMapper.getSumConsumeFee(merchantQueryWrapper);
        for (Map<String, Object> map : data) {
            if ("1".equals(map.get("status"))) {
                result[0] = new BigDecimal(map.get("fee").toString());
            } else {
                result[1] = new BigDecimal(map.get("fee").toString());
            }
        }

        return result;
    }

    /**
     * 获取实收金额, 即除开退款和手续费
     *
     * @param merchantOrder
     * @return
     */
    private BigDecimal getTotalEnterFee(MerchantOrder merchantOrder) {
        LambdaQueryWrapper<MerchantOrder> merchantQueryWrapper = getMerchantQueryWrapper(merchantOrder, false);
        merchantQueryWrapper.in(MerchantOrder::getStatus, "1", "2");
        Map<String, Object> sumMap = baseMapper.getSumEnterFee(merchantQueryWrapper);

        BigDecimal result = new BigDecimal(sumMap.get("fee").toString());

        return result;
    }

    /**
     * 获取手续费信息
     *
     * @param totalConsumeFee       实付金额
     * @param totalRefundConsumeFee 净退款
     * @param totalEnterFee         实收金额
     * @return
     */
    private BigDecimal getTotalCommission(BigDecimal totalConsumeFee, BigDecimal totalRefundConsumeFee, BigDecimal totalEnterFee) {
        return totalConsumeFee.subtract(totalRefundConsumeFee).subtract(totalEnterFee);
    }

    /**
     * 查询订单页面统计
     *
     * @param params
     * @return
     */
    @Override
    public Map<String, Object> querySumCount(Map<String, Object> params) {
        return baseMapper.querySumCount(params);
    }

    /**
     * queryNextMercTransAmtCount
     *
     * @param merchantNoList
     * @return
     */
    @Override
    public Double queryNextMercTransAmtCount(List<String> merchantNoList) {
        return baseMapper.queryNextMercTransAmtCount(merchantNoList);
    }

    /**
     * updateMerchantOrderStatus:(添加订单). <br/>
     *
     * @param
     * @return
     * 
     * @author Administrator
     * @since JDK 1.8
     */
    @Override
    public MerchantOrder saveMerchantOrderStatus(String outTradeNo, MerchantOrder merchantOrder) {
        merchantOrder.setTransNo(outTradeNo);
        merchantOrder.setStatus("1");
        this.baseMapper.updateById(merchantOrder);
        return merchantOrder;
    }

    /**
     * 获取超级代理商下级商户当月交易额
     *
     * @param params
     * @return
     */
    @Override
    public List<Map<String, Object>> getSuperMerchantToDayTradeMoneyCount(Map<String, Object> params) {
        return baseMapper.getSuperMerchantToDayTradeMoneyCount(params);
    }

    /**
     * 订单分润明细分页查询
     *
     * @param map
     * @return
     */
    @Override
    public List<MerchantOrderProfitVO> pageData(Map<String, Object> map) {
        List<MerchantOrderProfitVO> profitInfoPage = merchantOrderMapper.selectProfitPage(map);
        return profitInfoPage;
    }

    @Override
    public Integer pageDataCount(Map<String, Object> map) {
        return merchantOrderMapper.selectProfitPageCount(map);
    }

//    /**
//     * 统计营销活动奖励金
//     *
//     * @return
//     */
//    @Override
//    public Map<String, BigDecimal> getCountMaketAmt(Long userId, String date, String auditDate) {
//        return merchantOrderMapper.getCountMaketAmt(userId, date, auditDate);
//    }

    /**
     * 获取商户当前已经积累的交易额度
     *
     * @param merchantCode
     * @return
     */
    @Override
    public Map<String, Double> getCountTradeAmt(String merchantCode, String date, String startDate, String endDate) {
        return baseMapper.getCountTradeAmt(merchantCode, date, startDate, endDate);
    }

    /**
     * wap 分页查询
     *
     * @param page
     * @param order
     * @return
     */
    @Override
    public Page<MerchantOrder> pageWapInfo(Page<MerchantOrder> page, MerchantOrder order) {
        return this.baseMapper.pageWapInfo(page, order);
    }

    /**
     * 计算累计省钱金额和今日省钱金额
     *
     * @param merchantCode
     * @param nowDate
     * @return
     */
    @Override
    public Map<String, BigDecimal> getSaveMoneyCount(String merchantCode, String nowDate, String startDate, String endDate) {
        return this.baseMapper.getSaveMoneyCount(merchantCode, nowDate, startDate, endDate);
    }


    @Override
    public Result<Object> toActivePay(MerChantOrderDTO dto) {
        //校验参数
        checkActivePayParamsMap(dto);
        //组装订单参数
        if(StringUtils.isNotEmpty(dto.getType()) && "3".equals(dto.getType())){
            MerchantMemberCode menberCode = dto.getMercMenberCode();
            MerchantMenber menber = merchantMenberMapper.getByCardNo(menberCode.getCardNo());
            MemberScanPayDTO memberScanPayDTO = new MemberScanPayDTO(dto,menber);
            MemberScanVO vo = getMemberPayOrder(memberScanPayDTO, menber);
            Map<String, Object> result = new HashMap<>();
            result.put("data",vo);
            result.put("orderNumber",vo.getOrderNumber());
            result.put("message", "交易成功");
            return ResultGenerator.genSuccessResult("支付成功", result);
        }else{
            MerchantOrder order = getMerchantOrder(dto, dto.getConsumeFee(), "1","1");
            return activePay(order, dto);
        }
    }

    /**
     * 主扫会员卡支付
     *
     * @param memberScanPayDTO
     * @return
     */
    @Override
    public Result<MemberScanVO> toMemberScanPay(MemberScanPayDTO memberScanPayDTO) {
        // 校验参数
        MerchantMenber menber = checkMemberScanPayParamsMap(memberScanPayDTO);
        //组装会员订单支付参数
        MemberScanVO vo = getMemberPayOrder(memberScanPayDTO, menber);
        return ResultGenerator.genSuccessResult(vo);
    }

    /**
     * 主扫会员卡充值
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.NOT_SUPPORTED)
    public Result<Map<String, Object>> toMemberRecharge(MemberRechargeDTO dto) {
        // 校验参数
        checkActivePayParamsMap(dto);

        MerchantOrder order = getMerchantOrder(dto, Double.parseDouble(dto.getRechargeMoney()), "1","5");

        QueryWrapper<MerchantMenber> menberWrapper = new QueryWrapper<MerchantMenber>()
                .eq("phone", dto.getPhone()).eq("merchantCode", dto.getMerchantCode()).eq("storeId", dto.getStoreId());

        MerchantMenber menber = merchantMenberMapper.selectOne(menberWrapper);
        MsgException.checkNull(menber, "会员信息有误！");

        MemberOrder memberOrder = new MemberOrder();
        MerchantMenberRecharge recharge = new MerchantMenberRecharge();
        //扫码充值
        Result<Object> mapResult = null;
        if ("0".equals(dto.getType())) {
            mapResult = activePay(order, dto);
            recharge.setPayType(1);
            memberOrder.setRechargeType("2");
        } else if ("1".equals(dto.getType())) {
            // 现金充值
            recharge.setPayType(3);
            memberOrder.setRechargeType("1");
            memberOrder.setOrderStatus("1");
            setMemberRechargeOrder(dto, menber, memberOrder, recharge, order);
            try {
                merchantMenberService.sendMenberBalanceChangeNotice(menber,recharge.getRechargeMoney(),"3");
            }catch (Exception e){
                e.printStackTrace();
            }
            merchantIncome(memberOrder);
            return ResultGenerator.genSuccessResult("充值成功", null);
        }
        if(mapResult.getCode() == ResultCode.SUCCESS.code()){
            memberOrder.setOrderStatus("1");
            setMemberRechargeOrder(dto, menber, memberOrder, recharge, order);
            try {
                merchantMenberService.sendMenberBalanceChangeNotice(menber,recharge.getRechargeMoney(),"1");
            }catch (Exception e){
                e.printStackTrace();
            }
            return ResultGenerator.genSuccessResult("充值成功", null);
        }else if(mapResult.getCode() == ResultCode.TRANSUNKNOW.code()){
            memberOrder.setOrderStatus("2");
            setMemberRechargeOrder(dto, menber, memberOrder, recharge, order);
            return ResultGenerator.genTransunKonwResult("等待支付中...", null);
        }else{
            return ResultGenerator.genFailResult("充值失败！");
        }
    }

    /**
     * @param order
     * @param dto
     * @return
     */
    private Result<Object>  activePay(MerchantOrder order, MerChantOrderDTO dto) {
        log.info("【反扫支付】请求参数：{}", JSON.toJSONString(dto));
        if ("2".equals(order.getAisleSwitch())) {
            JSONObject object = sxfPayService.tradePay(dto, order);
            return scanPay(object, order);
        } else if ("3".equals(order.getAisleSwitch())) {
            JSONObject object = ryxPayService.tradePay(dto, order);
            return scanPay(object, order);
        } else if("4".equals(order.getAisleSwitch())){
            JSONObject object = ysPayOldService.tradePay(dto, order);
            return scanPay(object, order);
        }else{
            throw new MsgException("未知通道！");
        }
    }


    /**
     * 会员充值收益
     *
     * @param memberOrder
     */
    private void merchantIncome(MemberOrder memberOrder) {
        MerchantIncome merchantIncome = new MerchantIncome();
        merchantIncome.setMerchantCode(memberOrder.getMerchantCode());
        merchantIncome.setMerchantName(memberOrder.getMerchantName());
        merchantIncome.setStoreId(memberOrder.getStoreId());
        merchantIncome.setStoreName(memberOrder.getStoreName());
        merchantIncome.setDealFee(Double.valueOf(memberOrder.getOrderFee()));
        merchantIncome.setIncomeFee(Double.valueOf(memberOrder.getOrderFee()));
        merchantIncome.setPayTypeCode("2");
        merchantIncome.setPayTypeName("会员充值");
        merchantIncome.setCreateTime(memberOrder.getCreateDt());
        merchantIncomeMapper.saveMerchantIncome(merchantIncome);
    }

    /**
     * 组装会员充值订单
     *
     * @return
     */
    @Override
    public void setMemberRechargeOrder(MemberRechargeDTO dto, MerchantMenber menber, MemberOrder memberOrder, MerchantMenberRecharge recharge, MerchantOrder order) {

        double totalRechargeFee = menber.getTotalRechargeFee() == null ? 0d : menber.getTotalRechargeFee();// 当前充值总额；
        double usableRechargeFee = menber.getUsableRechargeFee() == null ? 0d : menber.getUsableRechargeFee();// 当前可用充值金额；
        double totalGiveFee = menber.getTotalGiveFee() == null ? 0d : menber.getTotalGiveFee();// 总的赠送金额
        double usableGiveFee = menber.getUsableGiveFee() == null ? 0d : menber.getUsableGiveFee();// 可用的赠送金额
        double rechargeMoney = dto.getRechargeMoney() == null ? 0d : Double.parseDouble(dto.getRechargeMoney());// 本次充值金额；
        totalRechargeFee = totalRechargeFee + rechargeMoney;
        usableRechargeFee = usableRechargeFee + rechargeMoney;
        //获取赠送金额
        double giveMoney = activityRechargeService.getRechargeReturnAmt(dto.getMerchantCode(), dto.getStoreId(), Double.valueOf(dto.getRechargeMoney()));

        totalGiveFee = totalGiveFee + giveMoney;
        usableGiveFee = usableGiveFee + giveMoney;
        menber.setTotalRechargeFee(totalRechargeFee);
        menber.setUsableRechargeFee(usableRechargeFee);
        menber.setTotalGiveFee(totalGiveFee);
        menber.setUsableGiveFee(usableGiveFee);

        memberOrder.setMerchantCode(dto.getMerchantCode());
        memberOrder.setStoreId(dto.getStoreId());
        memberOrder.setStaffCode(String.valueOf(dto.getUserId()));
        memberOrder.setStaffName(dto.getUserName());
        memberOrder.setNickName(menber.getNickName());
        memberOrder.setMemberCode(menber.getMemberCode());
        memberOrder.setOrderType("1");
        Date date = new Date();
        memberOrder.setCreateDt(date);
        memberOrder.setOrderFee(dto.getRechargeMoney());
        memberOrder.setMerchantName(menber.getMerchantName());
        memberOrder.setStoreName(menber.getStoreName());
        memberOrder.setOrderNumber(order.getOrderNumber());
        recharge.setMerchantCode(menber.getMerchantCode());
        recharge.setMerchantName(menber.getMerchantName());
        recharge.setStoreId(menber.getStoreId());
        recharge.setStoreName(menber.getStoreName());
        recharge.setOrderNumber(order.getOrderNumber());
        recharge.setCreateDt(date);
        recharge.setLogo(menber.getLogo());
        recharge.setMemberCode(menber.getMemberCode());
        recharge.setNickName(menber.getNickName());
        recharge.setPhone(menber.getPhone());
        recharge.setRechargeMoney(Double.valueOf(dto.getRechargeMoney()));
        recharge.setGiveMoney(giveMoney);
        if("1".equals(memberOrder.getOrderStatus())){
            merchantMenberMapper.updateMerchantMenber(menber);
            merchantMenberRechargeMapper.saveMerchantMenberRecharge(recharge);
        }
        memberOrderService.saveMemberOrder(memberOrder);
    }

    /**
     * 主扫会员卡充值
     *
     * @param dto
     * @return
     */
    private JSONObject checkMemberRechargeParamsMap(MemberRechargeDTO dto) {
        Optional.ofNullable(dto.getAuthCode()).orElseThrow(() -> new MsgException("无授权码"));
        Optional.ofNullable(dto.getPhone()).orElseThrow(() -> new MsgException("无手机号"));
        Optional.ofNullable(dto.getRechargeMoney()).orElseThrow(() -> new MsgException("无充值金额"));
        Optional.ofNullable(dto.getStoreId()).orElseThrow(() -> new MsgException("无店铺ID"));
        MerchantStore queryStore = new MerchantStore();
        queryStore.setMerchantCode(dto.getMerchantCode());
        queryStore.setStoreId(dto.getStoreId());
        MerchantStore store = merchantStoreMapper.selectOne(new QueryWrapper<>(queryStore));
        Optional.ofNullable(store).orElseThrow(() -> new MsgException("无店铺信息"));
        MsgException.check("2".equals(store.getStatus()), "店铺已被禁用");
        QueryWrapper<MerchantMenber> queryWrapper = new QueryWrapper<MerchantMenber>()
                .eq("phone", dto.getPhone()).eq("merchantCode", dto.getMerchantCode()).eq("storeId", dto.getStoreId());
        MerchantMenber member = merchantMenberMapper.selectOne(queryWrapper);
        MsgException.check(member == null, "不属于当前门店会员");

        MerchantChannelStatus channel = merchantChannelStatusService.getValidData(dto.getMerchantCode());
        MsgException.checkNull(channel,"未获取到商户进件信息，请先提交商户信息");
        MsgException.check("7".equals(channel.getStatus()),"实时到账审核中，请耐心等待或者联系客服！");
        MsgException.check(!channel.isPayment(),"当前进件状态未通过，请耐心等待或联系客服！");

        JSONObject result = new JSONObject(3);
        result.put("channel", channel);
        result.put("member", member);
        result.put("store", store);
        return result;
    }


    /**
     * 组装会员订单参数
     *
     * @param memberScanPayDTO
     * @return
     */
    private MemberScanVO getMemberPayOrder(MemberScanPayDTO memberScanPayDTO, MerchantMenber merchantMenber) {

        MemberScanVO vo = new MemberScanVO();
        vo.setRemark(memberScanPayDTO.getRemark());
        /**
         * 获取充值金额活动对应的返现金额
         */
        MerchantMenberComsume merchantMenberComsume = activityConsumReturnService.getActivityReturnParams(memberScanPayDTO.getMerchantCode(), memberScanPayDTO.getStoreId(), memberScanPayDTO.getConsumeFee());

        Double usableRechargeFee = merchantMenber.getUsableRechargeFee() == null ? 0d : merchantMenber.getUsableRechargeFee();// 可用充值金额
        usableRechargeFee = StringUtil.bigDecimal(usableRechargeFee);
        Double usableGiveFee = merchantMenber.getUsableGiveFee() == null ? 0d : merchantMenber.getUsableGiveFee();// 可用的赠送金额
        usableGiveFee = StringUtil.bigDecimal(usableGiveFee);
        Double count = usableGiveFee + usableRechargeFee;
        if (usableGiveFee >= memberScanPayDTO.getConsumeFee()) {// 可用的赠送余额大于等于消费金额
            usableGiveFee = usableGiveFee - memberScanPayDTO.getConsumeFee();// 扣款之后的赠送金额
        } else {// 可用的赠送余额小于消费金额
            usableGiveFee = 0d;
            usableRechargeFee = count - memberScanPayDTO.getConsumeFee();
        }
        MerchantMenber menber = new MerchantMenber();
        menber.setUsableGiveFee(usableGiveFee);
        menber.setUsableRechargeFee(usableRechargeFee);
        Double comsumeMoney = merchantMenber.getComsumeMoney() == null ? 0d : merchantMenber.getComsumeMoney();// 之前会员的消费金额
        menber.setComsumeMoney(StringUtil.bigDecimal(memberScanPayDTO.getConsumeFee() + comsumeMoney));// 现在的会员消费金额
        Double totalGiveFee = merchantMenber.getTotalGiveFee() == null ? 0d : merchantMenber.getTotalGiveFee();
        totalGiveFee = totalGiveFee + merchantMenberComsume.getReturnMoney();// 赠送总余额
        menber.setTotalGiveFee(totalGiveFee);
        // 赠送总可用余额
        menber.setUsableGiveFee(usableGiveFee + merchantMenberComsume.getReturnMoney());
        menber.setId(merchantMenber.getId());
        // 修改会员表余额
        merchantMenberMapper.updateMerchantMenber(menber);
        String orderNumber = "XF700" + StringUtil.getBillno();
        merchantMenberComsume = merchantMenberComsume.eval(orderNumber, merchantMenberComsume.getGiveMoney(), memberScanPayDTO, merchantMenber);

        merchantMenberComsumeMapper.saveMerchantMenberComsume(merchantMenberComsume);

        MemberOrder memberOrder = new MemberOrder();
        memberOrder.setRemark(memberScanPayDTO.getRemark());
        // 订单号
        memberOrder.setMerchantCode(memberScanPayDTO.getMerchantCode());
        memberOrder.setMerchantName(merchantMenber.getMerchantName());
        memberOrder.setStoreId(memberScanPayDTO.getStoreId());
        memberOrder.setStoreName(merchantMenber.getStoreName());
        memberOrder.setOrderNumber(orderNumber);
        memberOrder.setMemberCode(memberScanPayDTO.getAuthCode());
        Date date = new Date();
        memberOrder.setCreateDt(date);
        memberOrder.setOrderFee(memberScanPayDTO.getConsumeFee() + "");// 订单金额
        memberOrder.setNickName(merchantMenber.getNickName());
        memberOrder.setOrderType("0");
        memberOrder.setOrderStatus("1");
        memberOrder.setStaffCode(memberScanPayDTO.getUserId());
        memberOrder.setStaffName(memberScanPayDTO.getUserName());
        memberOrderService.saveMemberOrder(memberOrder);
        vo.setConsumeFee(memberScanPayDTO.getConsumeFee() + "");
        vo.setStoreName(memberScanPayDTO.getStoreName());
        vo.setCreateDt(date);
        vo.setLoginName(memberScanPayDTO.getUserName());
        try {
            menber.setCardNo(merchantMenber.getCardNo());
            menber.setMerchantCode(merchantMenber.getMerchantCode());
            menber.setOpenid(merchantMenber.getOpenid());
            merchantMenberService.sendMenberBalanceChangeNotice(menber,Double.valueOf(vo.getConsumeFee()),"2");
        }catch (Exception e){
            e.printStackTrace();
        }
        vo.setOrderNumber(orderNumber);
        return vo;
    }


    /**
     * 主扫会员充值参数校验
     *
     * @param memberScanPayDTO
     */
    private MerchantMenber checkMemberScanPayParamsMap(MemberScanPayDTO memberScanPayDTO) {
        Optional.ofNullable(memberScanPayDTO.getMemberCode()).orElseThrow(() -> new MsgException("无授权码"));
        Optional.ofNullable(memberScanPayDTO.getUserId()).orElseThrow(() -> new MsgException("无用户ID"));
        Optional.ofNullable(memberScanPayDTO.getMerchantCode()).orElseThrow(() -> new MsgException("无商户编码"));
        Optional.ofNullable(memberScanPayDTO.getStoreId()).orElseThrow(() -> new MsgException("无店铺ID"));
        Optional.ofNullable(memberScanPayDTO.getConsumeFee()).orElseThrow(() -> new MsgException("无消费金额"));
        Optional.ofNullable(memberScanPayDTO.getAuthCode()).orElseThrow(() -> new MsgException("无会员编码"));
        UserApp userApp = new UserApp();
        userApp.setUserId(Long.valueOf(memberScanPayDTO.getUserId()));
        userApp = userAppMapper.selectOne(new QueryWrapper<>(userApp));
        memberScanPayDTO.setUserName(userApp.getUserName());
        QueryWrapper<MerchantMenber> menberWrapper = new QueryWrapper<MerchantMenber>()
                .eq("memberCode", memberScanPayDTO.getAuthCode()).eq("storeId", memberScanPayDTO.getStoreId());
        MerchantMenber m = merchantMenberMapper.selectOne(menberWrapper);
        Optional.ofNullable(m).orElseThrow(() -> new MsgException("不属于当前门店会员"));
        MerchantStore merchantStore = new MerchantStore();
        merchantStore.setStoreId(memberScanPayDTO.getStoreId());
        merchantStore.setMerchantCode(memberScanPayDTO.getMerchantCode());
        merchantStore = merchantStoreMapper.selectOne(new QueryWrapper<>(merchantStore));
        if ("2".equals(merchantStore.getStatus())) {
            MsgException.throwException("当前店铺被禁用");
        }
        if (!"VIP".equalsIgnoreCase(memberScanPayDTO.getAuthCode().substring(0, 3))) {
            MsgException.throwException("会员码不匹配");
        }
        memberScanPayDTO.setStoreName(merchantStore.getStoreName());
        QueryWrapper<MerchantBaseInfo> infoWrapper = new QueryWrapper<MerchantBaseInfo>()
                .eq("merchantCode", memberScanPayDTO.getMerchantCode());
        MerchantBaseInfo merchant = merchantBaseInfoService.getOne(infoWrapper);
        Optional.ofNullable(merchant).orElseThrow(() -> new MsgException("无商家信息"));
        memberScanPayDTO.setMerchantName(merchant.getAlias());
        MerchantChannelStatus channelStatus = merchantChannelStatusService.getValidData(memberScanPayDTO.getMerchantCode());
        if (channelStatus == null) {
            MsgException.throwException("无进件信息");
        }
        if (!channelStatus.isPayment()) {
            MsgException.throwException("当前商家进件状态无法付款");
        }
        memberScanPayDTO.setAisleSwitch(String.valueOf(channelStatus.getChannel()));
        checkCardBalance(m,memberScanPayDTO.getConsumeFee());
        return m;
    }

    private void checkCardBalance(MerchantMenber m,Double consumeFee) {
        Double usableRechargeFee = m.getUsableRechargeFee() == null ? 0d : m.getUsableRechargeFee();// 可用充值金额
        usableRechargeFee = StringUtil.bigDecimal(usableRechargeFee);
        Double usableGiveFee = m.getUsableGiveFee() == null ? 0d : m.getUsableGiveFee();// 可用的赠送金额
        usableGiveFee = StringUtil.bigDecimal(usableGiveFee);
        Double count = usableGiveFee + usableRechargeFee;
        if (consumeFee > count) {
            MsgException.throwException("会员余额不足，请充值");
        }
    }


    private Result<Object> scanPay(JSONObject params, MerchantOrder order) {
        log.info("======================>请求返回参数，解析成功后返回：{}", params);
        Map<String, Object> result = new HashMap<>();
        if (ResultCode.FAIL.code() == params.getInteger("code")) {
            return ResultGenerator.genFailResult(params.getString("msg"), result);
        }
        result.put("data", order);
        if (ResultCode.TRANSUNKNOW.code() == params.getInteger("code")) {
            String payStatus = StringUtil.isNotEmpty(params.getString("payStatus")) ? params.getString("payStatus") : "7";
            order.setStatus(payStatus);
            this.baseMapper.updateById(order);
            result.put("orderNumber", order.getOrderNumber());
            return ResultGenerator.genTransunKonwResult("等待支付中...", result);
        }
        order.setStatus(params.getString("payStatus"));
        String mercUserId = params.getString("mercUserId");
        if (ResultCode.SUCCESS.code() == params.getInteger("code")) {
            String channelOrderNo = params.getString("channelOrderNo");
            String transNo = params.getString("transNo");
            Date payTime = params.getDate("payTime");
            order.setMercUserId(mercUserId);
            order.setTransDt(payTime);
            order.setThirdTransNo(channelOrderNo);
            order.setTransNo(transNo);
            order.setStatus("1");

            try {
                MerchantBaseInfo merchantBaseInfo = merchantBaseInfoService.getMerchantBaseInfoByMerchantCode(order.getMerchantCode());
                //校验该商户是否有效
//                userAssessService.checkUserValid(merchantBaseInfo);
                MerchantBaseInfo.setFirstAndLastTradeTime(merchantBaseInfo,payTime);
                merchantBaseInfoService.updateById(merchantBaseInfo);
            } catch (Exception e) {
                e.printStackTrace();
            }

            // 添加分润记录 主扫
            try {
                merchantProfitService.createOrderProfitV2(order,"1");
                log.info("【主扫支付】插入分润成功，订单号:{}",order.getOrderNumber());
            }catch (Exception e){
                log.error("【主扫支付】插入分润异常，订单号:{}，异常信息:{}",order.getOrderNumber(),e.getMessage());
            }
            this.baseMapper.updateById(order);
            //添加积分记录
            //TODO 添加判断是否满足条件返积分
            executorService.execute(()->{
                setActivityMarketAmt(order,null);
                userIntegralService.bstOrderIntegralReward(order);
                userInfoService.sendPayWxTemplateMessage(order);
            });
            result.put("data", order);
            result.put("orderNumber", order.getOrderNumber());
            result.put("message", "交易成功");
            return ResultGenerator.genSuccessResult("支付成功", result);
        } else {
            return ResultGenerator.genFailResult("未知异常", result);
        }
    }

    /**
     * merchantIncome:(添加收益记录). <br/>
     *
     * 
     * @author Administrator
     * @since JDK 1.8
     */
    private void merchantIncome(MerchantOrder merchantOrder) {
        MerchantIncome merchantIncome = new MerchantIncome();
        merchantIncome.setMerchantCode(merchantOrder.getMerchantCode());
        merchantIncome.setMerchantName(merchantOrder.getMerchantName());
        merchantIncome.setStoreId(merchantOrder.getStoreId());
        merchantIncome.setStoreName(merchantOrder.getStoreName());
        merchantIncome.setDealFee(merchantOrder.getConsumeFee());
        merchantIncome.setIncomeFee(merchantOrder.getEnterFee());
        merchantIncome.setPayTypeCode(merchantOrder.getPayTypeCode());
        merchantIncome.setPayTypeName(merchantOrder.getPayTypeName());
        merchantIncome.setCreateTime(merchantOrder.getTransDt());
        merchantIncomeMapper.saveMerchantIncome(merchantIncome);
    }

    /**
     *
     * @param dto
     * @param amt
     * @param type
     * @param orderType 订单类型 5 APP扫码充值
     * @return
     */
    private MerchantOrder getMerchantOrder(MerChantOrderDTO dto, Double amt, String type,String orderType) {

        MerchantOrder merchantOrder = new MerchantOrder();
        MerchantCashPlaceStaff cashPlaceStaff = new MerchantCashPlaceStaff();
        cashPlaceStaff.setStatus(MerchantCashPlaceStaff.STATUS_ONLINE);
        if(StringUtil.isNotEmpty(dto.getUserId())){
            cashPlaceStaff.setUserId(Long.parseLong(dto.getUserId()));
            cashPlaceStaff = cashPlaceStaffService.getOne(new QueryWrapper<>(cashPlaceStaff));
        }
        merchantOrder.setStaffCode(dto.getUserId());
        merchantOrder.setStaffName(dto.getStaffName());

        if(StringUtil.isNotEmpty(dto.getDeviceNo())){
            merchantOrder.setSnNo(dto.getDeviceNo());
            merchantCashPlaceService.setOrderPlaceInfo(merchantOrder,dto.getDeviceNo());
        }
        if (cashPlaceStaff != null && StringUtil.isNotEmpty(cashPlaceStaff.getCashPlaceId())) {
            merchantOrder.setCashPlaceId(cashPlaceStaff.getCashPlaceId() + "");
        }
        merchantOrder.setOrderType(StringUtil.isNotEmpty(orderType) ? orderType : "1");
        merchantOrder.setMerchantCode(dto.getMerchantCode());
        merchantOrder.setOrderNumber(dto.getOrderNumber());
        merchantOrder.setConsumeFee(amt);
        merchantOrder.setMemberCode(dto.getMemberCode());
        merchantOrder.setMerchantName(dto.getMerchantName());
        if(dto.getChannelStatus() != null && StringUtil.isNotEmpty(dto.getChannelStatus().getMercName())){
            merchantOrder.setAlias(dto.getChannelStatus().getMercName());
        }else if(dto.getMerchantBaseInfo() != null && StringUtil.isNotEmpty(dto.getMerchantBaseInfo().getMerchantName())){
            merchantOrder.setAlias(dto.getMerchantBaseInfo().getMerchantName());
        }else{
            merchantOrder.setAlias(dto.getMerchantName());
        }
        merchantOrder.setStoreId(dto.getStoreId());
        merchantOrder.setStoreName(dto.getStoreName());
        merchantOrder.setRemark(dto.getRemark());
        merchantOrder.setAisleSwitch(dto.getAisleSwitch());
        merchantOrder.setPayTypeName(dto.getPayTypeName());
        merchantOrder.setPayTypeCode(dto.getPayTypeCode());
        merchantOrder.setRemark(dto.getRemark());
        Date date = new Date();
        merchantOrder.setStatus("5");// 待付款
        merchantOrder.setCreateDt(date);
        merchantOrder.setUpdateTime(merchantOrder.getCreateDt());
        if(!"1".equals(dto.getType())){
            BigDecimal rate = merchantRateNewService.getMchRate(dto.getMerchantCode(),dto.getPayTypeCode(), amt);
            merchantOrder.calcRateAndFee(rate);
        }
        if (StringUtil.isNotEmpty(type) && !"1".equals(dto.getType())) {
            merchantOrder.isAllowBankLarge(dto.getMerchantBaseInfo());
            merchantOrderMapper.insert(merchantOrder);
        }
        if("4".equals(dto.getAisleSwitch())){
            MerchantChannelStatus channelStatus = dto.getChannelStatus();
            if(StringUtil.isEmpty(channelStatus.getSettlementType()) || YsBusinessCodeEnum.D0.getName().equals(channelStatus.getSettlementType())){
                merchantOrder.setSettlementType(SettleTypeEnum.D0.getValue());
            }else{
                merchantOrder.setSettlementType(SettleTypeEnum.D1.getValue());
            }
        }else{
            merchantOrder.setSettlementType(SettleTypeEnum.D1.getValue());
        }
        return merchantOrder;
    }

    /**
     * 校验参数
     *
     * @param merchantOrderDTO
     */
    private void checkActivePayParamsMap(MerChantOrderDTO merchantOrderDTO) {
        Optional.ofNullable(merchantOrderDTO.getMerchantCode()).orElseThrow(() -> new MsgException("无商家编码"));
        QueryWrapper<UserApp> appWrapper = new QueryWrapper<UserApp>()
                .eq("merchantCode", merchantOrderDTO.getMerchantCode()).eq("userType", "promoter");
        UserApp userApp = userAppMapper.selectOne(appWrapper);
        Optional.ofNullable(userApp).orElseThrow(() -> new MsgException("无用户信息"));
        if ("0".equals(merchantOrderDTO.getType())) {
            Optional.ofNullable(merchantOrderDTO.getAuthCode()).orElseThrow(() -> new MsgException("无支付码信息"));
            String authCode = merchantOrderDTO.getAuthCode();
            if(authCode.contains(":")){
                authCode = authCode.substring(0,authCode.indexOf(":"));
                merchantOrderDTO.setAuthCode(authCode);
            }
            if(StringUtil.isNotEmpty(merchantOrderDTO.getMemberCode()) && merchantOrderDTO.getMemberCode().contains(":")){
                String memberCode  = merchantOrderDTO.getMemberCode().substring(0,merchantOrderDTO.getMemberCode().indexOf(":"));
                merchantOrderDTO.setMemberCode(memberCode);
            }
        }else{
            String authCode = merchantOrderDTO.getAuthCode();
            if(StringUtil.isNotEmpty(authCode) && "7".equals(authCode.substring(0,1))){
                //会员卡支付
                merchantOrderDTO.setType("3");
                MerchantMemberCode code = merchantMemberCodeService.getByCode(authCode);
                MsgException.checkNull(code,"会员码有误！");
                Date now = DateUtils.currentDate();
                Date startTime = code.getStartTime();
                Date endTime = code.getEndTime();
                if(now.compareTo(startTime) < 0 || now.compareTo(endTime) > 0){
                    MsgException.throwException("该会员码已过期，请重新生成！");
                }
                if(!code.getMerchantCode().equals(userApp.getMerchantCode())){
                    MsgException.throwException("当前会员码不属于该门店！");
                }
                merchantOrderDTO.setMercMenberCode(code);
            }
        }
        // Optional.ofNullable(merchantOrderDTO.getConsumeFee()).orElseThrow(()-> new MsgException("无交易金额"));
        MerchantChannelStatus channel = merchantChannelStatusService.getValidData(merchantOrderDTO.getMerchantCode());
        Optional.ofNullable(channel).orElseThrow(() -> new MsgException("未获取到商户进件信息，请先提交商户信息"));

        MsgException.check("7".equals(channel.getStatus()),"实时到账审核中，请耐心等待或者联系客服！");
        MsgException.check(!channel.isPayment(),"当前进件状态未通过，请耐心等待或联系客服！");

        merchantOrderDTO.setChannelNo(channel.getMerchantId());

        merchantOrderDTO.setChannelStatus(channel);

        Optional.ofNullable(merchantOrderDTO.getChannelNo()).orElseThrow(() -> new MsgException("无商户编号"));
        MerchantBaseInfo merchant = merchantOrderDTO.getMerchantBaseInfo();
        if(merchant == null){
            QueryWrapper<MerchantBaseInfo> infoWrapper = new QueryWrapper<MerchantBaseInfo>()
                    .eq("merchantCode", merchantOrderDTO.getMerchantCode());
            merchant = merchantBaseInfoService.getOne(infoWrapper);
        }

        Optional.ofNullable(merchant).orElseThrow(() -> new MsgException("无商户信息"));
        merchantOrderDTO.setMerchantName(merchant.getAlias());

        if(StringUtil.isEmpty(merchantOrderDTO.getUserId())){
            if ((userApp.getUserId() + "").equals(merchantOrderDTO.getUserId())) {
                merchantOrderDTO.setStaffName(userApp.getUserName());
            }
        }
        MerchantStore queryStore = new MerchantStore();
        queryStore.setMerchantCode(merchantOrderDTO.getMerchantCode());
        List<MerchantStore> queryMerchantStoreList = merchantStoreMapper.queryMerchantStoreList(queryStore);// 查询店铺信息
        if (queryMerchantStoreList.isEmpty()) {
            throw new MsgException("无店铺信息");
        }
        MerchantStore store = queryMerchantStoreList.get(0);
        if ("2".equals(store.getStatus())) {
            throw new MsgException("当前店铺被禁用");
        }
        merchantOrderDTO.setStoreName(store.getStoreName());
        merchantOrderDTO.setStoreId(store.getStoreId());
        if(!"3".equals(merchantOrderDTO.getType())){
            setPayTypeCodeOrderNumber(merchantOrderDTO, channel);
        }
        merchantOrderDTO.setMerchantBaseInfo(merchant);
    }

    private void setPayTypeCodeOrderNumber(MerChantOrderDTO merchantOrderDTO, MerchantChannelStatus channelStatus) {

        if (StringUtil.isNotEmpty(merchantOrderDTO.getAuthCode())) {
            String payType = merchantOrderDTO.getAuthCode().substring(0, 1);// 判断收款码
            String orderPrefix = "";
            switch (payType) {
                case "1":
                    //随行付微信
                    if (channelStatus.getChannel() == 1) {
                        orderPrefix = "SXF_W_";
                        merchantOrderDTO.setAisleSwitch("2");
                        merchantOrderDTO.setPayTypeCode("sxfPay1");
                        merchantOrderDTO.setPayTypeName("随行微信支付");
                    } else if (channelStatus.getChannel() == 3) {
                        orderPrefix = "RYX_W_";
                        merchantOrderDTO.setAisleSwitch("3");
                        merchantOrderDTO.setPayTypeCode(Constant.PAY_TYPE_WECHAT);
                        merchantOrderDTO.setPayTypeName(Constant.PAY_TYPE_NAME_WECHAT);
                    } else if (channelStatus.getChannel() == 4) {
                        orderPrefix = "YS_W_";
                        merchantOrderDTO.setAisleSwitch("4");
                        merchantOrderDTO.setPayTypeCode(Constant.PAY_TYPE_WECHAT);
                        merchantOrderDTO.setPayTypeName(Constant.PAY_TYPE_NAME_WECHAT);
                    }
                    break;
                case "2":
                    //随行付支付宝
                    if (channelStatus.getChannel() == 1) {
                        orderPrefix = "SXF_Z_";
                        merchantOrderDTO.setAisleSwitch("2");
                        merchantOrderDTO.setPayTypeCode("sxfPay0");
                        merchantOrderDTO.setPayTypeName("随行支付宝支付");
                    } else if (channelStatus.getChannel() == 3) {
                        orderPrefix = "RYX_Z_";
                        merchantOrderDTO.setAisleSwitch("3");
                        merchantOrderDTO.setPayTypeCode(Constant.PAY_TYPE_ALIPAY);
                        merchantOrderDTO.setPayTypeName(Constant.PAY_TYPE_NAME_ALIPAY);
                    } else if (channelStatus.getChannel() == 4) {
                        orderPrefix = "YS_Z_";
                        merchantOrderDTO.setAisleSwitch("4");
                        merchantOrderDTO.setPayTypeCode(Constant.PAY_TYPE_ALIPAY);
                        merchantOrderDTO.setPayTypeName(Constant.PAY_TYPE_NAME_ALIPAY);
                    }
                    break;
                case "6":
                    if (channelStatus.getChannel() == 1) {
                        orderPrefix = "SXF_Y_";
                        merchantOrderDTO.setAisleSwitch("2");
                        merchantOrderDTO.setPayTypeCode("sxfPay2");
                        merchantOrderDTO.setPayTypeName("随行云闪付支付");
                    } else if (channelStatus.getChannel() == 3) {
                        orderPrefix = "RYX_Y_";
                        merchantOrderDTO.setAisleSwitch("3");
                        merchantOrderDTO.setPayTypeCode(Constant.PAY_TYPE_YSFPAY);
                        merchantOrderDTO.setPayTypeName(Constant.PAY_TYPE_NAME_YSFPAY);
                    } else if (channelStatus.getChannel() == 4) {
                        orderPrefix = "YS_Y_";
                        merchantOrderDTO.setAisleSwitch("4");
                        merchantOrderDTO.setPayTypeCode(Constant.PAY_TYPE_YSFPAY);
                        merchantOrderDTO.setPayTypeName(Constant.PAY_TYPE_NAME_YSFPAY);
                    }
                    break;
                default:
                    throw new MsgException("请扫微信、支付宝或云闪付的付款码！");
            }
            String orderNumber = orderPrefix + StringUtil.getBillno();
            merchantOrderDTO.setOrderNumber(orderNumber);
        } else {
            String orderNumber = "HYCZ_" + StringUtil.getBillno();
            merchantOrderDTO.setOrderNumber(orderNumber);
        }
    }

    /**
     * 订单退款
     *
     * @param orderNumber 退款订单号
     * @param refundReason 退款原因
     * @param type 退款类型
     * @return
     */
    @Override
    public void returnOrder(String orderNumber,String refundReason,String type, String noticeCode) {

        // 更新通知的处理状态
        if (StringUtil.isNotEmpty(noticeCode)) {
            Notice queryNotice = new Notice();
            queryNotice.setNoticeCode(noticeCode);
            List<Notice> queryNoticeList = noticeService.queryNoticeList(queryNotice);
            if (queryNoticeList != null && queryNoticeList.size() > 0) {
                queryNotice = queryNoticeList.get(0);
                queryNotice.setIsDeal(1);
                queryNotice.setIsApply(1);
                noticeService.updateNotice(queryNotice);
            }
        }

        MerchantOrderVO order = checkRefundOrderParams(orderNumber);
        order.setRemark(refundReason);
        MerchantChannelStatus channel = null;
        if("2".equals(order.getAisleSwitch())){
            channel = merchantChannelStatusService.getByMerchantCode(order.getMerchantCode(), 1);
        }else{
            channel = merchantChannelStatusService.getByMerchantCode(order.getMerchantCode(), Integer.valueOf(order.getAisleSwitch()));
        }
        MsgException.checkNull(channel,"订单通道获取异常");
        MsgException.check("7".equals(channel.getStatus()),"实时到账审核中，请耐心等待或者联系客服！");
        MsgException.check(!channel.isPayment(),"当前进件状态未通过，请耐心等待或联系客服！");

        Map<String, Object> resultMap = new HashMap<>();
        MerchantRefundOrder refundOrder = new MerchantRefundOrder();
        if (channel.getChannel() == 1) {
            resultMap = sxfPayService.refundPay(order, channel.getMerchantId());
        } else if (channel.getChannel() == 2) {
            MsgException.throwException("通道已关闭！");
        } else if (channel.getChannel() == 3) {
            resultMap = ryxPayService.refundPay(order, channel.getMerchantId());
        } else if (channel.getChannel() == 4) {
            resultMap = ysPayOldService.refundPay(order, channel.getMerchantId());
        }else {
            MsgException.throwException("未知通道！");
        }
        if (ResultCode.SUCCESS.code() != (Integer) resultMap.get("code")) {
            throw new MsgException(resultMap.get("msg") + "");
        }
        MerchantOrder update = new MerchantOrder();
        if(StringUtil.isNotEmpty(order.getMarketAmt()) && order.getMarketAmt().doubleValue() > 0){
            update.setId(order.getId());
            update.setMarketAmt(BigDecimal.ZERO);
        }
        update.setRefundAmt(BigDecimal.valueOf(order.getConsumeFee()));
        merchantOrderMapper.updateById(update);
        refundOrder.convert(order, resultMap, channel.getMerchantId());
        order.setId(null);
        order.setUpdateTime(new Date());
        order.setStatus("2");
        order.setMarketAmt(BigDecimal.ZERO);
        order.setRefundAmt(BigDecimal.valueOf(order.getConsumeFee()));
        merchantOrderMapper.insert(order);
        realFansService.removeProfit(order.getOrderNumber());
        merchantRefundOrderMapper.insert(refundOrder);
        if("app".equals(type)){
            //向小程序后台推送退款消息
            String url = "https://shop.shouyinbei.net/addons/we7_wmall/payment/refund/notify.php";
            JSONObject params = new JSONObject();
            params.put("orderNumber",orderNumber);
            try {
                String result = HttpUtil.doPostJson(url, params.toJSONString());
                log.info("================>【app退款】消息通知结果:{}<================",result);
            } catch (Exception e) {
                e.printStackTrace();
                log.info("================>【app退款】消息通知异常，异常信息:{}<================",e.getMessage());
            }
        }else{
            pushService.pushMsg(String.valueOf(order.getUserId()), PushService.REFUND_ORDER);
        }
    }

    @Override
    public void apiReturnOrderV2(String orderNumber, String refundReason, String type, String noticeCode, String payPassword) {
        if (StringUtils.isEmpty(payPassword)) {
            throw new MsgException("缺少支付密码");
        }

        UserApp userApp = userAppService.queryUserAppByToken();
        UserInfo userInfo = new UserInfo().setId(userApp.getUserId());
        userInfo = userInfoService.getOne(new QueryWrapper<>(userInfo));

        String psdMd5 = SecureUtil.md5(payPassword);
        if (!psdMd5.equals(userInfo.getPayPassword())) {
            throw new MsgException("支付密码错误");
        }

        returnOrder(orderNumber, refundReason, type, noticeCode);
    }

    /**
     * 检查退款订单参数
     *
     * @param orderNumber
     * @return
     */
    private MerchantOrderVO checkRefundOrderParams(String orderNumber) {
        MerchantOrderVO queryMerchantOrder = (MerchantOrderVO) new MerchantOrderVO().setOrderNumber(orderNumber);
        List<MerchantOrderVO> queryMerchantOrderList = merchantOrderVOMapper.selectList(new QueryWrapper<>(queryMerchantOrder));
        if (queryMerchantOrderList.isEmpty()) {
            MsgException.throwException("该订单不存在");
        }
        queryMerchantOrder = queryMerchantOrderList.get(0);

        UserApp queryUserApp = new UserApp();
        queryUserApp.setMerchantCode(queryMerchantOrder.getMerchantCode());
        queryUserApp.setUserType("promoter");
        List<UserApp> queryUserAppList = userAppMapper.queryUserAppList(queryUserApp);
        if (queryUserAppList.isEmpty()) {
            MsgException.throwException("无商户信息");
        }
        queryUserApp = queryUserAppList.get(0);

        QueryWrapper<MerchantBaseInfo> merchantQuery = new QueryWrapper<MerchantBaseInfo>().eq("merchantCode", queryMerchantOrder.getMerchantCode());
        MerchantBaseInfo merchantInfo = merchantBaseInfoService.getOne(merchantQuery);
        if (merchantInfo != null) {
            queryMerchantOrder.setAlias(merchantInfo.getAlias());
        }

        QueryWrapper<MerchantRefundOrder> queryWrapper = new QueryWrapper<MerchantRefundOrder>()
                .eq("orderNumber", orderNumber);
        MerchantRefundOrder one = merchantRefundOrderMapper.selectOne(queryWrapper);
        MsgException.check(one != null, "订单已退款，请勿重复操作！");
        queryMerchantOrder.setUserId(queryUserApp.getUserId().intValue());
        return queryMerchantOrder;
    }

    /**
     * 订单补单操作
     *
     * @param id
     * @return
     */
    @Override
    public Result suppleOrder(Integer id) {
        JSONObject object = checkSupperOrderParams(id);
        MerchantOrder order = object.getObject("order", MerchantOrder.class);
        MerchantChannelStatus channel = object.getObject("channel", MerchantChannelStatus.class);
        //随行付
        if (channel.getChannel() == 1) {
            JSONObject result = sxfPayService.tradeQuery(order, channel.getMerchantId());
            return updateOrderStatus(result, order);
            //乐刷
        } else if (channel.getChannel() == 2) {
            MsgException.throwException("当前通道已关闭");
            //瑞银信
        } else if (channel.getChannel() == 3) {
            JSONObject result = ryxPayService.tradeQuery(order, channel.getMerchantId());
            return updateOrderStatus(result, order);
        } else if (channel.getChannel() == 4) {
            JSONObject result = ysPayOldService.tradeQuery(order, channel.getMerchantId());
            return updateOrderStatus(result, order);
        }
        return ResultGenerator.genSuccessResult("补单成功", null);
    }

    /**
     * 解析返回参数修改状态
     *
     * @param result
     * @param order
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.NOT_SUPPORTED)
    public Result updateOrderStatus(JSONObject result, MerchantOrder order) {
        log.info("【订单状态更新】订单号：{},上游返回的支付结果：{}",order.getOrderNumber(),result.toString());
        Integer code = result.getInteger("code");
        if (ResultCode.SUCCESS.code() != code) {
            return ResultGenerator.genFailResult(result.getString("msg"));
        }
        if (order.getStatus().equals(result.getString("payStatus"))) {
            return ResultGenerator.genFailResult("订单状态一致,无需补单",null);
        }
        String status = result.getString("payStatus");
        order.setStatus(status);
        if ("1".equals(result.getString("payStatus"))) {
            String channelOrderNo = result.getString("channelOrderNo");
            Date payTime = result.getDate("payTime");
            String transNo = result.getString("transNo");
            order.setTransNo(transNo);
            order.setTransDt(payTime);
            order.setThirdTransNo(channelOrderNo);
            BigDecimal enterFee = new BigDecimal(String.valueOf(order.getEnterFee()));
            if(order.getOrderNumber().contains("YS")){
                BigDecimal tradeAmt = new BigDecimal(String.valueOf(order.getConsumeFee()));
                String payee_fee = StringUtil.isEmpty(result.getString("fee")) ? "0" : result.getString("fee");  //收款方手续费
                enterFee = tradeAmt.subtract(new BigDecimal(payee_fee)).setScale(2,BigDecimal.ROUND_DOWN);
                //提现手续费
                BigDecimal wFee = tradeAmt.multiply(new BigDecimal("0.001"));
                //提现手续费不足0.1元 按照0.1元扣
                if(wFee.doubleValue() < 0.1d ){
                    enterFee = enterFee.subtract(new BigDecimal("0.1"));
                }else{
                    enterFee = enterFee.subtract(wFee).setScale(2,BigDecimal.ROUND_DOWN);
                }
            }
            order.setEnterFee(enterFee.doubleValue());
            order.setThirdTransNo(channelOrderNo);
            updateOrderAndCreateProfit(order);
            return ResultGenerator.genSuccessResult("补单成功！", null);
        }
        return ResultGenerator.genFailResult("通道返回订单已关闭或支付失败，无需补单！");
    }

    /**
     * 检查订单补单参数
     *
     * @param id
     */
    private JSONObject checkSupperOrderParams(Integer id) {
        JSONObject params = new JSONObject(2);
        MsgException.checkNull(id, "无订单ID");
        MerchantOrder order = this.getById(id);
        MsgException.checkNull(order, "无订单数据");
        MsgException.check(!"5".equals(order.getStatus()) && !"7".equals(order.getStatus()), "只能操作“待付款”的订单");
        String aisleSwitch = order.getAisleSwitch();
        MerchantChannelStatus channel;
        switch (aisleSwitch){
            case "2":
                channel = merchantChannelStatusService.getByMerchantCode(order.getMerchantCode(),1);
                break;
            default:
                channel = merchantChannelStatusService.getByMerchantCode(order.getMerchantCode(),Integer.valueOf(aisleSwitch));
                break;
        }
        MsgException.checkNull(channel, "未获取商户进件信息，请先提交商户信息");
        MsgException.check(!channel.isPayment(), "当前通道状态异常");
        params.put("order", order);
        params.put("channel", channel);
        return params;
    }


    @Override
    public Page<MerchantOrder> pageInfo(Page<MerchantOrder> page, MerchantOrder query) {
        return baseMapper.pageInfo(page, query);
    }

    @Override
    public void readCSV(String srcPath) {
        log.info("====================>【瑞银信】读取csv文件信息开始<====================");
        try (CSVReader csvReader = new CSVReaderBuilder(new BufferedReader(new InputStreamReader(new FileInputStream(new File(srcPath)), "GBK"))).build()) {
            csvReader.readNext();
            List<String[]> list = csvReader.readAll(); //此时读取的已经是第二行了
            for (String[] s : list) {
                //过滤不需要的数据
                if ("总交易笔数".equals(s[0]) || StringUtil.isEmpty(s[0])) {
                    break;
                }
                String merchantNo = s[1];
                String mercOrderNo = s[3];
                if(!mercOrderNo.contains("RYX")){
                    MerchantOrder order = new MerchantOrder();
                    MerchantPlugin pluginQuery = new MerchantPlugin().setPluginId(merchantNo);
                    MerchantPlugin plugin = merchantPluginMapper.selectOne(new QueryWrapper<>(pluginQuery));
                    if (plugin == null) {
                        continue;
                    }
                    MerchantBaseInfo baseInfo = new MerchantBaseInfo().setUserId(String.valueOf(plugin.getUserId()));
                    MerchantBaseInfo merchant = merchantBaseInfoService.getOne(new QueryWrapper<>(baseInfo));
                    if (merchant == null) {
                        continue;
                    }
                    MerchantStore storeQuery = new MerchantStore().setMerchantCode(merchant.getMerchantCode());
                    MerchantStore store = merchantStoreMapper.selectOne(new QueryWrapper<>(storeQuery));
                    if (store == null) {
                        continue;
                    }
                    QueryWrapper<UserApp> queryWrapper = new QueryWrapper<UserApp>().eq("userId", merchant.getUserId());
                    UserApp app = userAppMapper.selectOne(queryWrapper);
                    if (app == null) {
                        continue;
                    }

                    order.setOrderNumber(s[3]);
                    order.setOrderType("99");
                    order.setMerchantCode(merchant.getMerchantCode());
                    order.setMerchantName(merchant.getAlias());
                    String payTypeCode = "";
                    String payTypeName = "";
                    if ("WXZF".equals(s[5])) {
                        payTypeCode = "wechatPay";
                        payTypeName = "微信支付";
                    } else if ("ZFBZF".equals(s[5])) {
                        payTypeCode = "aliPay";
                        payTypeName = "支付宝支付";
                    } else if ("UPZF".equals(s[5])) {
                        payTypeCode = "bank";
                        payTypeName = "银联支付";
                    } else {
                        payTypeCode = "未知";
                        payTypeName = "未知";
                    }
                    order.setPayTypeCode(payTypeCode);
                    order.setPayTypeName(payTypeName);
                    order.setStoreId(store.getStoreId());
                    order.setStoreName(store.getStoreName());
                    BigDecimal consumeFee = new BigDecimal(s[10]).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
                    order.setConsumeFee(consumeFee.doubleValue());
                    order.setTransNo(s[4]);
                    order.setCreateDt(new Date());
                    String payTime = s[8] + s[9];
                    order.setTransDt(DateUtils.parse(payTime, "yyyyMMddHHmmss"));
                    order.setStatus("1");
                    order.setEnterFee(new BigDecimal(s[12]).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP).doubleValue());
                    order.setAisleSwitch("3");
                    BigDecimal mercRate = new BigDecimal(s[13]).multiply(new BigDecimal(10000));
                    order.setRate(mercRate);

                    order.setMarketAmt(BigDecimal.ZERO);
                    //判断交易金额是否超出限制
                    if (consumeFee.compareTo(new BigDecimal(300)) <= 0) {
                        //判断当前商户是否报名插件活动
                        log.info("====================>【瑞银信】判断商户是否参加了插件活动<======================");
                        QueryWrapper<ActivityEnroll> query = new QueryWrapper<ActivityEnroll>()
                                .eq("merchantCode", merchant.getMerchantCode()).eq("actType", "3").eq("status", "1")
                                .orderByDesc("createTime").last("limit 1");
                        List<ActivityEnroll> enrollList = activityEnrollMapper.selectList(query);
                        if (!enrollList.isEmpty()) {
                            log.info("====================>【瑞银信】userId为：{}的商户参加了插件活动,当前订单的交易金额：{}<======================", app.getUserId(), consumeFee);
                            //判断活动时间是否过期
                            OfficialActivity byId = officialActivityMapper.selectById(enrollList.get(0).getActId());
                            if (byId != null) {
                                if ("2".equals(byId.getStatus())) {
                                    Integer startTimeValue = Integer.parseInt(DateUtils.formatDateDefault(byId.getStartTime(), "yyyyMMdd"));
                                    Integer endTimeValue = Integer.parseInt(DateUtils.formatDateDefault(byId.getEndTime(), "yyyyMMdd"));
                                    Integer nowDate = Integer.parseInt(DateUtils.formatDateDefault(new Date(), "yyyyMMdd"));
                                    if (nowDate >= startTimeValue && nowDate <= endTimeValue) {
                                        Integer mercFee = mercRate.intValue() - 25;
                                        if (mercFee > 0) {
                                            BigDecimal divide = new BigDecimal(mercFee).divide(new BigDecimal(10000));
                                            order.setMarketAmt(divide.multiply(consumeFee));

                                            MerchantMarket market = new MerchantMarket();
                                            market.setUserId(app.getParentId());
                                            market.setUserName(app.getUserName());
                                            //上级获得奖励金个数
                                            BigDecimal decimal = consumeFee.multiply(new BigDecimal("0.0025")).setScale(4, BigDecimal.ROUND_HALF_UP);
                                            market.setMarketAmt(decimal);
                                            market.setSource("3");
                                            market.setCreateTime(new Date());
                                            merchantMarketMapper.insert(market);
                                        }
                                    } else {
                                        log.info("====================>【瑞银信】当前插件活动适用时间不在活动范围内，活动开始时间：{}，结束时间：{}，当前时间：{}<======================", startTimeValue, endTimeValue, nowDate);
                                    }
                                } else {
                                    log.info("====================>【瑞银信】当前插件活动已过期或下架<======================");
                                }
                            } else {
                                log.info("=====================>【瑞银信】插件活动配置出错<==================");
                            }
                        }
                    } else {
                        log.info("=====================>【瑞银信】当前订单金额：{}超出300元限制，取消商户和服务商的返利<==================", consumeFee);
                    }
                    merchantOrderMapper.insert(order);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<Map<String, Object>> getCouponList(String orderNumber) {
        MerchantOrder merchantOrder = new MerchantOrder().setOrderNumber(orderNumber).setStatus("1");
        MerchantOrder one = getOne(new QueryWrapper<>(merchantOrder));
        if (one == null) {
            throw new MsgException("订单不存在");
        }

        if ("10".equals(one.getOrderType())) {
            return merchantOrderVOMapper.getOnlineCouponList(orderNumber);
        } else {
            return merchantOrderVOMapper.getOfflineCouponList(orderNumber);
        }
    }

    /**
     * @description:订单列表根据查询条件统计数据
     * @date: 2021/8/5 16:58
     * @param map:
     * @return java.util.Map<java.lang.String,java.lang.Object>
     */
    @Override
    public Map<String, Object> getOrderCountData(Map<String, Object> map) {
        return baseMapper.getOrderCountData(map);
    }

    /**
     * @description:更改订单支付状态
     * @date: 2021/8/19 18:50
     * @param order:
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.NOT_SUPPORTED)
    public void updateOrderAndCreateProfit(MerchantOrder order) {
        Integer row = queueDataService.newQueueData(order.getOrderNumber());
        if(row > 0){
            // 活动营销反积分
            setActivityMarketAmt(order,null);
            // 更新订单状态
            updateMerchantOrder(order);
            // 推送消息
            executorService.execute(() -> notifyMessageService.sendPayMessage(order,"pay",null,null));
            // 到账通知和微信订单推送
            sendPayCallBackArrival(order);
            // 更新临时码支付状态
            updateMerchantMoveRecords(order);
            // 发送mqtt消息
            rabbitTemplate.convertAndSend("payCallback",JSON.toJSONString(order));
            // 更新商品兑换状态
            updateGoodExchange(order);
            //订单分账
            merchantOrderSplitService.checkMerchantOrderSplit(order);
            // 添加判断BST是否满足条件返积分
            userIntegralService.bstOrderIntegralReward(order);

            try {
                MerchantBaseInfo mbi = merchantBaseInfoService.getMerchantBaseInfoByMerchantCode(order.getMerchantCode());
                //校验该商户是否有效
//                userAssessService.checkUserValid(mbi);
                MerchantBaseInfo.setFirstAndLastTradeTime(mbi, order.getTransDt());
                merchantBaseInfoService.updateById(mbi);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取订单分润数据
     * @param order
     * @return
     */
//    @Override
//    public JSONObject getOrderProfitData(MerchantOrder order) {
//        JSONObject result = new JSONObject(2);
//        if(!"1".equals(order.getOrderType())){
//            Fans fans = realFansService.getFansProfit(order);
//            if(fans != null){
//                result.put("fansProfitData",fans);
//            }
//        }
//        List<MerchantProfit> shareProfitList = merchantProfitService.getOrderShareProfit(order);
//        if(shareProfitList != null && !shareProfitList.isEmpty()){
//            result.put("shareProfitData",shareProfitList);
//        }
//        return result;
//    }
    /**
     * @description:更新商品状态
     * @date: 2021/11/23 18:35
     * @param order:
     */
    private void updateGoodExchange(MerchantOrder order) {
        UpdateWrapper<OfficialGoodsExchange> goodsWrapper = new UpdateWrapper<>();
        goodsWrapper.eq("orderNumber",order.getOrderNumber()).set("status","1");
        officialGoodsExchangeService.update(goodsWrapper);

        UpdateWrapper<UserIntegralUse> integralWrapper = new UpdateWrapper<>();
        integralWrapper.eq("orderNumber",order.getOrderNumber()).set("status","2").set("handleTime",new Date());
        userIntegralUseService.update(integralWrapper);
    }

//    @Override
//    public void sendPayCallBackArrival(Long userId, String orderNumber, Double consumeFee) {
//        UserApp userApp = userAppService.getUserAppByUserId(userId);
//        String isVoice = "1";
//        if (!StringUtil.isEmpty(userApp.getIsVoice())) {
//            isVoice = userApp.getIsVoice();
//        }
//        String extrasparam = "3";
//        if ("0".equals(isVoice)) {
//            extrasparam = "4";
//        }
//        Notice notice = new Notice(2,98,userApp);
//        notice.setUniqueKey(orderNumber+userApp.getUserId());
//        String content = "收银呗到账" + consumeFee + "元";
//        notice.setConrtent(content);
//        noticeService.saveOrUpdate(notice);
//        // 会员充值播报
//        generalPushUtil.sendAllPlatByAlias(Lists.asList(userId), "收银呗到账通知", content, extrasparam);
//    }

    @Override
    public void sendPayCallBackArrival(MerchantOrder order) {
        MerchantBaseInfo baseInfo = merchantBaseInfoService.getMerchantBaseInfoByMerchantCode(order.getMerchantCode());
        UserApp userApp = new UserApp().setUserId(Long.valueOf(baseInfo.getUserId()));
        userApp = userAppService.queryUserApp(userApp);
        List<String> alias = userAppService.storeMemberList(order.getMerchantCode());
        String isVoice = "1";
        if (!StringUtil.isEmpty(userApp.getIsVoice())) {
            isVoice = userApp.getIsVoice();
        }
        String extrasparam = "3";
        if ("0".equals(isVoice)) {
            extrasparam = "4";
        }
        try {
            Notice notice = new Notice(2,98,userApp);
            notice.setUniqueKey(order.getOrderNumber()+userApp.getUserId());
            String content = "收银呗到账" + order.getConsumeFee() + "元";
            notice.setConrtent(content);
            noticeService.saveOrUpdate(notice);
            // 会员充值播报
            UserVoice voice = userVoiceService.getByUserId(Long.valueOf(baseInfo.getUserId()));
            if("3".equals(order.getOrderType()) || "5".equals(order.getOrderType())){
                if(UserVoice.ENABLE.equals(voice.getMemberCharge())){
                    BigDecimal coupon = order.getDiscount() == null ? BigDecimal.ZERO : BigDecimal.valueOf(order.getDiscount());
                    generalPushUtil.sendAllPlatByUserIdChargeWithCoupon(alias,BigDecimal.valueOf(order.getConsumeFee()),coupon);
                }
            }else{
                if(UserVoice.ENABLE.equals(voice.getPaySuccess())){
                    generalPushUtil.sendAllPlatByAlias(alias, "收银呗到账通知", content, extrasparam);
                }
            }
            //发送模板消息
            executorService.execute(() -> {
                try {
                    userInfoService.sendPayWxTemplateMessage(order);
                } catch (Exception e) {
                    log.error("发送模板消息失败: {}", e.getMessage());
                    e.printStackTrace();
                }
            });
            log.info("【订单到账推送】订单到账推送成功，订单号：{},订单金额:{}",order.getOrderNumber(),order.getConsumeFee());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

//    private void sendLowerPayNotifyCallback(MerchantOrder order) {
//        log.info("====================>进入下游订单支付成功推送操作<====================");
//        JSONObject notifyMap = new JSONObject();
//        notifyMap.put("msgType","01");
//        notifyMap.put("channelTradeNo",order.getThirdTransNo());
//        notifyMap.put("mercOrderNo",order.getMercOrderNo());
//        notifyMap.put("mercUserId",order.getMercUserId());
//        notifyMap.put("payAmt",order.getConsumeFee().toString());
//        notifyMap.put("payTime",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(order.getTransDt()));
//        notifyMap.put("payWay",order.getPayTypeCode().contains("0") || "aliPay".equals(order.getPayTypeCode()) ? "ZFBZF" : "WXZF");
//        notifyMap.put("orderNumber",order.getOrderNumber());
//        notifyMap.put("status","1");
//        String key = "4c8d277b0f274604af68e590cc0b3e6b";
//        MerchantBaseInfo merchant = merchantBaseInfoService.getMerchantBaseInfoByMerchantCode(order.getMerchantCode());
//        if(merchant != null && StringUtil.isNotEmpty(merchant.getMd5Key())){
//            key = merchant.getMd5Key();
//        }
//        String signStr = SignUtils.getSignContent(notifyMap) + "&key="+key;
//        log.info("下游通知签名字符串：{}",signStr);
//        String nSign = MD5Util.MD5Encode(signStr, "UTF-8");
//        notifyMap.put("sign",nSign);
//        try {
//            notifyMessageService.sendNotifyMessage(order,notifyMap);
//        } catch (Exception e) {
//            log.info("====================>进入下游推送异步通知异常，异常信息:{}<====================",e);
//        }
//    }

    /**
     *
     * @param order
     */
//    private void createOrderProfitAndFansProfit(MerchantOrder order) {
//        if(!"1".equals(order.getOrderType())){
//            realFansService.createFansProfit(order);
//        }
//        merchantProfitService.createOrderProfitV2(order);
//    }
    /**
     * @description:修改会员卡订单操作
     * @date: 2021/9/6 15:36
     * @param order:
     */
    private void updateMemberOrder(MerchantOrder order) {
        log.error("【会员充值回调】开始，订单号:{},充值金额:{}",order.getOrderNumber(),order.getConsumeFee());
        QueryWrapper<MemberOrder> queryWrapper = new QueryWrapper<MemberOrder>().eq("orderNumber",order.getOrderNumber());
        MemberOrder mOrder = memberOrderService.getOne(queryWrapper);
        if(mOrder == null){
            log.error("【会员充值回调】未获取到订单号为：{}的充值记录，回调结束",order.getOrderNumber());
            return;
        }
        if("1".equals(mOrder.getOrderStatus())){
            log.error("【会员充值回调】订单号：{}的会员充值订单不是待支付状态，回调结束",order.getOrderNumber());
            return;
        }
        mOrder.setOrderStatus("1");
        mOrder.setChannelNo(order.getTransNo());
        memberOrderService.updateById(mOrder);
        QueryWrapper<MerchantMenber> memberWrapper = new QueryWrapper<MerchantMenber>().eq("memberCode",mOrder.getMemberCode());
        MerchantMenber member = merchantMenberService.getOne(memberWrapper);
        if(member == null){
            log.error("【会员充值回调】查询会员编号：{}的会员不存在，回调结束",mOrder.getMemberCode());
            return;
        }
        MerchantMenberRecharge recharge = new MerchantMenberRecharge();
        double rechargeReturnAmt = activityRechargeService.getRechargeReturnAmt(order.getMerchantCode(), member.getStoreId(), order.getConsumeFee());
        order.setDiscount(rechargeReturnAmt);
        recharge.setGiveMoney(rechargeReturnAmt);
        recharge.setRechargeMoney(order.getConsumeFee());
        recharge.setMemberCode(member.getMemberCode());
        recharge.setMerchantCode(order.getMerchantCode());
        recharge.setMerchantName(order.getMerchantName());
        recharge.setStoreId(member.getStoreId());
        recharge.setStoreName(member.getStoreName());
        recharge.setCreateDt(new Date());
        recharge.setLogo(member.getLogo());
        recharge.setNickName(member.getNickName());
        recharge.setPhone(member.getPhone());
        recharge.setPayType(1);
        recharge.setOrderNumber(order.getOrderNumber());
        try {
            menberRechargeService.saveMerchantMenberRecharge(recharge);
            Double usableRechargeFee = member.getUsableRechargeFee() == null ? 0d : member.getUsableRechargeFee();
            member.setUsableRechargeFee(StringUtil.bigDecimal(usableRechargeFee + Double.parseDouble(mOrder.getOrderFee())));
            //当前充值总额
            Double totalGiveFee = member.getTotalGiveFee() == null ? 0d : member.getTotalGiveFee();
            member.setTotalGiveFee(StringUtil.bigDecimal(totalGiveFee + recharge.getGiveMoney()));
            Double usableGiveFee = member.getUsableGiveFee() == null ? 0d : member.getUsableGiveFee();
            member.setUsableGiveFee(StringUtil.bigDecimal(usableGiveFee + recharge.getGiveMoney()));

            Double totalRechargeFee = member.getTotalRechargeFee() == null ? 0d : member.getTotalRechargeFee();
            member.setTotalRechargeFee(StringUtil.bigDecimal(totalRechargeFee + Double.parseDouble(mOrder.getOrderFee())));
            merchantMenberService.updateMerchantMenber(member);

            try {
                //发送会员充值通知余额变动通知
                merchantMenberService.sendMenberBalanceChangeNotice(member,order.getConsumeFee(),"1");
            }catch (Exception e){
                e.printStackTrace();
            }
//            List<String> alias = userAppService.storeMemberList(order.getMerchantCode());
            // 此处的推送属于重复
//            generalPushUtil.sendAllPlatByAlias(alias, "会员充值通知", "会员充值" + order.getConsumeFee() + "元", "3");
        }catch (Exception e){
            e.printStackTrace();
            log.error("【会员充值回调】回调重复通知,订单号：{}",order.getOrderNumber());
        }
    }

    /**
     * 设置营销活动
     * @param
     */
    @Override
    public void setActivityMarketAmt(MerchantOrder order,MerchantStore store) {
        try {
            if(store == null){
                store = merchantStoreService.getStoreByMerchantCode(order.getMerchantCode());
            }
            if(store != null){
                if("1".equals(store.getIsMarket())){
                    Double consumeFee = order.getConsumeFee();
                    Double enterFee = order.getEnterFee();
                    BigDecimal fee = new BigDecimal(String.valueOf(consumeFee))
                            .subtract(new BigDecimal(String.valueOf(enterFee))).setScale(2,BigDecimal.ROUND_HALF_DOWN);
                    order.setMarketAmt(fee);
                    if(fee.doubleValue() >= 0.01){
                        MerchantBaseInfo merchant = merchantBaseInfoService.getMerchantBaseInfoByMerchantCode(order.getMerchantCode());
                        if(merchant != null){
                            userIntegralService.saveUserIntegral(order.getOrderNumber(),
                                    BigDecimal.valueOf(order.getConsumeFee()),
                                    Long.parseLong(merchant.getUserId()),"1","1",fee);
                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * @description:更新支付状态
     * @date: 2021/8/2 17:41
     * @param order:
     */
    private void updateMerchantMoveRecords(MerchantOrder order) {
        UpdateWrapper<MerchantMoveRecords> updateWrapper = new UpdateWrapper<MerchantMoveRecords>()
                .set("payNum","1")
                .eq("orderNumber",order.getOrderNumber())
                .eq("merchantCode",order.getMerchantCode());
        merchantMoveRecordsService.update(updateWrapper);
    }

    private void updateMerchantOrder(MerchantOrder order){
        if(!"0".equals(order.getStatus())){
            order.setStatus("1");
        }
        this.baseMapper.updateById(order);
        if("3".equals(order.getOrderType()) || "5".equals(order.getOrderType())){
            log.info("====================>进入会员充值回调操作，订单类型：{}<====================",order.getOrderType());
            updateMemberOrder(order);
        }
    }
    /**
     * @description:更新交易失败的订单
     * @date: 2021/8/20 10:58
     * @param order:
     * @param channelStatus:
     * @param channelMsg:
     */
    @Override
    public void updateFailOrder(MerchantOrder order, String channelStatus, String channelMsg) {
        MerchantOrder update = new MerchantOrder();
        update.setId(order.getId());
        update.setStatus("0");
        String remark = "上游支付状态:"+channelStatus + ",失败描述："+ channelMsg;
        update.setRemark(remark);
        this.baseMapper.updateById(update);
    }

    /**
     * @description:设置订单相关参数
     * @date: 2021/8/25 11:17
     * @param order:
     * @param params:
     * @param channel:
     */
    @Override
    public void constOrderPayCodeAndName(MerchantOrder order, Map<String, Object> params, MerchantChannelStatus channel) {
        if(channel == null && params.get("payWay") != null){
            if("WXZF".equalsIgnoreCase((String) params.get("payWay"))){
                if("2".equals(order.getAisleSwitch())){
                    order.setPayTypeCode("sxfPay1");
                    order.setPayTypeName("随行微信支付");
                }else{
                    order.setPayTypeCode(Constant.PAY_TYPE_WECHAT);
                    order.setPayTypeName(Constant.PAY_TYPE_NAME_WECHAT);
                }
            }else if("ZFBZF".equalsIgnoreCase((String)params.get("payWay"))){
                if("2".equals(order.getAisleSwitch())){
                    order.setPayTypeCode("sxfPay0");
                    order.setPayTypeName("随行支付宝支付");
                }else{
                    order.setPayTypeCode(Constant.PAY_TYPE_ALIPAY);
                    order.setPayTypeName(Constant.PAY_TYPE_NAME_ALIPAY);
                }
            }else if("UNIONPAY".equalsIgnoreCase((String)params.get("payWay"))){
                if("2".equals(order.getAisleSwitch())){
                    order.setPayTypeCode("sxfPay2");
                    order.setPayTypeName("随行云闪付支付");
                }else{
                    order.setPayTypeCode(Constant.PAY_TYPE_YSFPAY);
                    order.setPayTypeName(Constant.PAY_TYPE_NAME_YSFPAY);
                }
            }
            return;
        }
        order.setSettlementType(SettleTypeEnum.D1.getValue());
        String orderPrefix = "";
        switch (channel.getChannel()){
            case 1:
                order.setAisleSwitch("2");
                order.setChannelRate(SxfConstants.CHANNEL_WECHAT_ALIPAY_BANK_COST_RATE.multiply(new BigDecimal(10000)));
                BigDecimal channelFee = new BigDecimal(order.getConsumeFee().toString()).multiply(SxfConstants.CHANNEL_WECHAT_ALIPAY_BANK_COST_RATE).setScale(2,BigDecimal.ROUND_HALF_UP);
                order.setChannelFee(channelFee);
                if(params.get("payWay") == null){
                    orderPrefix = "SXF_";
                }else{
                    if("WXZF".equalsIgnoreCase((String) params.get("payWay"))){
                        orderPrefix = "SXF_W_";
                        order.setPayTypeCode("sxfPay1");
                        order.setPayTypeName("随行微信支付");
                    }else if("ZFBZF".equalsIgnoreCase((String)params.get("payWay"))){
                        orderPrefix = "SXF_Z_";
                        order.setPayTypeCode("sxfPay0");
                        order.setPayTypeName("随行支付宝支付");
                    }else if("UNIONPAY".equalsIgnoreCase((String)params.get("payWay"))){
                        orderPrefix = "SXF_Y_";
                        order.setPayTypeCode("sxfPay2");
                        order.setPayTypeName("随行云闪付支付");
                    }
                }
                break;
            case 2:
                //乐刷通道
                MsgException.throwException("当前通道已关闭");
                break;
            case 3:
                order.setAisleSwitch("3");
                order.setChannelRate(RyxConstants.CHANNEL_WECHAT_ALIPAY_COST_RATE.multiply(new BigDecimal(10000)));
                order.setChannelFee(new BigDecimal(order.getConsumeFee().toString()).multiply(RyxConstants.CHANNEL_WECHAT_ALIPAY_COST_RATE).setScale(2,BigDecimal.ROUND_HALF_UP));
                if(params.get("payWay") == null){
                    orderPrefix = "RYX_";
                }else{
                    if("WXZF".equalsIgnoreCase((String) params.get("payWay"))){
                        orderPrefix = "RYX_W_";
                        order.setPayTypeCode(Constant.PAY_TYPE_WECHAT);
                        order.setPayTypeName(Constant.PAY_TYPE_NAME_WECHAT);
                    }else if("ZFBZF".equalsIgnoreCase((String)params.get("payWay"))){
                        orderPrefix = "RYX_Z_";
                        order.setPayTypeCode(Constant.PAY_TYPE_ALIPAY);
                        order.setPayTypeName(Constant.PAY_TYPE_NAME_ALIPAY);
                    }else if("UNIONPAY".equalsIgnoreCase((String)params.get("payWay"))){
                        if(order.getConsumeFee() <= 1000.0d){
                            order.setChannelRate(RyxConstants.CHANNEL_BANK_COST_RATE.multiply(new BigDecimal(10000)));
                            order.setChannelFee(new BigDecimal(order.getConsumeFee().toString()).multiply(RyxConstants.CHANNEL_BANK_COST_RATE).setScale(2,BigDecimal.ROUND_HALF_UP));
                        }else{
                            order.setChannelRate(null);
                            order.setChannelFee(null);
                        }
                        orderPrefix = "RYX_Y_";
                        order.setPayTypeCode(Constant.PAY_TYPE_YSFPAY);
                        order.setPayTypeName(Constant.PAY_TYPE_NAME_YSFPAY);
                    }
                }
                break;
            case 4:
                order.setAisleSwitch("4");
                if(StringUtil.isEmpty(channel.getSettlementType()) || YsBusinessCodeEnum.D0.getName().equals(channel.getSettlementType())){
                    order.setSettlementType(SettleTypeEnum.D0.getValue());
                }else{
                    order.setSettlementType(SettleTypeEnum.D1.getValue());
                }
                order.setChannelRate(YsOldConstants.CHANNEL_WECHAT_ALIPAY_BANK_COST_RATE.multiply(new BigDecimal(10000)));
                order.setChannelFee(new BigDecimal(order.getConsumeFee().toString()).multiply(YsOldConstants.CHANNEL_WECHAT_ALIPAY_BANK_COST_RATE).setScale(2,BigDecimal.ROUND_HALF_UP));
                if(params.get("payWay") == null){
                    orderPrefix = "YS_";
                }else{
                    if("WXZF".equalsIgnoreCase((String) params.get("payWay"))){
                        orderPrefix = "YS_W_";
                        order.setPayTypeCode(Constant.PAY_TYPE_WECHAT);
                        order.setPayTypeName(Constant.PAY_TYPE_NAME_WECHAT);
                    }else if("ZFBZF".equalsIgnoreCase((String)params.get("payWay"))){
                        orderPrefix = "YS_Z_";
                        order.setPayTypeCode(Constant.PAY_TYPE_ALIPAY);
                        order.setPayTypeName(Constant.PAY_TYPE_NAME_ALIPAY);
                    }else if("UNIONPAY".equalsIgnoreCase((String)params.get("payWay"))){
                        if(order.getConsumeFee() > 1000.0d){
                            order.setChannelRate(YsOldConstants.CREDIT_DEBIT_CARD_BANK_RATE_LARGE.multiply(new BigDecimal(10000)));
                            order.setChannelFee(new BigDecimal(order.getConsumeFee().toString()).multiply(YsOldConstants.CREDIT_DEBIT_CARD_BANK_RATE_LARGE).setScale(2,BigDecimal.ROUND_HALF_UP));
                        }
                        orderPrefix = "YS_Y_";
                        order.setPayTypeCode(Constant.PAY_TYPE_YSFPAY);
                        order.setPayTypeName(Constant.PAY_TYPE_NAME_YSFPAY);
                    }
                }
                break;
            default:
                throw new MsgException("无效的通道");
        }
        Object orderNum = params.get("orderNum");
        if(StringUtil.isNotEmpty(orderNum)){
            orderPrefix = orderPrefix + orderNum + "_";
        }
        if(StringUtils.isEmpty(order.getOrderNumber())){
            if(StringUtil.isNotEmpty(params.get("orderNumber"))){
                order.setOrderNumber(params.get("orderNumber").toString());
            }else{
                String orderNumber = orderPrefix + StringUtil.getBillno();
                order.setOrderNumber(orderNumber);
            }
        }
    }

    /**
     * @description:获取获取订单信息
     * @date: 2021/8/31 14:54
     * @param orderNumber:
     * @return cn.pluss.platform.entity.MerchantOrder
     */
    @Override
    public MerchantOrder getLockByOrderNumber(String orderNumber) {
        return this.baseMapper.getLockByOrderNumber(orderNumber);
    }

    /**
     * @description:获取订单首页数据
     * @date: 2021/10/19 14:55
     * @return java.util.Map<java.lang.String,java.lang.Object>
     */
    @Override
    public Map<String, Object> getPlatformOrderData() {
        return this.baseMapper.getPlatformOrderData();
    }

    /**
     * @description:统计累计金额数据
     * @date: 2021/10/19 17:53
     * @return java.util.Map<java.lang.String,java.lang.Object>
     */
    @Override
    public Map<String, Object> getPlatformAmtData() {
        return this.baseMapper.getPlatformAmtData();
    }

    /**
     * 统计用户订单流水
     * @date: 2022/1/15 11:33
     * @param date:
     * @return
     */
    @Override
    public List<UserProfit> getOrderFlow(String date,Integer sort) {
        return this.baseMapper.getOrderFlow(date,sort);
    }

    @Override
    public Integer getOrderMaxSort(String date) {
        return this.baseMapper.getOrderMaxSort(date);
    }

    @Override
    public Map<String, String> getPlatformTransData() {
        return this.baseMapper.getPlatformTransData();
    }

    /**
     * 根据商户号和时间获取流水
     * @date: 2022/3/1 17:00
     * @param mercList:
     * @param date:
     * @param flag:
     * @return java.math.BigDecimal
     */
    @Override
    public BigDecimal getAreaOrderCount(List<String> mercList, String date, Integer flag) {
        return this.baseMapper.getAreaOrderCount(mercList,date,flag);
    }

    /**
     * 获取通道对账文件地址
     * @param accountDate
     * @param channel
     * @param type
     * @return
     */
    @Override
    public Result<Object> getChannelFileUrl(String accountDate, Integer channel, Integer type) {
        MsgException.checkBlank(accountDate,"日期不能为空");
        MsgException.checkNull(channel,"通道不能为空");
        MsgException.checkNull(type,"类型不能为空");
        JSONObject reqData = new JSONObject(4);
        reqData.put("account_date",accountDate);
        reqData.put("file_type",type == 1 ? "28" : "29");
        JSONObject result = ysPayOldService.getUnionAccountUrl(reqData);
        return ResultGenerator.genSuccessResult("获取成功",result.getString("url"));
    }

    @Override
    public BigDecimal getPlatformAmtYestNowData(String date,String yestStartDate, String yestEndDate) {
        return baseMapper.getPlatformAmtYestNowData(date,yestStartDate,yestEndDate);
    }

    /**
     * 获取有效交易笔数
     * @param merchantCode
     * @return
     */
    @Override
    public Integer getValidNumByMerchantCode(String merchantCode) {
        return baseMapper.getValidNumByMerchantCode(merchantCode);
    }
}
