package com.jeequan.jeepay.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeequan.jeepay.core.constants.ApiCodeEnum;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.entity.SysUser;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.model.DBDefaultConfig;
import com.jeequan.jeepay.core.model.alipay.AlipaySpOperationInfo;
import com.jeequan.jeepay.core.utils.DateKit;
import com.jeequan.jeepay.core.utils.InviteCodeUtil;
import com.jeequan.jeepay.core.utils.SeqKit;
import com.jeequan.jeepay.db.entity.*;
import com.jeequan.jeepay.service.mapper.MchInfoMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 商户信息表 服务实现类
 * </p>
 *
 * @since 2021-04-27
 */
@Service
public class MchInfoService extends ServiceImpl<MchInfoMapper, MchInfo> {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private PayOrderService payOrderService;
    @Autowired
    private MchPayPassageService mchPayPassageService;
    @Autowired
    private PayInterfaceConfigService payInterfaceConfigService;
    @Autowired
    private SysUserAuthService sysUserAuthService;
    @Autowired
    private MchAppService mchAppService;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private MchStoreService mchStoreService;
    @Autowired
    private MchApplymentService mchApplymentService;
    @Autowired
    private AgentInfoService agentInfoService;
    @Autowired
    private InfoAccountService infoAccountService;
    @Autowired
    private MchConfigService mchConfigService;
    @Autowired
    private IsvUserConnService isvUserConnService;
    @Autowired
    private MchInfoMapper mchInfoMapper;

    @Transactional(rollbackFor = Exception.class)
    public void addMch(MchInfo mchInfo, String loginPassword) {

        // 校验特邀商户信息
        if (mchInfo.getType() == CS.MCH_TYPE_ISVSUB && StringUtils.isNotEmpty(mchInfo.getAgentNo())) {
            // 当前服务商状态是否正确
//            IsvInfoEntity isvInfoEntity = isvInfoService.getById(mchInfo.getIsvNo());
//            if (isvInfoEntity == null || isvInfoEntity.getState() == CS.NO) {
//                throw new BizException("当前服务商不可用");
//            }
        }

        if (ObjectUtils.isEmpty(mchInfo.getAgentNo())) {
            DBDefaultConfig dbDefaultConfig = sysConfigService.getDBDefaultConfig();
            mchInfo.setAgentNo(dbDefaultConfig.getDefaultAgentNo());
        }

        // 当前服务商状态是否正确
        if (mchInfo.getType() == CS.MCH_TYPE_ISVSUB && StringUtils.isNotEmpty(mchInfo.getAgentNo())) {
            AgentInfo agentInfo = agentInfoService.getById(mchInfo.getAgentNo());
            if (agentInfo == null || agentInfo.getState() == CS.NO) {
                throw new BizException("当前服务商不可用");
            }

            if (!ObjectUtils.isEmpty(agentInfo.getPidArr())) {
                mchInfo.setAgentNoArr(agentInfo.getAgentNo() + "," + agentInfo.getPidArr());
            } else {
                mchInfo.setAgentNoArr(agentInfo.getAgentNo());
            }

            // 查询当前服务商顶级服务商ID
            String topAgentNo = agentInfoService.queryTopAgentNo(agentInfo.getAgentNo());
            // 存入顶级服务商ID
            mchInfo.setTopAgentNo(topAgentNo);
            //　商户不再存储服务商信息
            // 如果未选择服务商，默认与服务商服务商一致
//            if (StringUtils.isEmpty(mchInfo.getIsvNo())) {
//                mchInfo.setIsvNo(agentInfo.getIsvNo());
//            }
        }

        // 插入商户基本信息
        boolean saveResult = save(mchInfo);
        if (!saveResult) {
            throw new BizException(ApiCodeEnum.SYS_OPERATION_FAIL_CREATE);
        }

        // 插入用户信息
        SysUserEntity sysUserEntity = new SysUserEntity();
        sysUserEntity.setLoginUsername(mchInfo.getLoginUsername());
        sysUserEntity.setRealname(mchInfo.getContactName());
        sysUserEntity.setTelphone(mchInfo.getContactTel());
        sysUserEntity.setUserNo(mchInfo.getMchNo());
        sysUserEntity.setBelongInfoId(mchInfo.getMchNo());
        sysUserEntity.setSex(CS.SEX_MALE);
        sysUserEntity.setUserType(SysUser.UEST_TYPE_ADMIN);
        sysUserEntity.setState(mchInfo.getState());
        sysUserService.addSysUser(sysUserEntity, CS.SYS_ROLE_TYPE.MCH, loginPassword);

        // 插入商户默认应用
        MchAppEntity mchAppEntity = new MchAppEntity();
        mchAppEntity.setAppId(IdUtil.objectId());
        mchAppEntity.setMchNo(mchInfo.getMchNo());
        mchAppEntity.setAgentNo(mchInfo.getAgentNo());
        mchAppEntity.setTopAgentNo(mchInfo.getTopAgentNo());
        mchAppEntity.setAppName("默认应用");
        mchAppEntity.setAppSecret(RandomUtil.randomString(128));
        mchAppEntity.setDefaultFlag(CS.YES);
        mchAppEntity.setState(CS.YES);
        mchAppEntity.setCreatedBy(sysUserEntity.getRealname());
        mchAppEntity.setCreatedUid(sysUserEntity.getSysUserId());
        saveResult = mchAppService.save(mchAppEntity);
        if (!saveResult) {
            throw new BizException(ApiCodeEnum.SYS_OPERATION_FAIL_CREATE);
        }

        // 插入商户的默认配置
        mchConfigService.initConfig(mchInfo.getMchNo());

        // 存入商户默认用户ID
        MchInfo updateRecord = new MchInfo();
        updateRecord.setMchNo(mchInfo.getMchNo());
        updateRecord.setInitUserId(sysUserEntity.getSysUserId());
        saveResult = updateById(updateRecord);
        if (!saveResult) {
            throw new BizException(ApiCodeEnum.SYS_OPERATION_FAIL_CREATE);
        }

        // 初始化账户数据
        infoAccountService.initMchAccount(mchInfo.getMchNo());

        List<IsvUserConnEntity> userConnEntityList = isvUserConnService.getSuperiorConnInfo(CS.SYS_ROLE_TYPE.MCH, mchInfo.getMchNo());
        isvUserConnService.saveBatch(userConnEntityList);
    }

