package cn.pluss.platform.merchant.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.pluss.platform.BankCardService;
import cn.pluss.platform.IdCardService;
import cn.pluss.platform.aliMcc.AliMccService;
import cn.pluss.platform.bill.MerchantBillStatisticsService;
import cn.pluss.platform.constants.CommonError;
import cn.pluss.platform.converter.Converter;
import cn.pluss.platform.converter.MerchantBaseInfoConverter;
import cn.pluss.platform.dict.DictService;
import cn.pluss.platform.dto.*;
import cn.pluss.platform.entity.*;
import cn.pluss.platform.enums.UserRoleEnum;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.mapper.ActivityEnrollMapper;
import cn.pluss.platform.mapper.MerchantBaseInfoMapper;
import cn.pluss.platform.mapper.MerchantMarketMapper;
import cn.pluss.platform.mapper.MerchantOrderMapper;
import cn.pluss.platform.merchant.AccountService;
import cn.pluss.platform.merchant.MerchantBaseInfoService;
import cn.pluss.platform.merchantChannelStatus.MerchantChannelStatusService;
import cn.pluss.platform.merchantImage.MerchantImageService;
import cn.pluss.platform.merchantOrder.MerchantOrderStatisticsService;
import cn.pluss.platform.merchantStore.MerchantStoreService;
import cn.pluss.platform.region.RegionReflectService;
import cn.pluss.platform.roleUserInfo.RoleUserInfoService;
import cn.pluss.platform.systemConfig.SystemConfigService;
import cn.pluss.platform.userApp.UserAppService;
import cn.pluss.platform.userInfo.UserInfoService;
import cn.pluss.platform.util.MD5Util;
import cn.pluss.platform.util.RegexUtils;
import cn.pluss.platform.util.StringUtil;
import cn.pluss.platform.vo.MerchantBaseInfoVO;
import cn.pluss.platform.vo.MerchantBaseNewVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.Setter;
import lombok.val;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;

import static cn.pluss.platform.constants.ProjectConstant.PAGE_SIZE;

/**
 * @author SSS
 */
@Service("merchantBaseInfoService")
public class MerchantBaseInfoServiceImpl extends ServiceImpl<MerchantBaseInfoMapper, MerchantBaseInfo> implements MerchantBaseInfoService {

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

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

    @Setter(onMethod_ = {@Autowired})
    private AliMccService aliMccService;

    @Setter(onMethod_ = {@Autowired})
    private MerchantImageService imageService;

    @Setter(onMethod_ = {@Autowired})
    private IdCardService idCardService;

    @Setter(onMethod_ = {@Autowired})
    private BankCardService bankCardService;

    @Setter(onMethod_ = {@Autowired, @Lazy})
    private UserInfoService userInfoService;

    @Setter(onMethod_ = {@Autowired, @Lazy})
    private MerchantBillStatisticsService mbsService;

    @Autowired
    @Lazy
    private MerchantChannelStatusService mcsService;

    @Setter(onMethod_ = {@Autowired})
    private SystemConfigService systemConfigService;

    @Setter(onMethod_ = {@Autowired})
    private RoleUserInfoService roleUserInfoService;

    @Setter(onMethod_ = {@Autowired})
    private ActivityEnrollMapper activityEnrollMapper;

    @Setter(onMethod_ = {@Autowired})
    private MerchantOrderMapper merchantOrderMapper;

    @Setter(onMethod_ = {@Autowired, @Lazy})
    private MerchantOrderStatisticsService mosService;

    @Setter(onMethod_ = {@Autowired})
    private MerchantMarketMapper merchantMarketMapper;

    @Setter(onMethod_ = {@Autowired, @Lazy})
    private AccountService accountService;

    @Autowired
    private RegionReflectService reflectService;

    @Autowired
    private DictService dictService;