    /**
     * 删除商户
     **/
    @Transactional(rollbackFor = Exception.class)
    public List<Long> removeByMchNo(String mchNo) {
        // 0.当前商户是否存在
        MchInfo mchInfo = getById(mchNo);
        if (mchInfo == null) {
            throw new BizException("该商户不存在");
        }

        // 1.查看当前商户是否存在交易数据
        long payCount = payOrderService.count(PayOrder.gw().eq(PayOrder::getMchNo, mchNo));
        if (payCount > 0) {
            throw new BizException("该商户已存在交易数据，不可删除");
        }

        // 1.1当前商户是否存在进件记录
        long applyMentCount = mchApplymentService.count(MchApplyment.gw().eq(MchApplyment::getMchNo, mchNo));
        if (applyMentCount > 0) {
            throw new BizException("该商户已存在进件信息，不可删除");
        }

        // 2.删除当前商户配置的支付通道
        mchPayPassageService.remove(MchPayPassage.gw().eq(MchPayPassage::getMchNo, mchNo));

        // 3.删除当前商户支付接口配置参数
        List<String> appIdList = new LinkedList<>();
        mchAppService.lambdaQuery().eq(MchAppEntity::getMchNo, mchNo).list().forEach(item -> appIdList.add(item.getAppId()));
        if (CollectionUtils.isNotEmpty(appIdList)) {
            payInterfaceConfigService.remove(PayInterfaceConfig.gw()
                    .in(PayInterfaceConfig::getInfoId, appIdList)
                    .eq(PayInterfaceConfig::getInfoType, CS.SYS_ROLE_TYPE.MCH_APP)
            );
        }

        List<SysUserEntity> userList = sysUserService.list(SysUserEntity.gw()
                .eq(SysUserEntity::getBelongInfoId, mchNo)
                .eq(SysUserEntity::getSysType, CS.SYS_ROLE_TYPE.MCH)
        );

        // 4.删除当前商户应用信息
        if (CollectionUtils.isNotEmpty(appIdList)) {
            mchAppService.removeByIds(appIdList);
        }

        // 返回的用户id
        List<Long> userIdList = new ArrayList<>();
        for (SysUserEntity user : userList) {
            userIdList.add(user.getSysUserId());
        }

        if (CollectionUtils.isNotEmpty(userIdList)) {
            // 5.删除当前商户用户子用户信息
            sysUserAuthService.remove(SysUserAuth.gw().in(SysUserAuth::getUserId, userIdList));
        }

        // 6.删除当前商户的登录用户
        sysUserService.remove(SysUserEntity.gw()
                .eq(SysUserEntity::getBelongInfoId, mchNo)
                .eq(SysUserEntity::getSysType, CS.SYS_ROLE_TYPE.MCH)
        );

        // 删除门店
        List<MchStore> mchStores = mchStoreService.list(MchStore.gw().eq(MchStore::getMchNo, mchNo));
        for (MchStore mchStore : mchStores) {
            mchStoreService.deleteStore(mchStore.getStoreId(), true);
        }

        // 7.删除当前商户
        boolean removeMchInfo = removeById(mchNo);
        if (!removeMchInfo) {
            throw new BizException("删除当前商户失败");
        }
        return userIdList;
    }

    /**
     * 商户注册
     **/
    @Transactional(rollbackFor = Exception.class)
    public void mchRegister(String mchName, String phone, String loginPassword, Byte mchType, String inviteCode) {

        String isvNo = null; // 服务商号
        String agentNo = null; // 服务商号
        Long inviteSysUserId = null; // 商户邀请者ID
        String inviteRealName = null; // 商户邀请者姓名

        // 判断是否邀请码必填
        SysConfig sysConfig = sysConfigService.getById("mchRegisterInviteCodeRequired");

        if (sysConfig != null && "1".equals(sysConfig.getConfigVal()) && StringUtils.isBlank(inviteCode)) {
            throw new BizException("请填写邀请码");
        }

        // 邀请者信息
        if (StringUtils.isNotBlank(inviteCode)) {
            SysUserEntity sysUserEntity = sysUserService.getById(InviteCodeUtil.codeToId(inviteCode));
            if (sysUserEntity == null) {
                throw new BizException("邀请码错误");
            }
            // 服务商信息
            if (sysUserEntity.getSysType().equals(CS.SYS_ROLE_TYPE.AGENT)) {
                agentNo = sysUserEntity.getBelongInfoId();

                // 服务商信息
                AgentInfo agentInfo = agentInfoService.getById(sysUserEntity.getBelongInfoId());
                if (agentInfo == null) {
                    throw new BizException("邀请码错误");
                }
                // 服务商是否允许发展下级商户
                if (agentInfo.getAddMchFlag() != CS.YES) {
                    throw new BizException("无效服务商[所填邀请码不可用]");
                }
                isvNo = agentInfo.getIsvNo();
            }
            inviteSysUserId = sysUserEntity.getSysUserId();
            inviteRealName = sysUserEntity.getRealname();
        }

        // 注册商户类型 特约商户/普通商户
        if (MchInfo.TYPE_ISVSUB == mchType && StringUtils.isBlank(isvNo)) {
            JSONObject defaultIsvJson = sysConfigService.selectByGroupKey("defaultConfig");
            if (defaultIsvJson == null) {
                throw new BizException("平台未配置服务商");
            }
            isvNo = defaultIsvJson.getString("defaultIsvNo");
            if (StringUtils.isEmpty(isvNo)) {
                throw new BizException("平台未配置默认服务商");
            }
        }

        // 参数校验
        if (StringUtils.isEmpty(mchName)) {
            throw new BizException("商户名称不能为空");
        }
        if (StringUtils.isEmpty(phone)) {
            throw new BizException("手机号不能为空");
        }
        if (StringUtils.isEmpty(loginPassword)) {
            throw new BizException("密码不能为空");
        }

        // 注册商户信息
        MchInfo mchInfo = new MchInfo();
        // 商户状态 默认启用
        mchInfo.setState(CS.YES);
        // 商户名称
        mchInfo.setMchName(mchName);
        // 商户简称
        mchInfo.setMchShortName(mchName);
        // 联系人电话
        mchInfo.setContactTel(phone);
        // 联系人姓名
        mchInfo.setContactName(mchName);
        // 服务商ID
//        mchInfo.setIsvNo(isvNo);
        // 服务商号
        mchInfo.setAgentNo(agentNo);
        // 商户类型
        mchInfo.setType(mchType);
        // 商户号
        mchInfo.setMchNo(SeqKit.genMchNo());

        // 登录用户名
        mchInfo.setLoginUsername("m" + phone);

        // 商户退款权限
        JSONArray refundModeArray = new JSONArray();
        refundModeArray.add(MchInfo.REFUND_MODEL_PLAT);
        refundModeArray.add(MchInfo.REFUND_MODEL_API);
        mchInfo.setRefundMode(refundModeArray);

        // 默认商户级别
        SysConfig sysConfigByDefLevel = sysConfigService.getById("mchRegisterLevel");
        if (sysConfigByDefLevel != null && StringUtils.isNotEmpty(sysConfigByDefLevel.getConfigVal())) {
            mchInfo.setMchLevel(sysConfigByDefLevel.getConfigVal());
        }

        // 创建者/邀请者信息
        mchInfo.setCreatedUid(inviteSysUserId);
        mchInfo.setCreatedBy(inviteRealName);

        // 新增商户
        addMch(mchInfo, loginPassword);
    }