    @Override
    public MerchantBaseInfoVO apiGetMchDetail(String userId) {
        // 先判断是不是直推或间推
        UserApp userApp = userAppService.queryUserAppByToken();
        UserApp mchUserApp = userAppService.getOne(new QueryWrapper<UserApp>().eq("userId", userId));

        if (mchUserApp == null) {
            throw new MsgException("拒绝访问");
        }

        UserApp parent = userAppService.getOne(new QueryWrapper<UserApp>().eq("userId", mchUserApp.getParentId()));

        UserInfo ui = userInfoService.getById(mchUserApp.getUserId());

        boolean directFlag = false;

        if (!userApp.getUserId().equals(mchUserApp.getParentId())) {
            if (parent == null || !Objects.equals(parent.getParentId(), userApp.getUserId())) {
                throw new MsgException("拒绝访问");
            }
        } else {
            directFlag = true;
        }
        UserInfo pui = userInfoService.getById(parent.getUserId());

        MerchantBaseInfo mbi = getMerchantBaseInfoByUserId(userId);

        MerchantBaseInfoVO result = MerchantBaseInfoConverter.INSTANCE.domain2VO(mbi);
        result.setCreateDt(mchUserApp.getCreateDt());
        result.setContactName(mchUserApp.getUserName());
        result.setContactMobile(ui.getPhone().substring(0, 11));
        result.setParentContactName(parent.getUserName());
        result.setParentContactMobile(pui.getPhone().substring(0, 11));

        MerchantChannelStatus mcs = mcsService.getValidData(mbi.getMerchantCode());

        LambdaQueryWrapper<MerchantImage> qWrapperImg = Wrappers.lambdaQuery();
        qWrapperImg.eq(MerchantImage::getMerchantCode, mbi.getMerchantCode());
        qWrapperImg.in(MerchantImage::getPhotoType, MerchantImage.ImageType.SHOP_FRONT_DOOR,
                MerchantImage.ImageType.STORE_INTERIOR_PHOTO, MerchantImage.ImageType.CASH_DESK_PHOTO,
                MerchantImage.ImageType.CASH_DESK_WITH_PERSON);

        List<MerchantImage> miList = imageService.list(qWrapperImg);
        for (MerchantImage mi : miList) {
            switch (mi.getPhotoType()) {
                case MerchantImage.ImageType.SHOP_FRONT_DOOR:
                    result.setStoreHeadPic(mi.getPicUrl());
                    break;
                case MerchantImage.ImageType.STORE_INTERIOR_PHOTO:
                    result.setStoreInsidePic(mi.getPicUrl());
                    break;
                case MerchantImage.ImageType.CASH_DESK_PHOTO:
                    result.setCashPic(mi.getPicUrl());
                    break;
                case MerchantImage.ImageType.CASH_DESK_WITH_PERSON:
                    result.setCashDeskWithPerson(mi.getPicUrl());
                    break;
                case MerchantImage.ImageType.HAND_IDCARD_PHOTO:
                    result.setHandIdCard(mi.getPicUrl());
                    break;
                default:
                    break;
            }
        }

        if (mcs == null || Objects.equals(MerchantChannelStatus.AUDIT_STATUS_REJECT, mcs.getStatus())) {
            return result;
        }

        if (directFlag || Objects.equals(MerchantChannelStatus.AUDIT_STATUS_SUCCESS, mcs.getStatus())) {
            String currentDate = DateUtil.format(new Date(), "yyyy-MM-dd");

            // 计算商户交易信息
            Map<String, Object> dayBillMap = merchantOrderMapper.getConsumeFee(mbi.getMerchantCode(), currentDate);
            if (dayBillMap != null) {
                result.setDayBillCount(dayBillMap.get("count").toString());
                result.setDayBillSum(dayBillMap.get("fee").toString());
            } else {
                result.setDayBillCount("0");
                result.setDayBillSum("0.00");
            }

            // 计算商户上月交易信息
            DateTime date = DateUtil.lastMonth();
            date.setField(DateField.DAY_OF_MONTH, 1);
            MerchantOrderStatistics mos = new MerchantOrderStatistics();
            mos.setMerchantCode(mcs.getMerchantCode());
            mos.setStartDate(LocalDate.of(date.year(), date.month() + 1, date.dayOfMonth()));
            mos = mosService.getOne(new QueryWrapper<>(mos));

            if (mos == null) {
                result.setLastMonthBillCount("0");
                result.setLastMonthBillSum("0.00");
            } else {
                result.setLastMonthBillCount((mos.getCount() - mos.getRetCount()) + "");
                result.setLastMonthBillSum(mos.getTotalFee().subtract(mos.getRetFee()).setScale(2, RoundingMode.HALF_EVEN).toPlainString());
            }

            // 计算商户今年的交易信息
            QueryWrapper<MerchantOrderStatistics> qWrapper = new QueryWrapper<>();
            qWrapper.eq("merchantCode", mcs.getMerchantCode());
            qWrapper.likeRight("startDate", new DateTime().year());
            qWrapper.select("SUM(totalFee) totalFee, SUM(count) count, SUM(retFee) retFee, SUM(retCount) retCount");
            qWrapper.groupBy("merchantCode");
            mos = mosService.getOne(qWrapper);
            if (mos == null) {
                result.setYearBillCount("0");
                result.setYearBillSum("0.00");
            } else {
                result.setYearBillCount((mos.getCount() - mos.getRetCount()) + "");
                result.setYearBillSum(mos.getTotalFee().subtract(mos.getRetFee()).setScale(2, RoundingMode.HALF_EVEN).toPlainString());
            }

            // 计算商户总的交易信息
            LambdaQueryWrapper<MerchantOrderStatistics> qWrapper2 = Wrappers.lambdaQuery();
            qWrapper2.eq(MerchantOrderStatistics::getMerchantCode, mcs.getMerchantCode());
            qWrapper2.likeRight(MerchantOrderStatistics::getStartDate, "1970-01-01");
            mos = mosService.getOne(qWrapper2);
            if (mos == null) {
                result.setAllBillCount("0");
                result.setAllBillSum("0.00");
            } else {
                result.setAllBillCount((mos.getCount() - mos.getRetCount()) + "");
                result.setAllBillSum(mos.getTotalFee().subtract(mos.getRetFee()).setScale(2, RoundingMode.HALF_EVEN).toPlainString());
            }
        }

        return result;
    }

    @Override
    public List<MerchantBaseInfo> getAllByUserId(String userId) {
        MerchantBaseInfo merchantBaseInfo = getMerchantBaseInfoByUserId(userId);
        if (merchantBaseInfo == null) {
            return new ArrayList<>();
        }

        if (StringUtils.isEmpty(merchantBaseInfo.getBindingCode())) {
            return Collections.singletonList(merchantBaseInfo);
        }

        MerchantBaseInfo condition = new MerchantBaseInfo().setBindingCode(merchantBaseInfo.getBindingCode());
        return list(new QueryWrapper<>(condition));
    }