    public JSONObject mchCount(String agentNo, List<String> agentSubList, JSONObject paramJSON) {
        String dateRange = paramJSON.getString("queryDateRange");
        String epUserId = paramJSON.getString("epUserId");
        String isQueryAll = (String) paramJSON.getOrDefault("isQueryAll", "");
        String createdStart = null;
        String createdEnd = null;

        if (StringUtils.isEmpty(isQueryAll)) {
            // 获取查询时间请求参数  [开始时间,  结束时间]
            Date[] queryDateRangeArray = DateKit.getQueryDateRange(dateRange);
            if (StringUtils.isEmpty(dateRange)) {   // 如果未传入参数默认为当天
                // 今日时间范围
                queryDateRangeArray = DateKit.getQueryDateRange("today");
            }

            createdStart = DateUtil.formatDateTime(queryDateRangeArray[0]);
            createdEnd = DateUtil.formatDateTime(queryDateRangeArray[1]);
        }

        JSONObject result = new JSONObject();

        // 商户总数
        LambdaQueryWrapper<MchInfo> gwMchAllCount = MchInfo.gw();
        gwMchAllCount.eq(StringUtils.isNotEmpty(agentNo), MchInfo::getAgentNo, agentNo);
        gwMchAllCount.eq(StringUtils.isNotEmpty(epUserId), MchInfo::getCreatedUid, epUserId);
        if (CollUtil.isNotEmpty(agentSubList)) {
            gwMchAllCount.in(MchInfo::getAgentNo, agentSubList);
        }

        long mchAllCount = count(gwMchAllCount);

        result.put("mchAllCount", mchAllCount);

        // 新增商户
        LambdaQueryWrapper<MchInfo> gwMchTodayAddCount = MchInfo.gw();
        gwMchTodayAddCount.eq(StringUtils.isNotEmpty(agentNo), MchInfo::getAgentNo, agentNo);
        gwMchTodayAddCount.eq(StringUtils.isNotEmpty(epUserId), MchInfo::getCreatedUid, epUserId);
        gwMchTodayAddCount.ge(StringUtils.isNotEmpty(createdStart), MchInfo::getCreatedAt, createdStart);
        gwMchTodayAddCount.le(StringUtils.isNotEmpty(createdEnd), MchInfo::getCreatedAt, createdEnd);
        if (CollUtil.isNotEmpty(agentSubList)) {
            gwMchTodayAddCount.in(MchInfo::getAgentNo, agentSubList);
        }

        long mchTodayAddCount = count(gwMchTodayAddCount);
        result.put("mchTodayAddCount", mchTodayAddCount);

        // 入网商户数
        LambdaQueryWrapper<MchApplyment> gwMchOnNetCount = MchApplyment.gw();
        gwMchOnNetCount.select(MchApplyment::getMchNo);
        gwMchOnNetCount.eq(StringUtils.isNotEmpty(agentNo), MchApplyment::getAgentNo, agentNo);
        gwMchOnNetCount.eq(StringUtils.isNotEmpty(epUserId), MchApplyment::getEpUserId, epUserId);
        gwMchOnNetCount.ge(StringUtils.isNotEmpty(createdStart), MchApplyment::getCreatedAt, createdStart);
        gwMchOnNetCount.le(StringUtils.isNotEmpty(createdEnd), MchApplyment::getCreatedAt, createdEnd);
        gwMchOnNetCount.groupBy(MchApplyment::getMchNo);
        if (CollUtil.isNotEmpty(agentSubList)) {
            gwMchOnNetCount.in(MchApplyment::getAgentNo, agentSubList);
        }

        List<MchApplyment> applymentOnNetList = mchApplymentService.list(gwMchOnNetCount);
        Integer mchOnNetCount = applymentOnNetList.size();
        result.put("mchOnNetCount", mchOnNetCount);

        // 新增商户入网数
        LambdaQueryWrapper<MchApplyment> gwMchOnNetNewCount = MchApplyment.gw();
        gwMchOnNetNewCount.select(MchApplyment::getMchNo);
        gwMchOnNetNewCount.eq(StringUtils.isNotEmpty(agentNo), MchApplyment::getAgentNo, agentNo);
        gwMchOnNetNewCount.eq(StringUtils.isNotEmpty(epUserId), MchApplyment::getEpUserId, epUserId);
        gwMchOnNetNewCount.eq(MchApplyment::getState, MchApplyment.STATE_SUCCESS);
        gwMchOnNetNewCount.ge(StringUtils.isNotEmpty(createdStart), MchApplyment::getCreatedAt, createdStart);
        gwMchOnNetNewCount.le(StringUtils.isNotEmpty(createdEnd), MchApplyment::getCreatedAt, createdEnd);
        gwMchOnNetNewCount.groupBy(MchApplyment::getMchNo);
        if (CollUtil.isNotEmpty(agentSubList)) {
            gwMchOnNetNewCount.in(MchApplyment::getAgentNo, agentSubList);
        }

        List<MchApplyment> applymentOnNetNewList = mchApplymentService.list(gwMchOnNetNewCount);
        Integer mchOnNetNewCount = applymentOnNetNewList.size();
        result.put("mchOnNetNewCount", mchOnNetNewCount);
        // 入网失败商户
        result.put("mchOnNetFailCount", mchOnNetCount - mchOnNetNewCount);
        return result;

    }

    /**
     * 商户数
     */
    public long mchCount(String agentNo, Long sysUserId, String createdStart, String createdEnd) {

        LambdaQueryWrapper<MchInfo> wrapper = MchInfo.gw();
        if (StringUtils.isNotBlank(agentNo)) wrapper.eq(MchInfo::getAgentNo, agentNo); // 服务商号
        if (sysUserId != null) wrapper.eq(MchInfo::getCreatedUid, sysUserId); // 商户创建者/邀请者
        if (StringUtils.isNotBlank(createdStart)) wrapper.ge(MchInfo::getCreatedAt, createdStart); // 开始时间
        if (StringUtils.isNotBlank(createdEnd)) wrapper.le(MchInfo::getCreatedAt, createdEnd); // 结束时间

        return count(wrapper);
    }

    /**
     * 入网商户数
     */
    public long mchApplyCount(String agentNo, Long sysUserId, String createdStart, String createdEnd) {

        LambdaQueryWrapper<MchApplyment> wrapper = MchApplyment.gw();
        wrapper.eq(StringUtils.isNotBlank(agentNo), MchApplyment::getAgentNo, agentNo); // 服务商号
        wrapper.eq(sysUserId != null, MchApplyment::getEpUserId, sysUserId); // 拓展员ID
        wrapper.ge(StringUtils.isNotBlank(createdStart), MchApplyment::getCreatedAt, createdStart); // 开始时间
        wrapper.le(StringUtils.isNotBlank(createdEnd), MchApplyment::getCreatedAt, createdEnd); // 结束时间

        return mchApplymentService.count(wrapper);
    }

    /**
     * 更新商户信息， 返回需要清除登录信息的userIdSet
     **/
    @Transactional
    public Set<Long> updateMch(MchInfo updateMchInfo, boolean resetPass, String confirmPwd) {

        // 待删除用户登录信息的ID list
        Set<Long> removeCacheUserIdList = new HashSet<>();

        // 如果商户状态为禁用状态，清除该商户用户登录信息
        if (updateMchInfo.getState() != null && updateMchInfo.getState() != CS.YES) {
            sysUserService.list(SysUserEntity.gw().select(SysUserEntity::getSysUserId).eq(SysUserEntity::getBelongInfoId, updateMchInfo.getMchNo()).eq(SysUserEntity::getSysType, CS.SYS_ROLE_TYPE.MCH)).forEach(u -> removeCacheUserIdList.add(u.getSysUserId()));
        }

        // 获取商户超管
        Long mchAdminUserId = sysUserService.findMchAdminUserId(updateMchInfo.getMchNo());


        //判断是否重置密码
        if (resetPass) {

            //删除超管登录信息
            removeCacheUserIdList.add(mchAdminUserId);

        }

        //重置超管 手机号 & 密码
        sysUserService.resetUserAndAuthInfo(mchAdminUserId, null, updateMchInfo.getContactTel(), resetPass, confirmPwd, CS.SYS_ROLE_TYPE.MCH);

        //更新商户信息
        if (!updateById(updateMchInfo)) {
            throw new BizException(ApiCodeEnum.SYS_OPERATION_FAIL_UPDATE);
        }

        return removeCacheUserIdList;
    }