    @Override
    public void saveMerchantBaseInfo(MerchantBaseInfoDTO merchantBaseInfoDTO) {
        Dict condition = new Dict().setValue(merchantBaseInfoDTO.getAlias());
        Dict banAlias = dictService.getByCode("BAN_ALIAS", condition);
        if (banAlias != null) {
            throw new MsgException("商户简称不合规，请不要使用行业泛词或敏感词汇");
        }

        UserApp userAppToken = userAppService.queryUserAppByToken();
        merchantBaseInfoDTO.setUserId(userAppToken.getUserId() + "");
        UserInfo userInfo = userInfoService.getById(userAppToken.getUserId());
        merchantBaseInfoDTO.setContactMobile(userInfo.getPhone().substring(0, 11));

        UserApp pUserApp = null;
        if (userAppToken.getParentId() != null) {
            pUserApp = userAppService.getOne(new QueryWrapper<UserApp>().eq("userId", userAppToken.getParentId()));
        }

        IdCard idCard = idCardService.getCertIdCard(userAppToken.getUserId() + "");
        merchantBaseInfoDTO.setContactName(idCard.getCertName());

        // 商户全称先按照小微的格式来填写，若有营业执照，在填写营业执照的时候会将商户全称修改为营业执照名称
        if ("1".equals(merchantBaseInfoDTO.getMerchantType())) {
            merchantBaseInfoDTO.setMerchantName("商户_" + idCard.getCertName());
        }

        // 商家名称 //经营范围 //联系人姓名 //联系人电话 //联系人邮箱 //店铺所在地区 //详细地址
        MerchantBaseInfo mbi = merchantBaseInfoDTO.convertMerchantBaseInfoDTO();
        if (pUserApp != null && UserRoleEnum.ZY_BST.getCode().equals(pUserApp.getRoleCode())) {
            mbi.setIsUnionPay(pUserApp.getIsUnionPay());
        } else {
            mbi.setIsUnionPay("1");
        }

        RegionCodeLs regionCode = reflectService.getLsRegionCode(mbi.getProvince(), mbi.getCity(), mbi.getDistrict());
        if (regionCode != null) {
            mbi.setAddressNo(regionCode.getProvinceCode() + "-" + regionCode.getCityCode() + "-" + regionCode.getAreaCode());
        }

        // 支付宝官方mccCode
        String aliMcc = aliMccService.queryMccCode(mbi.getMcc());
        mbi.setAliMcc(aliMcc);
        String merchantCode = userAppToken.getMerchantCode();
        if (StringUtils.isEmpty(merchantCode)) {
            // 不存在商户Code
            merchantCode = "M800" + DateUtil.format(new Date(), "yyyyMMdd") + StringUtil.random6V2();
            mbi.setBindingCode(UUID.randomUUID().toString().replace("-", ""));
            userAppToken.setMerchantCode(merchantCode);
            userAppToken.setMerchantName(merchantBaseInfoDTO.getMerchantName());
            userAppService.updateById(userAppToken);
        }

        mbi.setMerchantCode(merchantCode);
        saveMerchantBaseInfo(mbi);

        imageService.saveMerchantImageUpload(merchantCode, merchantBaseInfoDTO.getStoreHeadPic(), MerchantImage.ImageType.SHOP_FRONT_DOOR);
        imageService.saveMerchantImageUpload(merchantCode, merchantBaseInfoDTO.getCashPic(), MerchantImage.ImageType.CASH_DESK_PHOTO);
        imageService.saveMerchantImageUpload(merchantCode, merchantBaseInfoDTO.getStoreInsidePic(), MerchantImage.ImageType.STORE_INTERIOR_PHOTO);

        // 咸鱼字段极多，待清理
        MerchantStore merchantStore = new MerchantStore().setMerchantCode(mbi.getMerchantCode());
        merchantStore = merchantStoreService.queryMerchantStore(merchantStore);
        if (merchantStore == null) {
            merchantStore = MerchantBaseInfoConverter.INSTANCE.baseInfo2StoreInfo(mbi);
            if (pUserApp != null) {
                merchantStore.setIsMarket(pUserApp.getIsMarket());
                merchantStore.setPayEcdemicSwitch(pUserApp.getPayEcdemicSwitch());
            }
            merchantStore.setStoreId(StringUtil.genRandomNum(6));
            merchantStore.setStatus("1");
            merchantStore.setCreateDt(new Date());
            merchantStoreService.saveMerchantStore(merchantStore);
        } else {
            merchantStore.setStoreName(mbi.getAlias());
            merchantStore.setMerchantName(mbi.getAlias());
            merchantStoreService.updateMerchantStore(merchantStore);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveBusinessLicense(BusinessLicenseDTO businessLicenseDTO) {
        // if (!USCCUtil.checkUSCC(businessLicenseDTO.getBussAuthNum())) {
        //     throw new MsgException("营业执照号校验不通过，请仔细核对修改后再提交");
        // }

        UserApp tokenUa = userAppService.queryUserAppByToken();

        LambdaQueryWrapper<MerchantChannelStatus> qMcsWrapper = Wrappers.lambdaQuery();
        qMcsWrapper.eq(MerchantChannelStatus::getMerchantCode, tokenUa.getMerchantCode());
        qMcsWrapper.in(MerchantChannelStatus::getStatus,
                MerchantChannelStatus.AUDIT_STATUS_EXAMINING,
                MerchantChannelStatus.AUDIT_STATUS_SUCCESS,
                MerchantChannelStatus.AUDIT_STATUS_WAITING_SIGN,
                MerchantChannelStatus.AUDIT_STATUS_SIGNED);
        MerchantChannelStatus mcs = mcsService.getOne(qMcsWrapper.last("limit 1"));

        MsgException.checkNonNull(mcs, "当前状态暂不支持修改商户信息");

        final IdCard certIdCard = idCardService.getCertIdCard(tokenUa.getUserId());

        if (!Objects.equals(certIdCard.getCertName(), businessLicenseDTO.getPrincipalPerson())) {
            throw new MsgException("【营业执照所属人】必须与【实名身份信息】保持一致");
        }

        String bussAuthAddress = businessLicenseDTO.getBussAuthAddress();
        businessLicenseDTO.setBussAuthAddress(StringUtil.replaceNonLegalChar(bussAuthAddress));

        String bussAuthName = businessLicenseDTO.getBussAuthName();
        businessLicenseDTO.setBussAuthName(StringUtil.replaceNonLegalChar(bussAuthName));

        MerchantBaseInfo existMbi = getMerchantBaseInfoByUserId(businessLicenseDTO.getUserId() + "");
        MsgException.checkEquals("1", existMbi.getMerchantType(), "小微商户不需要营业执照");
        existMbi.setMerchantName(businessLicenseDTO.getBussAuthName());

        // 营业执照类型 //营业执照号码 //营业执照图片 //营业执照名称 //经营者姓名 //注册地址 //有效开始期 //有效结束期
        Long userId = businessLicenseDTO.getUserId();
        MsgException.checkNull(userId, CommonError.NO_LOGIN);

        UserApp userApp = new UserApp();
        userApp.setUserId(userId);
        userApp = userAppService.queryUserApp(userApp);

        MsgException.checkNull(userApp, CommonError.NO_EXIST_ACCOUNT);

        // 营业执照所属人发生变化，则将现有的法人信息清理掉
        if (!Objects.equals(existMbi.getPrincipalPerson(), businessLicenseDTO.getPrincipalPerson())) {
            LambdaQueryWrapper<IdCard> qWrapper = Wrappers.lambdaQuery();
            qWrapper.eq(IdCard::getUserId, userApp.getUserId()).eq(IdCard::getUserType, IdCard.TYPE_LEGAL);
            idCardService.remove(qWrapper);
        }

        existMbi = businessLicenseDTO.convertBusinessLicenseDTO();

        String merchantCode = userApp.getMerchantCode();
        // 不存在商户Code
        if (StringUtils.isEmpty(merchantCode)) {
            merchantCode = "M800" + DateUtil.format(new Date(), "yyyyMMdd") + StringUtil.random6V2();
            existMbi.setMerchantCode(merchantCode);
            existMbi.setBindingCode(UUID.randomUUID().toString().replace("-", ""));
            saveMerchantBaseInfo(existMbi);
            userApp.setMerchantCode(merchantCode);
            userAppService.updateById(userApp);
        } else {
            existMbi.setMerchantCode(merchantCode);
        }

        saveMerchantBaseInfo(existMbi);

        MerchantImage merchantImage = new MerchantImage();
        merchantImage.setPhotoType(MerchantImage.ImageType.BUSINESS_LICENSE).setMerchantCode(existMbi.getMerchantCode());
        merchantImage.setPicUrl(businessLicenseDTO.getBusinessLicensePic());

        imageService.saveMerchantImageUpload(merchantImage.getMerchantCode(), merchantImage.getPicUrl(), merchantImage.getPhotoType());
    }

    @Override
    public MerchantBaseInfo getMerchantBaseInfoByUserId(String userId) {
        LambdaQueryWrapper<MerchantBaseInfo> qWrapper = new LambdaQueryWrapper<MerchantBaseInfo>().eq(MerchantBaseInfo::getUserId, userId);
        return baseMapper.selectOne(qWrapper);
    }

    @Override
    public MerchantBaseInfo getMerchantBaseInfoByMerchantCode(String merchantCode) {
        LambdaQueryWrapper<MerchantBaseInfo> qWrapper = new LambdaQueryWrapper<MerchantBaseInfo>().eq(MerchantBaseInfo::getMerchantCode, merchantCode);
        return baseMapper.selectOne(qWrapper);
    }

    @Override
    public MerchantBaseInfo queryMerchantBaseInfo(MerchantBaseInfo merchantBaseInfo) {
        return baseMapper.queryMerchantBaseInfo(merchantBaseInfo);
    }

    @Override
    public MerchantBaseInfo getMerchantBaseInfoById(Integer id) {
        LambdaQueryWrapper<MerchantBaseInfo> qWrapper = new LambdaQueryWrapper<MerchantBaseInfo>().eq(MerchantBaseInfo::getId, id);
        return baseMapper.selectOne(qWrapper);
    }

    @Override
    public List<MerchantBaseInfo> queryMerchantBaseInfoList(MerchantBaseInfo merchantBaseInfo) {
        return baseMapper.queryMerchantBaseInfoList(merchantBaseInfo);
    }

    // @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveMerchantBaseInfo(MerchantBaseInfo mbi) {
        String address = mbi.getAddress();
        mbi.setAddress(StringUtil.replaceNonLegalChar(address));

        String merchantName = mbi.getMerchantName();
        mbi.setMerchantName(StringUtil.replaceNonLegalChar(merchantName));

        MerchantBaseInfo existData = getMerchantBaseInfoByUserId(mbi.getUserId());

        if (existData != null) {
            String existDataMerchantType = existData.getMerchantType();
            String newMerchantType = mbi.getMerchantType();
            // 商户类型为空则表明是更新营业执照
            if (StringUtils.isNotEmpty(newMerchantType) && !newMerchantType.equals(existDataMerchantType)) {
                LambdaQueryWrapper<IdCard> qWrapper = Wrappers.lambdaQuery();
                qWrapper.eq(IdCard::getUserId, mbi.getUserId()).eq(IdCard::getUserType, IdCard.TYPE_LEGAL);
                idCardService.remove(qWrapper);
                accountService.delAccount(mbi.getUserId(), Account.CHANNEL_TYPE_D1);
                accountService.delAccount(mbi.getUserId(), Account.CHANNEL_TYPE_D0);
            }

            mbi.setId(existData.getId());
            baseMapper.updateById(mbi);
        } else {
            baseMapper.insert(mbi);
        }
    }

    @Override
    public void updateMerchantBaseInfo(MerchantBaseInfo merchantBaseInfo) {
        merchantBaseInfo.setUpdateDt(new Date());
        baseMapper.updateMerchantBaseInfo(merchantBaseInfo);
    }

    @Override
    public void deleteMerchantBaseInfo(MerchantBaseInfo merchantBaseInfo) {
        baseMapper.deleteMerchantBaseInfo(merchantBaseInfo);
    }

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

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

    @Override
    public List<MerchantBaseNewVO> queryMerchantBaseNewPage(Map<String, Object> map) {
        List<MerchantBaseNewVO> queryMerchantBaseNewPage = baseMapper.queryMerchantBaseNewPage(map);
        for (MerchantBaseNewVO merchantBaseNewVO : queryMerchantBaseNewPage) {
            MerchantStore merchantStore = new MerchantStore();
            merchantStore.setMerchantCode(merchantBaseNewVO.getMerchantCode());
            List<MerchantStore> queryMerchantStoreList = merchantStoreService.queryMerchantStoreList(merchantStore);
            merchantBaseNewVO.setStoreNameList(queryMerchantStoreList);
        }
        return queryMerchantBaseNewPage;
    }

    public List<MerchantBaseNewVO> queryMerchantNoBaseNewPage(Map<String, Object> map) {
        List<MerchantBaseNewVO> queryMerchantNoBaseNewPage = baseMapper.queryMerchantNoBaseNewPage(map);
        for (MerchantBaseNewVO merchantBaseNewVO : queryMerchantNoBaseNewPage) {
            MerchantStore merchantStore = new MerchantStore();
            merchantStore.setMerchantCode(merchantBaseNewVO.getMerchantCode());
            List<MerchantStore> queryMerchantStoreList = merchantStoreService.queryMerchantNoStoreList(merchantStore);
            merchantBaseNewVO.setStoreNameList(queryMerchantStoreList);
        }
        return queryMerchantNoBaseNewPage;
    }

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

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveMerchantUser(MerchantBaseInfoDTO merchantBaseInfoDTO) {

        UserApp tokenUa = userAppService.checkApiToken();
        merchantBaseInfoDTO.setUserId(tokenUa.getUserId() + "");
        // 当前userId
        String userId = merchantBaseInfoDTO.getUserId();

        UserInfo tokenUserInfo = userInfoService.getById(userId);

        final MerchantStore tokenMs = merchantStoreService.getStoreByMerchantCode(tokenUa.getMerchantCode());
        final MerchantBaseInfo tokenMbi = getMerchantBaseInfoByUserId(userId);

        String userPhone = merchantBaseInfoDTO.getUserPhone();
        String suffix = userPhone.substring(userPhone.length() - 6);
        merchantBaseInfoDTO.setUserPhone(tokenUserInfo.getLoginName() + "@" + suffix);
        String merchantName = merchantBaseInfoDTO.getMerchantName();
        merchantName = StringUtil.replaceNonLegalChar(merchantName);
        merchantBaseInfoDTO.setMerchantName(merchantName);

        merchantBaseInfoDTO.setContactMobile(tokenUserInfo.getPhone().substring(0, 11));

        IdCard idCard = idCardService.getCertIdCard(userId);
        merchantBaseInfoDTO.setContactName(idCard.getCertName());

        UserApp userApp = new UserApp();
        userApp.setUserId(Long.valueOf(userId));
        List<UserApp> queryUserAppList = userAppService.queryUserAppList(userApp);

        MsgException.checkBlank(queryUserAppList, "无当前账号");
        userApp = queryUserAppList.get(0);

        MerchantBaseInfo merchantBaseInfo = new MerchantBaseInfo();
        merchantBaseInfo.setUserId(userId);
        merchantBaseInfo = queryMerchantBaseInfo(merchantBaseInfo);
        MsgException.checkNull(merchantBaseInfo, "添加失败");

        // 多商户关联码
        String bindingCode = merchantBaseInfo.getBindingCode();
        if (bindingCode == null) {
            bindingCode = UUID.randomUUID().toString().replace("-", "");
            merchantBaseInfo.setBindingCode(bindingCode);
            updateById(merchantBaseInfo);
        }

        MsgException.checkBlank(bindingCode, "添加失败");

        MerchantBaseInfo merchantBaseInfo2 = new MerchantBaseInfo();
        merchantBaseInfo2.setBindingCode(bindingCode);
        List<MerchantBaseInfo> queryMerchantBaseInfoList2 = queryMerchantBaseInfoList(merchantBaseInfo2);
        if (queryMerchantBaseInfoList2 != null && queryMerchantBaseInfoList2.size() > 10) {
            throw new MsgException("最多添加十个门店");
        }

        MerchantBaseInfo baseInfo = merchantBaseInfoDTO.convertMerchantBaseInfoDTO();
        val regionCode = reflectService.getLsRegionCode(baseInfo.getProvince(), baseInfo.getCity(), baseInfo.getDistrict());
        if (regionCode != null) {
            baseInfo.setAddressNo(regionCode.getProvinceCode() + "-" + regionCode.getCityCode() + "-" + regionCode.getAreaCode());
        }
        baseInfo.setBindingCode(bindingCode);
        UserInfo userInfo = new UserInfo();
        userInfo.setPhone(merchantBaseInfoDTO.getUserPhone());
        List<UserInfo> queryUserInfoList = userInfoService.queryUserInfoList(userInfo);

        MsgException.checkNonBlank(queryUserInfoList, CommonError.PHONE_HAS_REGISTER);

        userInfo.setLoginName(merchantBaseInfoDTO.getUserPhone());
        userInfo.setPassword(MD5Util.MD5Encode(merchantBaseInfoDTO.getUserPassWord(), "utf-8"));
        userInfoService.saveUserInfo(userInfo);
        String roleType = "promoter_role_id";
        Long roleId = null;
        // 获取全部的角色信息
        List<SystemConfig> systemConfigs = systemConfigService.querySystemConfigList(new SystemConfig());
        for (SystemConfig systemConfig : systemConfigs) {
            if (systemConfig.getPropertyKey().equalsIgnoreCase(roleType)) {
                roleId = Long.parseLong(systemConfig.getPropertyValue());
                break;
            }
        }

        MsgException.checkNull(roleId, "获取角色信息错误！");

        RoleUserInfo role = new RoleUserInfo();
        role.setRoleId(roleId);
        role.setUserId(userInfo.getId());
        roleUserInfoService.saveRoleUserInfo(role);
        UserApp userApp2 = new UserApp();
        userApp2.setUserId(userInfo.getId());
        userApp2.setLevel(1);// 默认一级推广员
        userApp2.setCreateDt(new Date());
        userApp2.setStatus(0);
        String merchantCode = "M800" + DateUtil.format(new Date(), "yyyyMMdd") + StringUtil.random6V2();
        userApp2.setMerchantCode(merchantCode);
        userApp2.setMerchantName(merchantBaseInfoDTO.getAlias());
        userApp2.setUserType("promoter");
        userApp2.setInviteNum(StringUtil.genRandomNum(5));
        userApp2.setParentId(userApp.getParentId());
        userApp2.setUserName(userApp.getUserName());
        userApp2.setSort(userApp.getSort());
        userApp2.setRoleCode(userApp.getRoleCode());
        userApp2.setLevelCode(userApp.getLevelCode());
        userApp2.setSpreadFlag("0");
        userAppService.save(userApp2);// 新添加的账号
        String aliMcc = aliMccService.queryMccCode(merchantBaseInfo.getMcc());// 支付宝官方mccCode
        baseInfo.setAliMcc(aliMcc);
        baseInfo.setMerchantCode(merchantCode);
        baseInfo.setIsUnionPay(tokenMbi.getIsUnionPay());
        baseInfo.setBindingCode(bindingCode);
        baseInfo.setUserId(userApp2.getUserId() + "");
        baseInfo.setAlias(merchantBaseInfoDTO.getAlias());
        saveMerchantBaseInfo(baseInfo);

        // 新建子商户的时候需要同时创建merchant_store
        MerchantStore merchantStore = MerchantBaseInfoConverter.INSTANCE.baseInfo2StoreInfo(baseInfo);
        merchantStore.setStoreId(StringUtil.genRandomNum(6));
        merchantStore.setStatus("1");
        merchantStore.setIsMarket(tokenMs.getIsMarket());
        merchantStore.setPayEcdemicSwitch(tokenMs.getPayEcdemicSwitch());
        merchantStore.setCreateDt(new Date());
        merchantStoreService.saveMerchantStore(merchantStore);

        userApp2.setMerchantName(merchantBaseInfoDTO.getMerchantName());

        BankCard bankCard = new BankCard().setUserId(userId).setAccountType(BankCard.ACCOUNT_TYPE_CERT);
        bankCard = bankCardService.getOne(new QueryWrapper<>(bankCard));

        if (bankCard != null) {
            idCard.setUserId(userInfo.getId() + "");
            idCard.setId(null);
            idCard.setCreateTime(new Date());
            idCard.setUpdateTime(new Date());
            idCardService.save(idCard);

            bankCard.setUserId(userInfo.getId() + "");
            bankCard.setId(null);
            bankCard.setCreateTime(new Date());
            bankCard.setUpdateTime(new Date());
            bankCardService.save(bankCard);

            userApp2.setStatus(3);
            userApp2.setBankStatus(3);
            userAppService.updateById(userApp2);
        }

        // 门头照
        imageService.saveMerchantImageUpload(merchantCode, merchantBaseInfoDTO.getStoreHeadPic(), MerchantImage.ImageType.SHOP_FRONT_DOOR);
        imageService.saveMerchantImageUpload(merchantCode, merchantBaseInfoDTO.getCashPic(), MerchantImage.ImageType.CASH_DESK_PHOTO);
        imageService.saveMerchantImageUpload(merchantCode, merchantBaseInfoDTO.getStoreInsidePic(), MerchantImage.ImageType.STORE_INTERIOR_PHOTO);
    }

    /**
     * 商户活动奖励金发放
     *
     * @param merchantCode 商编
     * @param consumeFee   消费金额
     */
    @Async
    @Override
    public void grantMerchantMarket(String merchantCode, Double consumeFee) {
        log.debug("===================>奖励金发放操作开始,商户编号:" + merchantCode + "<=====================");
        QueryWrapper<ActivityEnroll> queryWrapper = new QueryWrapper<ActivityEnroll>().eq("merchantCode", merchantCode)
                .eq("status", "1").isNotNull("actType");
        List<ActivityEnroll> actEnrollList = activityEnrollMapper.selectList(queryWrapper);
        if (actEnrollList.isEmpty()) {
            log.debug("===================>奖励金发放操作结束,商户编号:" + merchantCode + "未参加活动<=====================");
            return;
        }
        QueryWrapper<UserApp> baseQuery = new QueryWrapper<UserApp>().eq("merchantCode", merchantCode)
                .eq("userType", "promoter");
        UserApp app = userAppService.getOne(baseQuery);
        if (app == null) {
            log.debug("===================>奖励金发放操作结束,商户编号:" + merchantCode + "的商户用户信息不存在<=====================");
            return;
        }
        for (ActivityEnroll enroll : actEnrollList) {
            Date auditTime = enroll.getAuditTime();
            if (auditTime == null) {
                auditTime = enroll.getUpdateTime();
            }
            QueryWrapper<MerchantMarket> ketQuery = new QueryWrapper<MerchantMarket>().eq("userId", app.getUserId()).in("source", 1, 2, 5);
            List<MerchantMarket> lists = merchantMarketMapper.selectList(ketQuery);
            BigDecimal marketCount = BigDecimal.ZERO;
            if (!lists.isEmpty()) {
                for (MerchantMarket mm : lists) {
                    marketCount = marketCount.add(mm.getMarketAmt());
                }
            }
            String dateStr = new SimpleDateFormat("yyyy-MM-dd").format(auditTime);
            BigDecimal tradeAmt = merchantOrderMapper.getCountMaketAmtAndDate(merchantCode, dateStr);
            BigDecimal countTradeAmt = tradeAmt.add(new BigDecimal(String.valueOf(consumeFee)));
            if ("1".equals(enroll.getActType())) {
                BigDecimal marketQuota = new BigDecimal("500000");
                BigDecimal addMarket = new BigDecimal("199");
                String value = systemConfigService.querySystemConfigValue("activityTransMarketQuota");
                if (StringUtils.isNotEmpty(value)) {
                    marketQuota = new BigDecimal(value.split("-")[0]);
                    addMarket = new BigDecimal(value.split("-")[1]);
                }
                if (countTradeAmt.compareTo(marketQuota) >= 0 && lists.size() == 0) {
                    MerchantMarket market = new MerchantMarket();
                    market.setCreateTime(new Date());
                    market.setSource(enroll.getActType());
                    market.setMarketAmt(addMarket);
                    market.setUserId(app.getUserId());
                    market.setUserName(app.getUserName());
                    merchantMarketMapper.insert(market);
                    log.debug("===================>奖励金发放操作结束,商户编号:" + merchantCode + ",成功发放扫码王返利奖励金，发放奖励金数量为:" + addMarket + "元<=====================");
                } else if (countTradeAmt.compareTo(marketQuota) >= 0 && lists.size() != 0) {
                    if (addMarket.compareTo(marketCount) > 0) {
                        MerchantMarket m = new MerchantMarket();
                        m.setCreateTime(new Date());
                        m.setSource(enroll.getActType());
                        m.setMarketAmt(addMarket.subtract(marketCount).setScale(2, BigDecimal.ROUND_HALF_UP));
                        m.setUserId(app.getUserId());
                        m.setUserName(app.getUserName());
                        merchantMarketMapper.insert(m);
                    }
                    log.debug("===================>奖励金发放操作结束,商户编号:" + merchantCode + ",补发奖励金差价：" + addMarket.subtract(marketCount) + "<=====================");
                } else {
                    log.debug("===================>奖励金发放操作结束,商户编号:" + merchantCode + ",不符合发放扫码王返利奖励金条件<=====================");
                }
            } else if ("2".equals(enroll.getActType())) {
                BigDecimal marketQuota = new BigDecimal("250000");
                BigDecimal addMarket = new BigDecimal("99");
                String value = systemConfigService.querySystemConfigValue("activityTransP117Quota");
                if (StringUtil.isNotEmpty(value)) {
                    marketQuota = new BigDecimal(value.split("-")[0]);
                    addMarket = new BigDecimal(value.split("-")[1]);
                }
                if (countTradeAmt.compareTo(marketQuota) >= 0 && lists.isEmpty()) {
                    MerchantMarket market = new MerchantMarket();
                    market.setCreateTime(new Date());
                    market.setSource(enroll.getActType());
                    market.setMarketAmt(addMarket);
                    market.setUserId(app.getUserId());
                    market.setUserName(app.getUserName());
                    merchantMarketMapper.insert(market);
                    log.debug("===================>奖励金发放操作结束,商户编号:" + merchantCode + ",成功发放云音箱返利奖励金，发放奖励金数量为:" + addMarket + "元<=====================");
                } else if (countTradeAmt.compareTo(marketQuota) >= 0 && !lists.isEmpty()) {
                    if (addMarket.compareTo(marketCount) > 0) {
                        MerchantMarket m = new MerchantMarket();
                        m.setCreateTime(new Date());
                        m.setSource(enroll.getActType());
                        m.setMarketAmt(addMarket.subtract(marketCount).setScale(2, RoundingMode.HALF_UP));
                        m.setUserId(app.getUserId());
                        m.setUserName(app.getUserName());
                        merchantMarketMapper.insert(m);
                    }
                    log.debug("===================>奖励金发放操作结束,商户编号:" + merchantCode + ",补发奖励金差价：" + addMarket.subtract(marketCount) + "<=====================");
                } else {
                    log.debug("===================>奖励金发放操作结束,商户编号:" + merchantCode + ",不符合发放扫码王返利奖励金条件<=====================");
                }
            } else if ("5".equals(enroll.getActType())) {
                BigDecimal marketQuota = new BigDecimal("500000");
                BigDecimal addMarket = new BigDecimal("169");
                String value = systemConfigService.querySystemConfigValue("activityTransCG02Quota");
                if (StringUtils.isNotEmpty(value)) {
                    marketQuota = new BigDecimal(value.split("-")[0]);
                    addMarket = new BigDecimal(value.split("-")[1]);
                }
                if (countTradeAmt.compareTo(marketQuota) >= 0 && lists.isEmpty()) {
                    MerchantMarket market = new MerchantMarket();
                    market.setCreateTime(new Date());
                    market.setSource(enroll.getActType());
                    market.setMarketAmt(addMarket);
                    market.setUserId(app.getUserId());
                    market.setUserName(app.getUserName());
                    merchantMarketMapper.insert(market);
                    log.debug("===================>奖励金发放操作结束,商户编号:" + merchantCode + ",成功发放4G音箱返利奖励金，发放奖励金数量为:" + addMarket + "元<=====================");
                } else if (countTradeAmt.compareTo(marketQuota) >= 0 && !lists.isEmpty()) {
                    if (addMarket.compareTo(marketCount) > 0) {
                        MerchantMarket m = new MerchantMarket();
                        m.setCreateTime(new Date());
                        m.setSource(enroll.getActType());
                        m.setMarketAmt(addMarket.subtract(marketCount).setScale(2, RoundingMode.HALF_UP));
                        m.setUserId(app.getUserId());
                        m.setUserName(app.getUserName());
                        merchantMarketMapper.insert(m);
                    }
                    log.debug("===================>奖励金发放操作结束,商户编号:" + merchantCode + ",补发奖励金差价：" + addMarket.subtract(marketCount) + "<=====================");
                } else {
                    log.debug("===================>奖励金发放操作结束,商户编号:" + merchantCode + ",不符合发放扫码王返利奖励金条件<=====================");
                }
            }
        }
        log.debug("===================>商户编号:" + merchantCode + ",奖励金发放操作结束<=====================");
    }

    /**
     * 关联分页查询商户信息
     *
     * @param merchantPage
     * @param userApp
     * @return
     */
    @Override
    public Page<MerchantBaseInfo> pageJoinData(Page<MerchantBaseInfo> merchantPage, UserApp userApp) {
        return this.baseMapper.pageJoinData(merchantPage, userApp);
    }

    /**
     * 商户详情分页查询
     *
     * @param currPage
     * @param size
     * @param merchantBaseNewVO
     * @return 分页数据
     */
    @Override
    public Map<String, Object> listMerchantBaseInfoPage(Integer currPage, Integer size, String column, Boolean asc, MerchantBaseNewVO merchantBaseNewVO) {
        Map<String, Object> result = new HashMap<>(16);
        Map<String, Object> map = new HashMap<>(16);
        map.put("column", column);
        map.put("asc", asc);
        if (StringUtils.isNotEmpty(merchantBaseNewVO.getUserId())) {
            map.put("userId", merchantBaseNewVO.getUserId());
        }
        if (StringUtils.isNotEmpty(merchantBaseNewVO.getPhone())) {
            map.put("phone", merchantBaseNewVO.getPhone());
        }
        if (StringUtils.isNotEmpty(merchantBaseNewVO.getParentIdPhone())) {
            map.put("parentIdPhone", merchantBaseNewVO.getParentIdPhone());
        }
        map.put("pageSize", size);
        map.put("offset", (currPage - 1) * size);
        if (StringUtils.isNotEmpty(merchantBaseNewVO.getUserName())) {
            map.put("userName", merchantBaseNewVO.getUserName());
        }
        if (StringUtils.isNotEmpty(merchantBaseNewVO.getAlias())) {
            map.put("alias", merchantBaseNewVO.getAlias());
        }
        List<MerchantBaseNewVO> merchantBaseInfoList;
        Integer count = 0;
        merchantBaseInfoList = queryMerchantBaseNewPage(map);
        count = queryMerchantBaseNewPageCount(map);
        result.put("merchantBaseInfoList", merchantBaseInfoList);
        result.put("count", count);
        result.put("pageCount", StringUtil.getPageCount(count, PAGE_SIZE));
        result.put("currPage", currPage);
        result.put("code", 200);
        return result;
    }

    @Override
    public void apiSwitchBankLargePermission() {
        UserApp userApp = userAppService.queryUserAppByToken();
        MerchantBaseInfo mbi = getMerchantBaseInfoByUserId(userApp.getUserId() + "");
        if (mbi == null) {
            throw new MsgException("请先进件");
        }

        if ("0".equals(mbi.getAllowBankLarge())) {
            mbi.setAllowBankLarge("1");
        } else {
            mbi.setAllowBankLarge("0");
        }

        updateById(mbi);
    }

    @Override
    public void apiWxCertPass() {
        UserApp userApp = userAppService.queryUserAppByToken();
        MerchantChannelStatus mcs = mcsService.getValidData(userApp.getMerchantCode());

        if (mcs == null) {
            throw new MsgException("当前商户还未进件");
        }

        if (!MerchantChannelStatus.AUDIT_STATUS_SUCCESS.equals(mcs.getStatus())) {
            throw new MsgException("当前商户还通过进件");
        }

        if (!Objects.equals(mcs.getAuthorizationStatus(), MerchantChannelStatus.AUTHORIZATION_STATUS_AUTHORIZED)) {
            mcs.setAuthorizationStatus(MerchantChannelStatus.AUTHORIZATION_STATUS_AUTHORIZED);
            mcsService.updateById(mcs);
        }

        MerchantBaseInfo mbi = getMerchantBaseInfoByUserId(userApp.getUserId() + "");
        mbi.setWxCertStatus("1");
        updateById(mbi);
    }

    @Override
    public Page<MercOrderDataDTO> pageData(Page<MercOrderDataDTO> page, MercOrderDataDTO dto) {
        return this.baseMapper.pageData(page, dto);
    }

    /**
     * pageTradeData
     *
     * @param page:
     * @param dto:
     * @return com.baomidou.mybatisplus.extension.plugins.pagination.Page<cn.pluss.platform.dto.MercTradeDataDTO>
     * @date: 2021/12/31 13:47
     */
    @Override
    public Page<MercTradeDataDTO> pageTradeData(Page<MercTradeDataDTO> page, MercTradeDataDTO dto) {
        if (!Objects.equals(dto.getCondition(), -1)) {
            return baseMapper.pageTradeData(page, dto);
        } else {
            return pageTradeDataAll(page, dto);
        }
    }


    private Page<MercTradeDataDTO> pageTradeDataAll(Page<MercTradeDataDTO> page, MercTradeDataDTO dto) {

        MerchantBaseInfo mbi = null;
        if (dto.getUserId() != null) {
            mbi = getMerchantBaseInfoByUserId(dto.getUserId().toString());
        }

        Page<MercTradeDataDTO> result = new Page<>(page.getCurrent(), page.getSize());
        result.setRecords(new ArrayList<>());

        Page<MerchantOrderStatistics> page2 = new Page<>(page.getCurrent(), page.getSize());
        if ("tradeSumAmt".equals(dto.getField())) {
            if ("desc".equals(dto.getOrder())) {
                page2.addOrder(OrderItem.desc("totalFee"));
            } else {
                page2.addOrder(OrderItem.asc("totalFee"));
            }
        } else if ("tradeSumNum".equals(dto.getField())) {
            if ("desc".equals(dto.getOrder())) {
                page2.addOrder(OrderItem.desc("count"));
            } else {
                page2.addOrder(OrderItem.asc("count"));
            }
        }

        final QueryWrapper<MerchantOrderStatistics> qWrapper = new QueryWrapper<>();
        qWrapper.eq("startDate", "1970-01-01");
        if (dto.getUserId() != null) {
            qWrapper.eq("merchantCode", mbi.getMerchantCode());
        }

        page2 = mosService.page(page2, qWrapper);

        result.setTotal(page2.getTotal());

        if (page2.getRecords().size() == 0) {
            return result;
        }

        List<String> merchantCodeList = new ArrayList<>();
        for (MerchantOrderStatistics record : page2.getRecords()) {
            MercTradeDataDTO item = new MercTradeDataDTO();
            item.setAmtChain("-");
            item.setNumChain("-");
            item.setMerchantCode(record.getMerchantCode());
            item.setTradeSumAmt(record.getTotalFee());
            item.setTradeSumNum(record.getCount());
            item.setPrevTradeSumNum(0);
            item.setPrevTradeSumAmt(BigDecimal.ZERO);

            result.getRecords().add(item);

            merchantCodeList.add(record.getMerchantCode());
        }

        Long userId = null;
        if (dto.getUserId() != null) {
            userId = dto.getUserId().longValue();
        }
        final List<MercTradeDataDTO> dataList = baseMapper.listMercData(userId, merchantCodeList);

        Set<Long> userIdList = new HashSet<>();

        for (MercTradeDataDTO item : dataList) {
            userIdList.add(item.getUserId().longValue());
            for (MercTradeDataDTO record : result.getRecords()) {
                if (item.getMerchantCode().equals(record.getMerchantCode())) {
                    Converter.INSTANCE.cp(item, record);
                    break;
                }
            }
        }

        final Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_MONTH, -1);
        LambdaQueryWrapper<MerchantBillStatistics> qWrapper3 = Wrappers.lambdaQuery();
        qWrapper3.in(MerchantBillStatistics::getUserId, userIdList);
        qWrapper3.eq(MerchantBillStatistics::getStartDate, DateUtil.format(cal.getTime(), "yyyy-MM-dd"));
        qWrapper3.eq(MerchantBillStatistics::getType,1);
        final List<MerchantBillStatistics> yesterdayData = mbsService.list(qWrapper3);

        for (MerchantBillStatistics item : yesterdayData) {
            for (MercTradeDataDTO record : result.getRecords()) {
                if (item.getUserId().equals(record.getUserId())) {
                    record.setPrevTradeSumAmt(item.getAmount());
                    record.setPrevTradeSumNum(item.getCount());
                    break;
                }
            }
        }

        return result;
    }

    /**
     * 商户活跃度统计
     *
     * @param page:
     * @param dto:
     * @return com.baomidou.mybatisplus.extension.plugins.pagination.Page<cn.pluss.platform.dto.MercActiveDataDTO>
     * @date: 2022/1/7 14:12
     */
    @Override
    public Page<MercActiveDataDTO> pageActiveData(Page<MercActiveDataDTO> page, MercActiveDataDTO dto) {
        return this.baseMapper.pageActiveData(page, dto);
    }

    /**
     * 根据区域和角色查询商户信息
     *
     * @param areaList:
     * @param roleCode:
     * @date: 2022/3/1 16:33
     */
    @Override
    public List<String> getAreaAndRoleList(List<String> areaList, String roleCode) {
        return baseMapper.getAreaAndRoleList(areaList, roleCode);
    }

    /**
     * 查询当前用户直推商户
     * @param userId
     * @return
     */
    @Override
    public List<String> queryNextMercCodeByUserId(Serializable userId) {
        return baseMapper.queryNextMercCodeByUserId(userId);
    }
}