    // 保存或更新支付宝服务商代运营授权商户信息
    public void saveOrUpdateAlipaySpOperationAccount(String currentMchNo, String alipayAccount, String authType) {
        MchConfig updateRecord = new MchConfig();
        updateRecord.setMchNo(currentMchNo);
        updateRecord.setConfigKey(AlipaySpOperationInfo.MCH_CONFIG_KEY);

        AlipaySpOperationInfo alipaySpOperationInfo = new AlipaySpOperationInfo();
        alipaySpOperationInfo.setAlipayAccount(alipayAccount);
        alipaySpOperationInfo.setAuthType(authType);
        updateRecord.setConfigVal(JSONObject.toJSONString(alipaySpOperationInfo));

        // 从商户配置表 查询当前商户支付宝授权信息
        MchConfig mchConfig = mchConfigService.getByMchNoAndConfigKey(currentMchNo, AlipaySpOperationInfo.MCH_CONFIG_KEY);

        // 首次授权，保存配置信息
        if (mchConfig == null) {
            updateRecord.setConfigName("支付宝服务商代运营授权的商户信息");
            updateRecord.setGroupKey(AlipaySpOperationInfo.MCH_CONFIG_KEY);
        }

        int count = mchConfigService.saveOrUpdateConfig(updateRecord);
        if (count != 1) {
            throw new BizException(ApiCodeEnum.SYS_OPERATION_FAIL_CREATE);
        }
    }

    public List<Map<String, String>> getDefIsv(String mchNo, String ifCode) {
        return mchConfigService.lambdaQuery()
                .eq(MchConfig::getMchNo, mchNo)
                .eq(MchConfig::getGroupKey, "applymentConfig")
                .eq(!ObjectUtils.isEmpty(ifCode), MchConfig::getConfigKey, MchConfig.getDefIsvKey(ifCode))
                .list().stream().map(r -> {
                    Map<String, String> item = new HashMap<>();
                    item.put(r.getConfigKey(), r.getConfigVal());
                    return item;
                }).collect(Collectors.toList());
    }

    public void setDefIsv(String mchNo, String ifCode, String isvNo) {
        Assert.notNull(ifCode, "通道编码[ifCode]不能为空");
        Assert.notNull(mchNo, "用户号[mchNo]不能为空");

        IsvUserConnEntity isvUserConn = isvUserConnService.lambdaQuery()
                .eq(IsvUserConnEntity::getIsvNo, isvNo)
                .eq(IsvUserConnEntity::getInfoType, CS.SYS_ROLE_TYPE.MCH)
                .eq(IsvUserConnEntity::getInfoId, mchNo)
                .one();

        Assert.notNull(isvUserConn, "当前商户与所选渠道不存在关联关系");

        List<MchConfig> applymentConfigList = mchConfigService.lambdaQuery()
                .eq(MchConfig::getMchNo, mchNo)
                .eq(MchConfig::getGroupKey, "applymentConfig")
                .eq(MchConfig::getConfigKey, MchConfig.getDefIsvKey(ifCode))
                .list();
    }

    public Page<MchInfo> getListPage(Page<MchInfo> page,MchInfo mchInfo){
        // 时间搜索
        Date[] searchDateRange = mchInfo.buildQueryDateRange();
        if(searchDateRange[0] != null){
            mchInfo.setFirstDate(searchDateRange[0]);
        }
        if(searchDateRange[1] != null){
            mchInfo.setLastDate(searchDateRange[1]);
        }
        Page<MchInfo> listPage = mchInfoMapper.getListPage(page, mchInfo);
        // 数据脱敏
        if (!listPage.getRecords().isEmpty()){
            for (MchInfo record : listPage.getRecords()) {
                //手机号脱敏
                if (StringUtils.isNotEmpty(record.getMchServicePhone())){
                    record.setMchServicePhone(DesensitizedUtil.mobilePhone(record.getMchServicePhone()));
                }
                if (StringUtils.isNotEmpty(record.getContactTel())){
                    record.setContactTel(DesensitizedUtil.mobilePhone(record.getContactTel()));
                }
            }
        }
        return listPage;
    }
}
