package cn.pluss.platform.userApp.impl;

import cn.pluss.platform.IdCardService;
import cn.pluss.platform.ali.AliService;
import cn.pluss.platform.api.PageInfo;
import cn.pluss.platform.api.Result;
import cn.pluss.platform.api.ResultGenerator;
import cn.pluss.platform.channel.BaseMerchantAuditService;
import cn.pluss.platform.channel.MerchantAuditService;
import cn.pluss.platform.channel.ys.YSAuditServiceV3;
import cn.pluss.platform.common.CommonRemarkService;
import cn.pluss.platform.common.RiskBlacklistService;
import cn.pluss.platform.converter.Converter;
import cn.pluss.platform.converter.UserAppConverter;
import cn.pluss.platform.dto.AccountDTO;
import cn.pluss.platform.dto.MerchSearchDTO;
import cn.pluss.platform.dto.MerchantFeeDTO;
import cn.pluss.platform.dto.StaffDTO;
import cn.pluss.platform.entity.*;
import cn.pluss.platform.enums.UserRoleEnum;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.jfShop.JfShopHandler;
import cn.pluss.platform.leshua.BizConstants;
import cn.pluss.platform.leshua.ExpandDto;
import cn.pluss.platform.mapper.*;
import cn.pluss.platform.merchant.AccountService;
import cn.pluss.platform.merchant.MerchantBaseInfoService;
import cn.pluss.platform.merchant.MerchantStaffConnService;
import cn.pluss.platform.merchant.StaffPermissionService;
import cn.pluss.platform.merchantChannel.MerchantChannelService;
import cn.pluss.platform.merchantChannelStatus.MerchantChannelStatusService;
import cn.pluss.platform.merchantIncome.MerchantIncomeService;
import cn.pluss.platform.merchantStore.MerchantStoreService;
import cn.pluss.platform.notice.NoticeService;
import cn.pluss.platform.phoneValidateCode.PhoneValidateCodeService;
import cn.pluss.platform.roleUserInfo.RoleUserInfoService;
import cn.pluss.platform.systemConfig.SystemConfigService;
import cn.pluss.platform.user.UserIpRecordService;
import cn.pluss.platform.user.impl.GeneralPushUtil;
import cn.pluss.platform.userApp.UserAppService;
import cn.pluss.platform.userInfo.UserInfoService;
import cn.pluss.platform.util.*;
import cn.pluss.platform.vo.*;
import cn.pluss.platform.wechat.WechatService;
import cn.pluss.platform.wx.WxTalkService;
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.metadata.IPage;
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.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
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.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * @author djh
 */
@Slf4j
@Service("userAppService")
@RequiredArgsConstructor
public class UserAppServiceImpl extends ServiceImpl<UserAppMapper, UserApp> implements UserAppService {

    @Setter(onMethod_ = {@Autowired})
    private MerchantChannelService channelService;

    @Setter(onMethod_ = {@Autowired})
    private MerchantBaseInfoMapper baseInfoMapper;

    @Setter(onMethod_ = {@Autowired})
    private MerchantIncomeService merchantIncomeService;

    @Setter(onMethod_ = {@Autowired})
    private MerchantProfitMapper profitMapper;

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

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

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

    @Setter(onMethod_ = {@Autowired})
    private MerchantBaseInfoService mbiService;

    @Setter(onMethod_ = {@Autowired})
    private MerchantChannelStatusService mcsService;

    @Setter(onMethod_ = {@Autowired, @Lazy})
    private AliService aliService;

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

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

    @Setter(onMethod_ = {@Autowired})
    private WechatService wechatService;

    @Setter(onMethod_ = {@Autowired, @Qualifier("sxfMerchantAuditService")})
    private MerchantAuditService sxfMerchantAuditService;

    @Setter(onMethod_ = {@Autowired, @Qualifier("leshuaMerchantAuditService")})
    private MerchantAuditService leshuaMerchantAuditService;

    @Setter(onMethod_ = {@Autowired, @Qualifier("ryxMerchantAuditService")})
    private MerchantAuditService ryxMerchantAuditService;

    @Setter(onMethod_ = {@Autowired, @Qualifier("ysAuditServiceV2")})
    private MerchantAuditService ysAuditServiceV2;

    @Setter(onMethod_ = {@Autowired, @Qualifier("ysAuditService")})
    private MerchantAuditService ysAuditService;

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

    @Setter(onMethod_ = {@Autowired, @Lazy})
    private WxTalkService wxTalkService;

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

    @Setter(onMethod_ = {@Lazy, @Autowired})
    private NoticeService noticeService;

    @Setter(onMethod_ = {@Lazy, @Autowired})
    private PhoneValidateCodeService phoneValidateCodeService;

    @Setter(onMethod_ = {@Autowired})
    private MerchantStaffConnService staffConnService;

    @Setter(onMethod_ = {@Autowired})
    private StaffPermissionService staffPermissionService;

    @Setter(onMethod_ = {@Autowired})
    private CommonRemarkService remarkService;

    @Autowired
    private UserIpRecordService ipRecordService;

    @Setter(onMethod_ = {@Autowired, @Lazy})
    private RiskBlacklistService blacklistService;

    @Setter(onMethod_ = {@Autowired, @Lazy})
    private JfShopHandler jfShopHandler;

    @Autowired
    private GeneralPushUtil generalPushUtil;

    @Autowired
    private UserAssessMapper userAssessMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private YSAuditServiceV3 ysAuditServiceV3;


    @Override
    public Map<String, Object> getUserByUid(String userIds) {
        String[] userIdArr = userIds.replace("，", ",").split(",");
        List<String> userNameList = new ArrayList<>();
        List<String> parentNameList = new ArrayList<>();
        List<String> aliasList = new ArrayList<>();
        List<String> userIdList = new ArrayList<>();
        List<String> parentIdsList = new ArrayList<>();
        int i = 1;
        String fastName = "";
        for (String uid : userIdArr) {
            MerchantBaseInfo baseInfo = mbiService.getMerchantBaseInfoByUserId(uid);
            if (baseInfo == null) {
                MerchantChannelStatus channel = mcsService.getChannelByMerchantId(uid);
                if (channel != null) {
                    baseInfo = mbiService.getMerchantBaseInfoByMerchantCode(channel.getMerchantCode());
                }
            }

            if (baseInfo != null) {
                if (i == 1) {
                    fastName = baseInfo.getAlias();
                }
                aliasList.add(baseInfo.getAlias());
            }

            UserApp userApp = baseMapper.selectOne(new QueryWrapper<UserApp>().eq("userId", uid));
            MsgException.checkNull(userApp, "未查询到相关用户信息");
            UserAppConverter.INSTANCE.copyProperties(baseInfo, userApp);
            userNameList.add(userApp.getUserName());
            userIdList.add(uid);
            parentIdsList.add(userApp.getParentId() + "");
            if (userApp.getParentId() != null) {
                UserApp parentUserApp = new UserApp();
                parentUserApp.setUserId(userApp.getParentId());
                parentUserApp = queryUserApp(parentUserApp);
                parentNameList.add(parentUserApp.getUserName());
            }
            i++;
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("userName", StringUtils.join(userNameList, ","));
        resultMap.put("parentName", StringUtils.join(parentNameList, ","));
        resultMap.put("alias", StringUtils.join(aliasList, ","));
        resultMap.put("fastName", fastName);
        resultMap.put("userIds", StringUtils.join(userIdList, ","));
        resultMap.put("parentIds", StringUtils.join(parentIdsList, ","));

        return resultMap;
    }

    @Override
    @SuppressWarnings("unchecked")
    public Page<UserInfoVO> queryUserInfoVOPage(Map<String, Object> map) {
        List<List<?>> queryResult = baseMapper.queryUserInfoVOPage(map);
        List<UserInfoVO> result = (List<UserInfoVO>) queryResult.get(0);

        long page = ((Integer) map.get("offset")).longValue() + 1L;
        long pageSize = ((Integer) map.get("pageSize")).longValue();
        Page<UserInfoVO> pageResult = new Page<>(page, pageSize);
        pageResult.setRecords(result);
        Long count = (Long) queryResult.get(1).get(0);
        pageResult.setTotal(count);

        if (result.isEmpty()) {
            return pageResult;
        }
        List<String> merchantCodeList = new ArrayList<>();
        for (UserInfoVO userInfoVO : result) {
            merchantCodeList.add(userInfoVO.getMerchantCode() + "");
        }

        List<MerchantChannelStatusVO> channelStatusList = mcsService.listByMerchantCodeList(merchantCodeList);

        Map<String, Integer> mapMerchantId = new HashMap<>();

        for (UserInfoVO userInfoVO : result) {
            List<MerchantChannelStatus> statusList = userInfoVO.getChannelStatusList();
            if (statusList == null) {
                statusList = new ArrayList<>();
                userInfoVO.setChannelStatusList(statusList);
            }

            Iterator<MerchantChannelStatusVO> iterator = channelStatusList.iterator();
            while (iterator.hasNext()) {
                MerchantChannelStatusVO item = iterator.next();
                if (item.getMerchantCode().equals(userInfoVO.getMerchantCode())) {
                    if (!mapMerchantId.containsKey(item.getChannel() + item.getMerchantId() + item.getMerchantCode())) {
                        statusList.add(item);
                        mapMerchantId.put(item.getChannel() + item.getMerchantId() + item.getMerchantCode(), 1);
                    }

                    if (Objects.equals(4, item.getChannel())) {
                        if (userInfoVO.getWxMercNoD0() == null) {
                            userInfoVO.setWxMercNoD0(item.getWxMercNo());
                        } else {
                            userInfoVO.setWxMercNoD0(userInfoVO.getWxMercNoD0() + " / " + item.getWxMercNo());
                        }

                        if (userInfoVO.getZfbMercNoD0() == null) {
                            userInfoVO.setZfbMercNoD0(item.getZfbMercNo());
                        } else {
                            userInfoVO.setZfbMercNoD0(userInfoVO.getZfbMercNoD0() + " / " + item.getWxMercNo());
                        }
                    } else {
                        userInfoVO.setWxMercNoD1(item.getWxMercNo());
                        userInfoVO.setZfbMercNoD1(item.getZfbMercNo());
                    }

                    iterator.remove();
                }
            }
        }

        return pageResult;
    }

    @Override
    public Result<Map<String, Object>> saveStaff(StaffDTO staffDTO) {
        Map<String, Object> result = new HashMap<>(16);
        try {
            if (staffDTO.getId() != null && staffDTO.getId() != 0) {
                UserInfo userInfo = new UserInfo();
                UserApp userApp = staffDTO.convert();
                UserApp userAppl = new UserApp();
                userAppl.setId(staffDTO.getId());
                UserApp queryUserApp = baseMapper.selectOne(new QueryWrapper<>(userAppl));
                userInfo.setId(queryUserApp.getUserId());
                userInfo = userInfoService.queryUserInfo(userInfo);
                userInfo.setTrueName(userApp.getUserName());
                userInfo.setPhone(userApp.getPhone());
                userInfo.setPassword(MD5Util.MD5Encode(userApp.getPassword(), BizConstants.CHARSET_UTF8));
                userInfoService.updateUserInfo(userInfo);
                userApp.setId(staffDTO.getId());
                baseMapper.updateById(userApp);
                result.put("code", "1");
                result.put("msg", "修改成功");
                log.debug("修改员工成功");
            } else {
                MerchantStore merchantStore = new MerchantStore();
                merchantStore.setStoreId(staffDTO.getStoreId());
                MerchantStore queryMerchantStore = merchantStoreService.queryMerchantStore(merchantStore);
                staffDTO.setMerchantCode(queryMerchantStore.getMerchantCode());
                staffDTO.setMerchantName(queryMerchantStore.getMerchantName());
                staffDTO.setStoreId(queryMerchantStore.getStoreId());
                staffDTO.setStoreName(queryMerchantStore.getStoreName());
                staffDTO.setLoginName(staffDTO.getLoginName() + "@shouyin");
                if (!staffDTO.getPassword().equals(staffDTO.getVerifyPassword())) {
                    result.put("code", "0");
                    result.put("msg", "两次输入的密码不一致");
                    return ResultGenerator.genFailResult("两次输入的密码不一致", result);
                }
                UserApp userApp = staffDTO.convert();
                UserInfo userInfo = new UserInfo();
                userInfo.setLoginName(userApp.getLoginName());
                List<UserInfo> queryUserInfoList = userInfoService.queryUserInfoList(userInfo);
                if (queryUserInfoList != null && !queryUserInfoList.isEmpty()) {
                    result.put("code", "0");
                    result.put("msg", "账号已存在");
                    return ResultGenerator.genFailResult("账号已存在", result);
                }
                userInfo.setTrueName(userApp.getUserName());
                userInfo.setPhone(userApp.getPhone());
                userInfo.setPassword(MD5Util.MD5Encode(userApp.getPassword(), "utf-8"));
                userInfoService.saveUserInfo(userInfo);
                userApp.setUserType("staff");
                userApp.setUserId(userInfo.getId());
                userApp.setCreateDt(new Date());
                baseMapper.insert(userApp);
                result.put("code", "1");
                result.put("msg", "添加成功");
                log.debug("添加员工成功");
            }
            return ResultGenerator.genSuccessResult(result);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            log.error("添加失败");
            result.put("code", "0");
            result.put("msg", "添加失败");
            return ResultGenerator.genFailResult("添加失败", result);
        }
    }

    @Override
    public Result<Map<String, Object>> deleteStaff(Long id) {
        Map<String, Object> result = new HashMap<>(16);
        try {
            UserApp userApp = new UserApp();
            userApp.setId(id);
            UserApp queryUserApp = baseMapper.selectById(id);
            Long userId = queryUserApp.getUserId();
            baseMapper.deleteById(id);
            userInfoService.removeById(userId);
            result.put("code", "1");
            result.put("msg", "删除成功");
            return ResultGenerator.genSuccessResult(result);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            result.put("code", "0");
            result.put("msg", "删除失败");
            return ResultGenerator.genFailResult("删除失败", result);
        }
    }

    @Override
    public UserApp queryUserAppByToken() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("token");
        String merchantCode = request.getHeader("merchantCode");
        UserApp userApp = new UserApp();
        userApp.setToken(token);

        if (token == null) {
            throw new MsgException("缺少商户信息");
        }

        QueryWrapper<Object> queryWrapper = new QueryWrapper<>()
                .eq("ua.token", token)
                .and(StringUtils.isNotBlank(merchantCode), i -> i.in("ua.userType", "promoter", "agent").or()
                        .eq("msc.merchantCode", merchantCode));

        userApp = baseMapper.selectUserApp(queryWrapper);

        if (userApp == null) {
            throw new MsgException("用户不存在");
        }

        if ("staff".equals(userApp.getUserType())) {
            if (StringUtils.isNotBlank(merchantCode)) {
                MerchantStaffConn staffConn = new MerchantStaffConn();
                staffConn.setUserId(userApp.getUserId());
                staffConn.setMerchantCode(merchantCode);
                staffConn = staffConnService.getOne(new QueryWrapper<>(staffConn));
                if (staffConn != null) {
                    userApp.setMerchantCode(merchantCode);
                }
            } else {
                MerchantStaffConn staffConn = new MerchantStaffConn();
                staffConn.setUserId(userApp.getUserId());

                QueryWrapper<MerchantStaffConn> qWrapper = new QueryWrapper<>(staffConn);
                qWrapper.last("limit 1");
                staffConn = staffConnService.getOne(qWrapper);
                userApp.setMerchantCode(staffConn.getMerchantCode());
            }
        }

        return userApp;
    }

    @Override
    public Map<String, Object> expandMerchantList(ExpandDto dto) {
        if (StringUtil.isEmpty(dto.getUserId())) {
            throw new MsgException("请先登录账号");
        }

        if (StringUtil.isEmpty(dto.getType())) {
            throw new MsgException("请传实名类型");
        }

        UserApp userApp = new UserApp().setUserId(Long.parseLong(dto.getUserId()));
        userApp = queryUserApp(userApp);
        if ("agent_staff".equals(userApp.getUserType())) {
            dto.setAgentStaffId(dto.getUserId());
            dto.setUserId(userApp.getParentId() + "'");
            dto.setRecommend("1");
        }

        if ("agent".equals(userApp.getUserType())) {
            dto.setRecommend("1");
        }

        List<String> parentIdList = getParentIdByRecommendType(dto.getRecommend(), dto.getUserId(), null);
        if (parentIdList.isEmpty()) {
            parentIdList.add("99999999999999999999999");
        }

        // 此处需要加通道判断
        IPage<UserApp> page = new Page<>(dto.getPage(), dto.getSize());
        IPage<UserApp> pageUserApp = baseMapper.getExPageUserApp(page, dto, parentIdList);
        // 返回参数
        Map<String, Object> result = new HashMap<>(16);
        PageInfo<UserApp> pager = PageUtils.page(pageUserApp);
        result.put("pager", pager);

        return result;
    }

    @Override
    public Map<String, Object> queryAllMerchantFee(String userId, String merchantUserId) {
        // 商户的下级代理商数量
        int subClientCount;
        // 本月流水
        BigDecimal agentMonthMoney = BigDecimal.ZERO;
        // 总流水
        BigDecimal agentTotalMoney = BigDecimal.ZERO;
        // 本月分润
        BigDecimal agentMonthProfit = BigDecimal.ZERO;
        // 总分润
        BigDecimal agentTotalProfit = BigDecimal.ZERO;
        // 商户信息列表
        List<Map<String, Object>> merchantBillList = new ArrayList<>();
        // 商户信息Map, 用于对商户信息进行查询和收集
        Map<String, Map<String, Object>> map = new HashMap<>();
        Map<String, Object> agentMap = new HashMap<>();
        Map<String, Object> resultMap = new HashMap<>();
        agentMap.put("parentId", merchantUserId);
        subClientCount = baseMapper.queryUserAppPageCountByPhone(agentMap);

        // 1、查询所有的店铺
        List<MerchantBaseInfo> merchantBaseInfos = baseInfoMapper.queryMerchantListByUserId(merchantUserId);
        if (merchantBaseInfos.isEmpty()) {
            merchantBaseInfos = baseInfoMapper.selectListByUserId(merchantUserId);
        }
        if (!merchantBaseInfos.isEmpty()) {
            List<String> merchantCodeList = new ArrayList<>();
            for (MerchantBaseInfo merchantBaseInfo : merchantBaseInfos) {
                merchantCodeList.add(merchantBaseInfo.getMerchantCode());
                Map<String, Object> merchantData = new HashMap<>();
                // 流水默认初始化为0
                merchantData.put("alias", merchantBaseInfo.getAlias());
                merchantData.put("merchantCode", merchantBaseInfo.getMerchantCode());
                merchantData.put("merchantMonthMoney", BigDecimal.ZERO);
                merchantData.put("merchantTotalMoney", BigDecimal.ZERO);
                merchantBillList.add(merchantData);
                map.put(merchantBaseInfo.getMerchantCode(), merchantData);
            }

            // 2、查询所有店铺当前当月的流水及分润
            Date startDate = DateUtils.getBeginDayOfMonth();
            Date endDate = DateUtils.getEndDayOfMonth();

            UserApp userApp = new UserApp().setUserId(Long.parseLong(userId));
            userApp = queryUserApp(userApp);
            if (userApp.getUserType().equals("agent_staff")) {
                userId = userApp.getParentId() + "";
            }
            List<MerchantFeeDTO> monthBillInfoList = profitMapper.queryMerchantBillWithProfit(userId, merchantCodeList, startDate, endDate);
            // 3、查询所有店铺所有流水及分润
            List<MerchantFeeDTO> totalBillInfoList = profitMapper.queryMerchantBillWithProfit(userId, merchantCodeList, null, null);

            // 对需要的数据进行统计
            for (MerchantFeeDTO merchantFeeDTO : monthBillInfoList) {
                // 总计
                agentMonthMoney = agentMonthMoney.add(merchantFeeDTO.getMoney());
                agentMonthProfit = agentMonthProfit.add(merchantFeeDTO.getProfit());
                // 单店统计
                Map<String, Object> merchantData = map.get(merchantFeeDTO.getMerchantCode());
                merchantData.put("merchantMonthMoney", merchantFeeDTO.getMoney());
            }

            for (MerchantFeeDTO merchantFeeDTO : totalBillInfoList) {
                // 总计
                agentTotalMoney = agentTotalMoney.add(merchantFeeDTO.getMoney());
                agentTotalProfit = agentTotalProfit.add(merchantFeeDTO.getProfit());
                // 单店统计
                Map<String, Object> merchantData = map.get(merchantFeeDTO.getMerchantCode());
                merchantData.put("merchantTotalMoney", merchantFeeDTO.getMoney());
            }
        }

        //下级代理商数
        resultMap.put("nextAgentCount", subClientCount + "");
        //本月流水
        resultMap.put("agantMonthMoney", agentMonthMoney + "");
        //总流水
        resultMap.put("agantTotalMoney", agentTotalMoney + "");
        //本月分润
        resultMap.put("agantMonthProfit", agentMonthProfit + "");
        //总分润
        resultMap.put("agantTotalProfit", agentTotalProfit + "");
        resultMap.put("merchantList", merchantBillList);

        return resultMap;
    }

    /**
     * 1-直推，2-间推，3-二级间推
     *
     * @param type   1，2，3
     * @param userId 用户id
     * @return id列表
     */
    private List<String> getParentIdByRecommendType(String type, String userId, List<String> secondaryList) {
        List<String> result = new ArrayList<>();
        List<String> direct = new ArrayList<>();
        List<String> indirect;
        List<String> secondary;

        direct.add(userId);
        if ("1".equals(type)) {
            return direct;
        }

        //查询出直推的集合
        indirect = getDirectRecommendUserIdList(direct);
        if ("2".equals(type)) {
            // 保存间推数据，方便推断查出来的商户是间推还是二级间推
            if (secondaryList != null) {
                secondaryList.addAll(indirect);
            }
            return indirect;
        }

        //查询出间推的集合
        // secondary = getDirectRecommendUserIdList(indirect);
        // if ("3".equals(type)) {
        //     return secondary;
        // }

        result.addAll(direct);
        result.addAll(indirect);
        // result.addAll(secondary);

        return result;
    }

    /**
     * 获取直接推荐的用户id
     *
     * @param userIdList 推荐人userId列表
     * @return 用户id列表
     */
    private List<String> getDirectRecommendUserIdList(List<String> userIdList) {
        List<String> result = new ArrayList<>();
        UserApp query = new UserApp();
        if (userIdList.isEmpty()) {
            return result;
        }

        query.setParentIdList(userIdList);
        query.setLoginName("1");
        List<UserApp> userAppList = queryUserAppListByPhone(query);
        for (UserApp userApp : userAppList) {
            result.add(userApp.getUserId() + "");
        }

        return result;
    }

    @Override
    public Map<String, Object> getMerchantListByConditionV2(Page<MerchSummaryVO> page, MerchSearchDTO merchSearchDTO) {
        Page<MerchSummaryVO> resultPage = baseMapper.selectMerchantSummaryPage(page, merchSearchDTO);
        Map<String, Object> result = new HashMap<>(4);
        result.put("listData", resultPage);

        for (MerchSummaryVO record : resultPage.getRecords()) {
            MerchSummaryVO.wrapper(record);
        }

        MerchSummaryVO summaryVO = baseMapper.selectBillCountAndTotalFee(merchSearchDTO);
        result.put("count", summaryVO.getCount());
        result.put("totalFee", summaryVO.getTotalFee());

        return result;
    }

    @Override
    public Map<String, Object> getMerchantListByCondition(ExpandDto dto) {
        UserApp userApp = queryUserAppByToken();

        if ("agent_staff".equals(userApp.getUserType())) {
            dto.setAgentStaffId(dto.getUserId());
            dto.setUserId(userApp.getParentId() + "'");
            dto.setRecommend("1");
        }

        if ("agent".equals(userApp.getUserType())) {
            dto.setRecommend("1");
        }

        //间推集合
        List<String> secondaryList = new ArrayList<>();
        List<String> parentIdList = getParentIdByRecommendType(dto.getRecommend(), dto.getUserId(), secondaryList);

        QueryWrapper<UserApp> userAppQueryWrapper = new QueryWrapper<>();
        userAppQueryWrapper.in("parentId", parentIdList)
                .like(StringUtils.isNotEmpty(dto.getMerchantName()), "alias", dto.getMerchantName())
                .eq("status", "3");

        if (dto.getAgentStaffIds() != null && !dto.getAgentStaffIds().isEmpty()) {
            String index = dto.getAgentStaffIds().get(0);
            if ("-1".equals(index)) {
                userAppQueryWrapper.isNull("agentStaffId");
            } else {
                userAppQueryWrapper.in("agentStaffId", dto.getAgentStaffIds());
            }
        }

        userAppQueryWrapper.eq(StringUtils.isNotEmpty(dto.getAgentStaffId()), "agentStaffId", dto.getAgentStaffId())
                .gt(StringUtils.isNotEmpty(dto.getStartTime()), "createDt", dto.getStartTime())
                .lt(StringUtils.isNotEmpty(dto.getEndTime()), "createDt", dto.getEndTime())
                .orderByDesc("createDt");

        // 分页用户数据
        IPage<UserApp> pageInfo = new Page<>(dto.getPage(), dto.getSize());
        IPage<UserApp> pageUserAppList = baseMapper.selectCustomList(pageInfo, userAppQueryWrapper);
        // 全部数据
        userAppQueryWrapper.last("");
        // 获取用户总数
//        Integer count = baseMapper.selectCount(userAppQueryWrapper);
        userAppQueryWrapper.select("merchantCode");


        List<String> merchantCodeList = new ArrayList<>();

        for (UserApp item : pageUserAppList.getRecords()) {
            merchantCodeList.add(item.getMerchantCode());
        }

        List<Map<String, Object>> merchantTotalMoneyList = new ArrayList<>();
        if (!merchantCodeList.isEmpty()) {
            // 获取查询出来的每个店铺的营业额
            merchantTotalMoneyList = merchantOrderMapper.selectGroupMerchantTotalConsumeMoney(merchantCodeList);
        }

        // 将每个店铺的营业额和店铺基本信息填入相应店铺的数据实体类中
        for (UserApp item : pageUserAppList.getRecords()) {
            Double totalMoney = item.getTotalMoney();
            if (totalMoney == null) {
                totalMoney = 0.00d;
            }
            for (Map<String, Object> merchantTotalMoneyMap : merchantTotalMoneyList) {
                Object merchantCode = merchantTotalMoneyMap.get("merchantCode");
                if (!item.getMerchantCode().equals(merchantCode)) {
                    continue;
                }

                Object totalConsumeFee = merchantTotalMoneyMap.get("totalConsumeFee");
                if ("1".equals(merchantTotalMoneyMap.get("status"))) {
                    totalMoney = totalMoney + Double.parseDouble(totalConsumeFee.toString());
                } else {
                    totalMoney = totalMoney - Double.parseDouble(totalConsumeFee.toString());
                }
            }
            item.setTotalMoney(totalMoney);
        }

        // 返回参数
        Map<String, Object> result = new HashMap<>(16);
        PageInfo<UserApp> pager = PageUtils.page(pageUserAppList);
        result.put("pager", pager);
        result.put("merchantCount", pageUserAppList.getTotal() + "");

        // 如果带店名的筛选条件，即表明不是新增商户和全部商户页面
        if (StringUtils.isNotEmpty(dto.getMerchantName())) {
            return result;
        }

        // 获取总用户数，去分页
        BigDecimal merchantMoney = BigDecimal.ZERO;
        result.put("merchantMoney", merchantMoney + "");

        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void merchantAudit(JSONObject jsonObject, String channelId) {
        MsgException.checkBlank(channelId, "请选择进件通道");

        MerchantChannel validChannel = channelService.getValidChannel(channelId);
        MsgException.checkNull(validChannel, "不存在的进件通道，或所选通道暂不支持进件");

        String userId = (String) jsonObject.get("userId");

        UserApp userApp = new UserApp().setUserId(Long.parseLong(userId));
        userApp = getOne(new QueryWrapper<>(userApp));

        if ("1".equals(channelId)) {
            MerchantChannelStatus ryxAuditData = mcsService.getByMerchantCode(userApp.getMerchantCode(), 3);
            if (ryxAuditData != null && Objects.equals(ryxAuditData.getChannel(), 3)) {
                throw new MsgException("已在【瑞银信】进件的商户禁止在【随行付】通道进件");
            }
        }

        if ("3".equals(channelId)) {
            MerchantChannelStatus ryxAuditData = mcsService.getByMerchantCode(userApp.getMerchantCode(), 1);
            if (ryxAuditData != null && Objects.equals(ryxAuditData.getChannel(), 1)) {
                throw new MsgException("已在【随行付】进件的商户禁止在【瑞银信】通道进件");
            }
        }

        /*
         * 先查询该通道下是否有记录
         */
        MerchantChannelStatus mcs = mcsService.getByMerchantCode(userApp.getMerchantCode(), Integer.parseInt(channelId));
        if (mcs == null) {
            throw new MsgException("商户未提交进件请求");
        } else {
            if (mcs.getChannel() != null) {
                if (Integer.parseInt(channelId) == mcs.getChannel()
                        && MerchantChannelStatus.isAudited(mcs)) {
                    throw new MsgException("当前通道下已进件，请选择别的进件通道");
                }
            }
        }

        MerchantChannelStatus.checkCanAudit(mcs);

        // 添加行数据锁, 然后重新校验
        MerchantChannelStatus.checkCanAudit(mcs);

        switch (channelId) {
            case "1":
                // 随行付
                sxfMerchantAuditService.merchantAudit(userId, false);
                break;
            case "2":
                // 乐刷，暂不支持
                leshuaMerchantAuditService.merchantAudit(userId, false);
                break;
            case "3":
                // 瑞银信
                ryxMerchantAuditService.merchantAudit(userId, false);
                break;
            case "4":
                // 银盛
                //ysAuditServiceV2.merchantAudit(userId, false);
                ysAuditServiceV3.merchantAuditV3(userId, false);
                break;
            default:
                MsgException.throwException("未知的进件通道");
        }

        wxTalkService.sendAuditResultAlert(userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED)
    public void merchantAuditReq() {
        UserApp userApp = queryUserAppByToken();
        MsgException.checkBlank(userApp.getMerchantCode(), "请完善经营信息");

        AccountDTO realAccount = accountService.getRealAccount(userApp.getUserId() + "");

        MsgException.checkNull(realAccount, "请完善商户结算信息");

        MsgException.checkBlank(userApp.getInviteNum(), "请先填写邀请码");

        CommonRemark commonRemark = new CommonRemark()
                .setUserId(userApp.getUserId().intValue())
                .setCode("CAN_AUDIT");
        commonRemark = remarkService.getOne(new QueryWrapper<>(commonRemark).last(" limit 1"));
        if (commonRemark != null && "-1".equals(commonRemark.getRemark())) {
            throw new MsgException("当前状态不能进件，请联系客服");
        }

        String certNo = realAccount.getIdcard().getCertNo();
        RiskBlacklist riskBlacklist = new RiskBlacklist().setIdcardNo(certNo);
        int count = blacklistService.count(new QueryWrapper<>(riskBlacklist));
        if (count > 0) {
            throw new MsgException("风控黑名单，禁止进件");
        }

        // 保存进件信息之前，先做D0、D1的判断
        MerchantChannelStatus validData = mcsService.getValidData(userApp.getMerchantCode());
        String pushMsg;
        boolean flagD1 = validData == null || validData.getChannel() == null || Objects.equals(4, validData.getChannel());
        if (flagD1) {
            pushMsg = "商家审核已提交，将会在下个工作日内给出审核结果";
        } else {
            pushMsg = "实时到账申请已提交，将会在三个工作日内给出审核结果";
        }
        mcsService.reqAudit(userApp.getMerchantCode());

        Notice notice = new Notice();
        notice.setUserId(userApp.getUserId() + "");
        String uniqueKey = "auditReq" + System.currentTimeMillis();
        notice.setNoticeCode(uniqueKey);
        notice.setUniqueKey(uniqueKey);
        notice.setCreateDt(new Date());
        notice.setConrtent(pushMsg);
        noticeService.saveMerAuthNotice(notice);
        ipRecordService.saveAuditIp(userApp.getUserId() + "");
        generalPushUtil.sendAllPlatByAlias(Collections.singletonList(userApp.getUserId() + ""), "商家审核通知", pushMsg, "1");

        LambdaQueryWrapper<UserApp> qWrapper = Wrappers.lambdaQuery();
        qWrapper.eq(UserApp::getUserId, userApp.getParentId()).last("limit 1");
        UserApp one = getOne(qWrapper);

        if (one != null && "1".equals(one.getAutoAudit())) {
            // 有自动权限先自动审核
            try {
                if (flagD1) {
                    MerchantBaseInfo mbi = mbiService.getMerchantBaseInfoByUserId(userApp.getUserId() + "");
                    if ("1".equals(mbi.getMerchantType())) {
                        log.info("小微自动进件");
                        ryxMerchantAuditService.merchantAudit(userApp.getUserId() + "", false);
                    } else {
                        log.info("个体户自动进件");
                        sxfMerchantAuditService.merchantAudit(userApp.getUserId() + "", false);
                    }
                } else {
                    // mcc问题，暂不设置自动进件
//                    ysAuditServiceV2.merchantAudit(userApp.getUserId() + "", false);
                }

            } catch (Exception e) {
                e.printStackTrace();
                log.warn("自动审核失败");
            }
        }
    }

    @Override
    public void editMerchantAudit(String userId) {
        UserApp userApp = new UserApp().setUserId(Long.parseLong(userId));

        final MerchantBaseInfo mbi = mbiService.getMerchantBaseInfoByMerchantCode(userApp.getMerchantCode());

        userApp = queryUserApp(userApp);
        MsgException.checkNull(userApp, "无法获取对应的商户信息");

        MerchantChannelStatus channelStatus = mcsService.getValidData(userApp.getMerchantCode());

        switch (channelStatus.getChannel().toString()) {
            case "1":
                // 随行付
                sxfMerchantAuditService.editMerchantAudit(userId);
                sendEditApplyNotice(userApp.getUserId() + "", mbi.getAlias(), "次日到账");
                break;
            case "2":
                // 乐刷，暂不支持
                leshuaMerchantAuditService.editMerchantAudit(userId);
                sendEditApplyNotice(userApp.getUserId() + "", mbi.getAlias(), "次日到账");
                break;
            case "3":
                // 瑞银信
                ryxMerchantAuditService.editMerchantAudit(userId);
                sendEditApplyNotice(userApp.getUserId() + "", mbi.getAlias(), "次日到账");
                break;
            case "4":
                // throw new MsgException("暂不支持修改该操作, 请联系客服进行银行卡信息变更");
                // 银盛
                ysAuditServiceV2.editMerchantAudit(userId);
                sendEditApplyNotice(userApp.getUserId() + "", mbi.getAlias(), "实时到账");
                break;
            default:
                throw new MsgException("未知的进件通道");
        }
    }

    private void sendEditApplyNotice(String userId, String alias, String settleName) {
        noticeService.sendTempNotice("结算卡修改申请通知", BaseMerchantAuditService.editApplyNoticeTemplate, null, null, userId, alias, settleName);
    }

    @Override
    public UserApp queryUserBaseInfoByToken() {
        UserAppVO result = new UserAppVO();
        UserApp userApp = queryUserAppByToken();
        UserInfo userInfo = userInfoService.getMainUserInfo(userApp.getUserId());
        UserInfo userInfoThis = userInfoService.getById(userApp.getUserId());
        userApp.setPayPassword(userInfo.getPayPassword());
        userApp.setPhone(userInfo.getPhone());
        userApp.setFaceCert(userInfoThis.getFaceCert());

        String faceCompare = userInfoThis.getFaceCompare() == null ? "0" : userInfoThis.getFaceCompare();
        userApp.setFaceCompare(faceCompare);

        LambdaQueryWrapper<MerchantChannelStatus> qWrapper = Wrappers.lambdaQuery();
        qWrapper.eq(MerchantChannelStatus::getMerchantCode, userApp.getMerchantCode());
        List<MerchantChannelStatus> mcsList = mcsService.list(qWrapper);
        MerchantChannelStatus validMcs = mcsService.getValidData(userApp.getMerchantCode());

        for (MerchantChannelStatus item : mcsList) {
            if (Objects.equals(item.getVirChannelFlag(), Account.CHANNEL_TYPE_D1)) {
                result.setMerchAuditStatusD1(item.getAppStatus());
            }

            if (Objects.equals(item.getVirChannelFlag(), Account.CHANNEL_TYPE_D0)) {
                result.setMerchAuditStatusD0(item.getAppStatus());
            }
        }

        if (validMcs != null) {
            userApp.setMerchantAuditStatus(validMcs.getAppStatus());
            userApp.setMerchantId(validMcs.getMerchantId());
            userApp.setAuditReason(validMcs.getRemark());
        } else {
            userApp.setMerchantId(null);
            userApp.setMerchantAuditStatus(MerchantChannelStatus.AUDIT_STATUS_RESET);
        }

        if ("staff".equals(userApp.getUserType())) {
            UserApp queryUserApp2 = new UserApp();
            queryUserApp2.setMerchantCode(userApp.getMerchantCode());
            queryUserApp2.setUserType("promoter");
            queryUserApp2 = queryUserApp(queryUserApp2);
        }

        if (!StringUtils.isEmpty(userApp.getMerchantCode())) {
            Long userId = userApp.getUserId();
            MerchantStore queryMerchantStore = new MerchantStore();
            queryMerchantStore.setMerchantCode(userApp.getMerchantCode());
            MerchantStore merchantStore = merchantStoreService.queryMerchantStore(queryMerchantStore);
            UserAppConverter.INSTANCE.copyProperties(merchantStore, userApp);

            MerchantBaseInfo merchantBaseInfo = new MerchantBaseInfo();
            merchantBaseInfo.setMerchantCode(userApp.getMerchantCode());
            merchantBaseInfo = mbiService.queryMerchantBaseInfo(merchantBaseInfo);
            UserAppConverter.INSTANCE.copyProperties(merchantBaseInfo, userApp);
            userApp.setUserId(userId);
        }

        userApp.setAisleSwitch(Integer.valueOf(systemConfigService.getaisleSwitch()));
        IdCard legalIdCard;
        if (StringUtils.isNotEmpty(userApp.getMerchantCode())) {
            legalIdCard = idCardService.getCertIdCard(userApp.getUserId() + "");
            if (legalIdCard != null) {
                userApp.setBankCertName(legalIdCard.getCertName());
            }
        }

        Converter.INSTANCE.cp(userApp, result);

        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void appSaveStaffInfo(UserApp userApp) {
        UserApp tokenUserApp = queryUserAppByToken();
        userApp.setLoginName(userApp.getLoginName().replaceAll("[ \u3000]", ""));

        if ("promoter".equals(tokenUserApp.getUserType())) {
            saveStaff(userApp);
        } else {
            throw new MsgException("没有权限");
        }
    }

    @Override
    public Integer getUserAppWithChannelStatus(QueryWrapper<UserApp> queryWrapper) {
        return baseMapper.selectUserAppWithChannelStatusCount(queryWrapper);
    }

    @Override
    public Map<String, Object> agentStaffShareInfo() {
        Map<String, Object> result = new HashMap<>();
        UserApp userApp = queryUserAppByToken();

        BigDecimal totalConsume = BigDecimal.ZERO;
        BigDecimal monthConsume = BigDecimal.ZERO;
        int totalOrderCount = 0;
        int monthOrderCount = 0;
        int totalMerchantCount;
        int monthMerchantCount = 0;

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        Date monthFirst = calendar.getTime();

        // 获取推广的商户
        QueryWrapper<UserApp> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("agentStaffId", userApp.getUserId());
        // TODO 暂不确定是否需要添加秒审的商户
        queryWrapper.in("merchantAuditStatus", "3");
        List<UserApp> merchantList = baseMapper.selectListWithChannelStatus(queryWrapper);

        List<String> merchantCodeList = new ArrayList<>();

        totalMerchantCount = merchantList.size();
        for (UserApp item : merchantList) {
            merchantCodeList.add(item.getMerchantCode());

            if (monthFirst.before(item.getCreateDt())) {
                monthMerchantCount++;
            }
        }

        if (merchantCodeList.isEmpty()) {
            result.put("totalConsume", totalConsume.setScale(2, RoundingMode.HALF_UP).toString());
            result.put("monthConsume", monthConsume.setScale(2, RoundingMode.HALF_UP).toString());
            result.put("totalOrderCount", totalOrderCount);
            result.put("monthOrderCount", monthOrderCount);
            result.put("totalMerchantCount", totalMerchantCount);
            result.put("monthMerchantCount", monthMerchantCount);
            return result;
        }

        QueryWrapper<MerchantOrder> merchantOrderQueryWrapper = new QueryWrapper<>();
        merchantOrderQueryWrapper.in("merchantCode", merchantCodeList);
        merchantOrderQueryWrapper.in("status", "1", "2");
        List<MerchantOrder> orderList = merchantOrderMapper.selectList(merchantOrderQueryWrapper);

        for (MerchantOrder item : orderList) {
            if (item.getStatus().equals("1")) {
                totalConsume = totalConsume.add(BigDecimal.valueOf(item.getConsumeFee()));
                totalOrderCount++;

                if (monthFirst.before(item.getCreateDt())) {
                    monthConsume = monthConsume.add(BigDecimal.valueOf(item.getConsumeFee()));
                    monthOrderCount++;
                }
            } else {
                totalConsume = totalConsume.subtract(BigDecimal.valueOf(item.getConsumeFee()));
                totalOrderCount--;

                if (monthFirst.before(item.getCreateDt())) {
                    monthConsume = monthConsume.subtract(BigDecimal.valueOf(item.getConsumeFee()));
                    monthOrderCount--;
                }
            }
        }

        result.put("totalConsume", totalConsume.setScale(2, RoundingMode.HALF_UP).toString());
        result.put("monthConsume", monthConsume.setScale(2, RoundingMode.HALF_UP).toString());
        result.put("totalOrderCount", totalOrderCount);
        result.put("monthOrderCount", monthOrderCount);
        result.put("totalMerchantCount", totalMerchantCount);
        result.put("monthMerchantCount", monthMerchantCount);
        return result;
    }

    @Override
    public List<String> storeMemberList(String merchantCode) {
        UserApp userApp = new UserApp().setMerchantCode(merchantCode);
        QueryWrapper<UserApp> queryWrapper = new QueryWrapper<>(userApp);
        queryWrapper.select("userId");
        List<UserApp> userApps = baseMapper.selectList(queryWrapper);

        List<String> result = new ArrayList<>();
        for (UserApp item : userApps) {
            result.add(item.getUserId() + "");
        }

        return result;
    }

    /**
     * 保存商户员工
     */
    private void saveStaff(UserApp userApp) {
        if (StringUtil.isEmpty(userApp.getMerchantCode())) {
            throw new MsgException("无商家编码");
        }

        if (StringUtil.isEmpty(userApp.getStoreId())) {
            throw new MsgException("无店铺id");
        }

        // 判断商家信息
        MerchantBaseInfo queryBaseInfo = new MerchantBaseInfo();
        queryBaseInfo.setMerchantCode(userApp.getMerchantCode());
        List<MerchantBaseInfo> queryMerchantBaseInfoList = mbiService
                .queryMerchantBaseInfoList(queryBaseInfo);

        MsgException.checkBlank(queryMerchantBaseInfoList, "无商家信息！");
        queryBaseInfo = queryMerchantBaseInfoList.get(0);
        userApp.setMerchantName(queryBaseInfo.getMerchantName());
        // 查询门店信息
        MerchantStore queryMerchantStore = new MerchantStore();
        queryMerchantStore.setMerchantCode(userApp.getMerchantCode());
        queryMerchantStore.setStoreId(userApp.getStoreId());
        List<MerchantStore> queryMerchantStoreList = merchantStoreService.queryMerchantStoreList(queryMerchantStore);

        MsgException.checkBlank(queryMerchantStoreList, "无店铺信息！");
        queryMerchantStore = queryMerchantStoreList.get(0);

        userApp.setStoreName(queryMerchantStore.getStoreName());
        // 判断登陆账号是否存在
        UserInfo queryUserInfo = new UserInfo();
        queryUserInfo.setLoginName(userApp.getLoginName());
        List<UserInfo> queryUserInfoList = userInfoService.queryUserInfoList(queryUserInfo);

        MsgException.checkNonBlank(queryUserInfoList, "登陆账号已存在");

        // 保存后台的登陆信息
        UserInfo userInfo = new UserInfo();
        userInfo.setPhone(userApp.getPhone());
        userInfo.setPassword(MD5Util.MD5Encode(userApp.getPassword(), "utf-8"));
        userInfo.setLoginName(userApp.getLoginName());
        userInfo.setTrueName(userApp.getUserName());
        userInfoService.saveUserInfo(userInfo);
        // 获取当前用户的userId
        UserInfo userInfoData = new UserInfo();
        userInfoData.setLoginName(userApp.getLoginName());
        List<UserInfo> queryUserInfoList2 = userInfoService.queryUserInfoList(userInfoData);
        if (queryUserInfoList2 != null && !queryUserInfoList2.isEmpty()) {
            userInfoData = queryUserInfoList2.get(0);
            userApp.setUserId(userInfoData.getId());
        }
        Long roleId = null;
        // 获取全部的角色信息
        List<SystemConfig> systemConfigs = systemConfigService.querySystemConfigList(new SystemConfig());
        for (SystemConfig systemConfig : systemConfigs) {
            if (systemConfig.getPropertyKey().equalsIgnoreCase("staff_role_id")) {
                roleId = Long.parseLong(systemConfig.getPropertyValue());
            }
        }
        if (null == roleId) {
            throw new MsgException("获取角色信息错误");
        }
        // 获取当前用户的角色信息
        RoleUserInfo role = new RoleUserInfo();
        role.setRoleId(roleId);
        role.setUserId(userInfo.getId());
        roleUserInfoService.saveRoleUserInfo(role);
        userApp.setUserType("staff");
        userApp.setCreateDt(new Date());
        save(userApp);

        MerchantStaffConn staffConn = new MerchantStaffConn();
        staffConn.setMerchantCode(queryBaseInfo.getMerchantCode());
        staffConn.setUserId(userApp.getUserId());
        staffConnService.save(staffConn);

        StaffPermission staffPermission = staffPermissionService.getEntity(userApp.getUserId(), userApp.getMerchantCode());
        staffPermission.setPermissionBill(userApp.getPermissionBill());
        staffPermissionService.saveOrUpdate(staffPermission);
    }

    /**
     * 关联查询分页
     */
    @Override
    public Page<UserApp> pageJoinData(Page<UserApp> page, UserApp userApp) {
        return this.baseMapper.pageData(page, userApp);
    }

    /**
     * 获取下级商户数量
     */
    @Override
    public Integer getSubUserCount(Long userId, String startDate, String endDate) {
        return this.baseMapper.getSubUserCount(userId, startDate, endDate);
    }

    /**
     * 分页查询活动商户详情列表
     */
    @Override
    public Page<UserInfoVO> queryActPage(Page<UserInfoVO> page, UserInfoVO userInfoVO) {
        return baseMapper.queryActPage(page, userInfoVO);
    }

    @Override
    public Integer getParentUserId(Integer parentUserId) {
        return baseMapper.getParentUserId(parentUserId);
    }

    @Override
    public Integer getUserId(String merchantCode) {
        return baseMapper.getUserId(merchantCode);
    }

    @Override
    public Map<String, Object> getStaffPage(Integer currPage, Integer size, UserInfoVO userInfoVO) {
        Map<String, Object> map = new HashMap<>();
        map.put("pageSize", size);
        map.put("offset", (currPage - 1) * size);
        map.put("userType", userInfoVO.getUserType());// 筛选出员工
        if (StringUtils.isNotEmpty(userInfoVO.getUserName())) {
            map.put("userName", userInfoVO.getUserName());
        }
        if (StringUtils.isNotEmpty(userInfoVO.getPhone())) {
            map.put("phone", userInfoVO.getPhone());
        }
        if (StringUtils.isNotEmpty(userInfoVO.getStoreId())) {
            map.put("storeId", userInfoVO.getStoreId());
        }
        if (StringUtils.isNotEmpty(userInfoVO.getStoreName())) {
            map.put("storeName", userInfoVO.getStoreName());
        }
        if (StringUtils.isNotEmpty(userInfoVO.getPhone())) {
            map.put("phone", userInfoVO.getPhone());
        }
        if (StringUtils.isNotEmpty(userInfoVO.getAlias())) {
            map.put("alias", userInfoVO.getAlias());
        }
        if (StringUtils.isNotEmpty(userInfoVO.getContactMobile())) {
            map.put("contactMobile", userInfoVO.getContactMobile());
        }
        if (userInfoVO.getUserId() != null) {
            map.put("userId", userInfoVO.getUserId());
        }

        Page<UserInfoVO> page = queryUserInfoVOPage(map);
        Map<String, Object> result = new HashMap<>();
        result.put("userAppList", page.getRecords());
        result.put("code", 200);
        result.put("count", page.getTotal());
        result.put("pageCount", StringUtil.getPageCount(page.getTotal(), size));
        result.put("currPage", currPage);
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> getLevelUpOrder(UserApp userApp, String type) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        MsgException.checkBlank(type, "请选择支付方式");

        String merchantCode = "M800202008254990744";

        MerchantBaseInfo merchantBaseInfo = new MerchantBaseInfo().setMerchantCode(merchantCode);
        merchantBaseInfo = mbiService.getOne(new QueryWrapper<>(merchantBaseInfo));

        MerchantStore merchantStore = new MerchantStore().setMerchantCode(merchantCode);
        merchantStore = merchantStoreService.queryMerchantStore(merchantStore);


        SystemConfig systemConfig = new SystemConfig();
        if (userApp.getLevel() == 1) {
            systemConfig.setPropertyKey("twoUpVipAmount");
            systemConfig = systemConfigService.querySystemConfig(systemConfig);
        } else if (userApp.getLevel() == 2) {
            systemConfig.setPropertyKey("threeUpVipAmount");
            systemConfig = systemConfigService.querySystemConfig(systemConfig);
        } else {
            throw new MsgException("已经是最高等级");
        }

        String propertyValue = systemConfig.getPropertyValue();
        String[] split = propertyValue.split("-");

        String payTypeCode = null;
        String payTypeName = null;
        switch (type) {
            case "1":
                payTypeCode = "aliPay";
                payTypeName = "支付宝支付";
                break;
            case "2":
                payTypeCode = "wechatPay";
                payTypeName = "微信支付";
                break;
            default:
                MsgException.throwException("未知的支付方式");
                break;
        }

        // 生成升级订单信息
        String orderNumber = "SJ000" + StringUtil.getBillno();
        MerchantIncome income = new MerchantIncome();
        income.setUserId(userApp.getUserId().intValue());
        income.setDealCode(orderNumber);
        income.setCreateTime(new Date());
        income.setDealFee(Double.valueOf(split[0]));
        income.setPayTypeCode("3");
        income.setPayTypeName("推广员升级充值");
        income.setMerchantName(merchantBaseInfo.getAlias());
        income.setMerchantCode(merchantCode);
        income.setStoreId(merchantStore.getStoreId());
        income.setStoreName(merchantStore.getStoreName());
        income.setDealStatus(0);
        // 生成商户订单信息，并保存
        String aisleSwitch = systemConfigService.querySystemConfigValue("aisleSwitch");
        Date date = new Date();
        MerchantOrder merchantOrder = new MerchantOrder();
        merchantOrder.setOrderNumber(orderNumber);
        merchantOrder.setCreateDt(date);
        merchantOrder.setUpdateTime(date);
        merchantOrder.setAisleSwitch(aisleSwitch);
        merchantOrder.setOrderType("8");
        merchantOrder.setPayTypeCode(payTypeCode);
        merchantOrder.setPayTypeName(payTypeName);
        merchantOrder.setMerchantName(merchantBaseInfo.getMerchantName());
        merchantOrder.setMerchantCode(merchantCode);
        merchantOrder.setStoreId(merchantStore.getStoreId());
        merchantOrder.setStoreName(merchantStore.getStoreName());
        merchantOrder.setConsumeFee(Double.valueOf(split[0]));

        Double rate = 0.0038d;
        BigDecimal fee = new BigDecimal(split[0]).multiply(new BigDecimal(String.valueOf(rate))).setScale(2, BigDecimal.ROUND_HALF_UP);
        merchantOrder.setEnterFee(new BigDecimal(split[0]).subtract(fee).doubleValue());
        merchantOrder.setStatus("5");
        merchantOrder.setAisleSwitch(aisleSwitch);

        merchantIncomeService.save(income);
        merchantOrderMapper.insert(merchantOrder);

        Map<String, String> map = new HashMap<>(16);
        map.put("body", "收银呗商城充值");
        map.put("subject", "收银呗商城充值");
        map.put("outTradeNo", orderNumber);
        map.put("totalAmount", split[0]);

        // 请求支付宝/微信支付的订单信息
        if ("1".equals(type)) {
            return aliService.appPayParam(map);
        } else {
            Map<String, String> reMap = wechatService.appPayParam(request, map);
            return new HashMap<>(reMap);
        }
    }

    @Override
    public Map<String, Object> getLevelUpOrderV2Info(UserApp userApp, String level) {
        if (!"promoter".equals(userApp.getUserType()) && !"agent".equals(userApp.getUserType())) {
            throw new MsgException("拒绝访问");
        }

        String currentLevelNum = userApp.getLevelCode().replace("LV", "");

        String levelNum = userApp.getLevelCode().replace("LV", "");

        String targetLevelNum = level.replace("VIP", "");

        if (Integer.parseInt(targetLevelNum) >= 10) {
            throw new MsgException("等级错误");
        }

        if (Integer.parseInt(currentLevelNum) >= Integer.parseInt(targetLevelNum)) {
            throw new MsgException("当前已达到该等级");
        }

        if ("9".equals(currentLevelNum) || "10".equals(currentLevelNum)) {
            throw new MsgException("当前已达到最高等级");
        }

        Map<String, Object> result = new HashMap<>();
        BigDecimal targetFee = BigDecimal.ZERO;

        result.put("targetLevel", level);
        result.put("fee", BigDecimal.ZERO);

        LambdaQueryWrapper<SystemConfig> qWrapper = new LambdaQueryWrapper<>();
        qWrapper.likeRight(SystemConfig::getPropertyKey, "vipUpAmt");
        qWrapper.orderByAsc(SystemConfig::getPropertyKey);
        List<SystemConfig> configList = systemConfigService.list(qWrapper);

        for (SystemConfig systemConfig : configList) {
            String vipUpAmtKeyLevel = systemConfig.getPropertyKey().replace("vipUpAmt", "");
            int targetCompare = targetLevelNum.compareTo(vipUpAmtKeyLevel);
            int currentCompare = levelNum.compareTo(vipUpAmtKeyLevel);

            if (targetCompare < 0) {
                break;
            }

            targetFee = targetFee.add(new BigDecimal(systemConfig.getPropertyValue().split("-")[0]));
        }

        MerchantIncome merchantIncome = new MerchantIncome();
        merchantIncome.setPayTypeCode("3");
        merchantIncome.setDealStatus(1);
        merchantIncome.setUserId(userApp.getUserId().intValue());
        List<MerchantIncome> list = merchantIncomeService.list(new QueryWrapper<>(merchantIncome));
        for (MerchantIncome income : list) {
            targetFee = targetFee.subtract(BigDecimal.valueOf(income.getDealFee()));
        }

        if (targetFee.compareTo(BigDecimal.ZERO) <= 0) {
            throw new MsgException("已达到最高等级");
        }

        result.put("fee", targetFee);

        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> getLevelUpOrderV2(UserApp userApp, String type, String level) {
        if (!"promoter".equals(userApp.getUserType()) && !"agent".equals(userApp.getUserType())) {
            throw new MsgException("拒绝访问");
        }

        String currentLevelNum = userApp.getLevelCode().replace("LV", "");

        String levelNum = userApp.getLevelCode().replace("LV", "");

        String targetLevelNum = level.replace("VIP", "");

        if (Integer.parseInt(targetLevelNum) >= 10) {
            throw new MsgException("等级错误");
        }

        if (Integer.parseInt(currentLevelNum) >= Integer.parseInt(targetLevelNum)) {
            throw new MsgException("当前已达到该等级");
        }

        if ("9".equals(currentLevelNum) || "10".equals(currentLevelNum)) {
            throw new MsgException("当前已达到最高等级");
        }

        Map<String, Object> result = new HashMap<>();
        BigDecimal targetFee = BigDecimal.ZERO;
        BigDecimal targetProfit = BigDecimal.ZERO;

        LambdaQueryWrapper<SystemConfig> qWrapper = new LambdaQueryWrapper<>();
        qWrapper.likeRight(SystemConfig::getPropertyKey, "vipUpAmt");
        qWrapper.orderByAsc(SystemConfig::getPropertyKey);
        List<SystemConfig> configList = systemConfigService.list(qWrapper);

        for (SystemConfig systemConfig : configList) {
            String vipUpAmtKeyLevel = systemConfig.getPropertyKey().replace("vipUpAmt", "");
            int targetCompare = Integer.parseInt(targetLevelNum) - Integer.parseInt(vipUpAmtKeyLevel);
            // 目标等级低于当前要升级的等级时，跳出
            if (targetCompare < 0) {
                break;
            }

            // int currentCompare = Integer.parseInt(levelNum) - Integer.parseInt(vipUpAmtKeyLevel);
            // // 低于目前等级的升级费用，不用跳出
            // if (currentCompare >= 0) {
            //     continue;
            // }

            String[] split = systemConfig.getPropertyValue().split("-");
            targetFee = targetFee.add(new BigDecimal(split[0]));
        }

        MerchantIncome merchantIncome = new MerchantIncome();
        merchantIncome.setPayTypeCode("3");
        merchantIncome.setDealStatus(1);
        merchantIncome.setUserId(userApp.getUserId().intValue());
        List<MerchantIncome> list = merchantIncomeService.list(new QueryWrapper<>(merchantIncome));
        for (MerchantIncome income : list) {
            targetFee = targetFee.subtract(BigDecimal.valueOf(income.getDealFee()));
        }

        targetProfit = targetFee.multiply(new BigDecimal("0.3"));

        if (targetFee.compareTo(BigDecimal.ZERO) <= 0) {
            throw new MsgException("已达到最高等级");
        }

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        MsgException.checkBlank(type, "请选择支付方式");

        String merchantCode = "M800202008254990744";

        MerchantBaseInfo merchantBaseInfo = new MerchantBaseInfo().setMerchantCode(merchantCode);
        merchantBaseInfo = mbiService.getOne(new QueryWrapper<>(merchantBaseInfo));

        MerchantStore merchantStore = new MerchantStore().setMerchantCode(merchantCode);
        merchantStore = merchantStoreService.queryMerchantStore(merchantStore);

        String payTypeCode = null;
        String payTypeName = null;
        switch (type) {
            case "1":
                payTypeCode = "aliPay";
                payTypeName = "支付宝支付";
                break;
            case "2":
                payTypeCode = "wechatPay";
                payTypeName = "微信支付";
                break;
            default:
                MsgException.throwException("未知的支付方式");
                break;
        }

        // 生成升级订单信息
        String orderNumber = "SJ000" + StringUtil.getBillno();
        MerchantIncome income = new MerchantIncome();
        income.setUserId(userApp.getUserId().intValue());
        income.setDealCode(orderNumber);
        income.setCreateTime(new Date());
        income.setDealFee(targetFee.doubleValue());
        income.setPayTypeCode("3");
        income.setPayTypeName("推广员升级充值");
        income.setMerchantName(merchantBaseInfo.getAlias());
        income.setMerchantCode(merchantCode);
        income.setStoreId(merchantStore.getStoreId());
        income.setStoreName(merchantStore.getStoreName());
        income.setDealStatus(0);
        // 生成商户订单信息，并保存
        String aisleSwitch = systemConfigService.querySystemConfigValue("aisleSwitch");
        Date date = new Date();
        MerchantOrder merchantOrder = new MerchantOrder();
        merchantOrder.setOrderNumber(orderNumber);
        merchantOrder.setCreateDt(date);
        merchantOrder.setUpdateTime(date);
        merchantOrder.setAisleSwitch(aisleSwitch);
        merchantOrder.setOrderType("8");
        merchantOrder.setPayTypeCode(payTypeCode);
        merchantOrder.setPayTypeName(payTypeName);
        merchantOrder.setMerchantName(merchantBaseInfo.getMerchantName());
        merchantOrder.setMerchantCode(merchantCode);
        merchantOrder.setStoreId(merchantStore.getStoreId());
        merchantOrder.setStoreName(merchantStore.getStoreName());
        merchantOrder.setConsumeFee(targetFee.doubleValue());
        merchantOrder.setRemark("分润金额合计为-" + targetProfit.toPlainString() + "-" + "从-" + currentLevelNum + "-升到-" + targetLevelNum);

        int rate = 60;
        merchantOrder.calcRateAndFee(BigDecimal.valueOf(rate));
        merchantOrder.setChannelRate(BigDecimal.valueOf(rate));
        merchantOrder.setChannelFee(targetFee.multiply(BigDecimal.valueOf(rate)).divide(BigDecimal.valueOf(10000), 2, RoundingMode.HALF_EVEN));
        merchantOrder.setStatus("5");
        merchantOrder.setAisleSwitch(aisleSwitch);

        merchantIncomeService.save(income);
        merchantOrderMapper.insert(merchantOrder);

        Map<String, String> map = new HashMap<>(16);
        map.put("body", "收银呗商城充值");
        map.put("subject", "收银呗商城充值");
        map.put("outTradeNo", orderNumber);
        map.put("totalAmount", targetFee.toPlainString());

        // 请求支付宝/微信支付的订单信息
        if ("1".equals(type)) {
            return aliService.appPayParam(map);
        } else {
            Map<String, String> reMap = wechatService.appPayParam(request, map);
            return new HashMap<>(reMap);
        }
    }

    @Override
    public UserApp getBossUserApp(UserApp userAppStaff) {
        // 如果是员工进行查询，那么查询账单的userId得替换成老板的userId
        if ("staff".equals(userAppStaff.getUserType())) {
            UserApp userAppBoss = new UserApp();
            userAppBoss.setUserType("promoter");
            userAppBoss.setMerchantCode(userAppStaff.getMerchantCode());
            userAppBoss = getOne(new QueryWrapper<>(userAppBoss));
            return userAppBoss;
        }

        return null;
    }

    @Override
    public UserApp getBossUserApp(Integer userId, String merchantCode) {
        UserApp userApp = new UserApp().setUserId(userId.longValue());
        userApp = getOne(new QueryWrapper<>(userApp));
        userApp.setMerchantCode(merchantCode);

        if (merchantCode == null) {
            MerchantStaffConn staffConn = new MerchantStaffConn().setUserId(userId.longValue());
            staffConn = staffConnService.getOne(new QueryWrapper<>(staffConn).last("limit 1"));
            if (staffConn != null) {
                userApp.setMerchantCode(staffConn.getMerchantCode());
            }
        }

        return getBossUserApp(userApp);
    }

    @Override
    public Page<UserApp> appPageStaff(UserApp userApp) {
        UserApp tokenUserApp = queryUserAppByToken();
        MerchantStore merchantStore = new MerchantStore();
        merchantStore.setMerchantCode(tokenUserApp.getMerchantCode());
        merchantStore = merchantStoreService.queryMerchantStore(merchantStore);

        Page<UserApp> page = new Page<>();
        page.addOrder(new OrderItem().setAsc(false).setColumn("id"));

        QueryWrapper<Object> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("msc.merchantCode", userApp.getMerchantCode());
        queryWrapper.eq("userType", userApp.getUserType());

//        queryWrapper.like(StringUtils.isNotBlank(userApp.getLoginName()), "ui.loginName", userApp.getLoginName());
        queryWrapper.like(StringUtils.isNotBlank(userApp.getUserName()), "ua.userName", userApp.getUserName());

        if (userApp.getPage() != null) {
            page.setCurrent(userApp.getPage());
        }

        page = baseMapper.selectUserApp(page, queryWrapper);

        for (UserApp app : page.getRecords()) {
            app.setStoreId(merchantStore.getStoreId());
            app.setMerchantCode(tokenUserApp.getMerchantCode());
        }
        return page;
    }

    @Override
    @Transactional
    public void userCert(String userId, Integer status, String certReason) {
        UserApp userApp;
        LambdaQueryWrapper<UserApp> qWua = Wrappers.lambdaQuery();
        userApp = getOne(qWua.eq(UserApp::getUserId, userId));
        userApp.setStatus(status);
        userApp.setCertReason(certReason);
        updateById(userApp);
        String statusZh = "审核通过";
        if (status == 2) {
            statusZh = certReason;
        }

        Notice notice = new Notice();
        notice.setUserId(userApp.getUserId().toString());
        notice.setUserName(userApp.getUserName());
        notice.setIsDeal(0);
        notice.setDesc(statusZh);
        notice.setConrtent(statusZh);
        notice.setCreateDt(new Date());
        notice.setNoticeCode(UUID.randomUUID().toString().replace("-", ""));
        noticeService.saveIdCardAuthNotice(notice);

        List<String> alias = new ArrayList<>();
        alias.add(userApp.getUserId().toString());
        generalPushUtil.sendAllPlatByAlias(alias, "实名认证通知", statusZh, "1");
    }

    /**
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @description:首页统计数据
     * @date: 2021/10/19 17:24
     */
    @Override
    public Map<String, Object> getPlatformData() {
        return baseMapper.getPlatformData();
    }

    @Override
    public Integer getMaxSort() {
        return baseMapper.getMaxSort();
    }

    /**
     * 获取直推用户的新增数量和总数
     *
     * @param userId:
     * @param date:
     * @param dateType:
     * @return cn.pluss.platform.vo.UserNumVO
     * @date: 2022/1/24 23:26
     */
    @Override
    public UserNumVO getUserNumInfo(Long userId, String date, Integer dateType) {
        return baseMapper.getUserNumInfo(userId, date, dateType);
    }

    /**
     * 检查wap请求token
     *
     * @param token:
     * @param request:
     * @param roleEnum:
     * @date: 2022/2/16 14:18
     */
    @Override
    public UserApp checkWapToken(String token, HttpServletRequest request, UserRoleEnum roleEnum) {
        if (StringUtil.isEmpty(token)) {
            MsgException.throwException("登录超时，请重新登录");
        }
        Object obj = request.getSession().getAttribute(token);
        UserApp userApp = null;
        if ((obj instanceof UserApp)) {
            userApp = (UserApp) obj;
        } else {
            QueryWrapper<UserApp> queryAppWrapper = new QueryWrapper<>();
            queryAppWrapper.eq("token", token);
            userApp = baseMapper.selectOne(queryAppWrapper);
            if (userApp == null) {
                MsgException.throwException("登录超时，请重新登录");
            }
            request.getSession().setAttribute(token, userApp);
        }
        if (roleEnum != null && !roleEnum.getCode().equals(userApp.getRoleCode())) {
            MsgException.throwException("非直营团队角色，无法开通代理！");
        }
        return userApp;
    }

    /**
     * 根据邀请码获取用户信息
     *
     * @param inviteNum:
     * @param roleEnum:
     * @return cn.pluss.platform.entity.UserApp
     * @date: 2022/2/16 15:53
     */
    @Override
    public UserApp getUserAppByInviteNum(String inviteNum, UserRoleEnum roleEnum) {
        QueryWrapper<UserApp> queryWrapper = new QueryWrapper<UserApp>().eq("inviteNum", inviteNum);
        if (roleEnum != null) {
            queryWrapper.eq("roleCode", roleEnum.getCode());
        }
        UserApp userApp = baseMapper.selectOne(queryWrapper);
        if (userApp == null) {
            MsgException.throwException("无效邀请码！");
        }
        if (userApp.getStatus() != 3 && userApp.getBankStatus() != 3) {
            MsgException.throwException("无效邀请码，当前邀请码还未完成实名认证！");
        }
        return userApp;
    }

    /**
     * 保存贝斯特代理账号
     *
     * @param params:
     * @date: 2022/2/16 17:54
     */
    @Override
    public void bstSaveAgent(Map<String, Object> params) {
        MsgException.checkNull(params.get("phone"), "注册手机号不能为空！");
        MsgException.checkNull(params.get("phoneverify"), "验证码不能为空！");
        MsgException.checkNull(params.get("password"), "登录密码不能为空！");
        MsgException.checkNull(params.get("userId"), "推荐人不能为空！");
        UserApp parentApp = baseMapper.selectByUserId(params.get("userId").toString());
        if (!Objects.equals(parentApp.getStatus(), 3) || !Objects.equals(parentApp.getBankStatus(), 3)) {
            throw new MsgException("邀请人无效，当前推广服务商未完成实名");
        }

        UserInfo ui = userInfoService.getById(parentApp.getUserId());
        if (Objects.equals(ui.getStatus(), UserInfo.STATUS_NO_SPREAD)) {
            throw new MsgException("当前推广服务商存在违规行为, 已被关闭推广权限, 请联系收银呗客服申诉");
        }

        if (!"1".equals(parentApp.getSpreadFlag())) {
            throw new MsgException("当前用户已经注册多个账户，无法开通代理");
        }

        UserInfo queryUserInfo = new UserInfo().setLoginName(params.get("phone").toString());
        List<UserInfo> existUserInfoList = userInfoService.queryUserInfoList(queryUserInfo);
        if (existUserInfoList != null && !existUserInfoList.isEmpty()) {
            MsgException.throwException("当前手机号已被注册");
        }
        PhoneValidateCode phoneValidateCode = new PhoneValidateCode();
        phoneValidateCode.setCode(params.get("phoneverify").toString());
        phoneValidateCode.setPhone(params.get("phone").toString());
        List<PhoneValidateCode> list = phoneValidateCodeService
                .queryPhoneValidateCodeList(phoneValidateCode);
        if (list.isEmpty()) {
            MsgException.throwException("验证码有误！");
        }
        String mdxPassword = MD5Util.MD5Encode(params.get("password").toString(), "UTF-8");
        UserInfo userInfo = new UserInfo();
        userInfo.setLoginName(params.get("phone").toString());
        userInfo.setTrueName(params.get("phone").toString());
        userInfo.setPhone(params.get("phone").toString());
        userInfo.setPassword(mdxPassword);
        userInfo.setCreateTime(new Date());
        userInfoService.saveUserInfo(userInfo);
        UserApp userApp = new UserApp();
        userApp.setUserId(userInfo.getId());
        //判断推广员是否是业务员
//        if ("agent_staff".equals(appInfo.getUserType())) {
//            userApp.setAgentStaffId(appInfo.getUserId());
//        }
        if (StringUtil.isNotEmpty(parentApp.getPIdArr())) {
            userApp.setPIdArr(parentApp.getUserId() + "," + parentApp.getPIdArr());
        }
        userApp.setParentId(Long.parseLong(params.get("userId").toString()));
        Object userNo = params.get("userNo");
        if (userNo != null) {
            userApp.setUserNo(userNo.toString());
        }
        UserApp.setSort(parentApp, userApp);
        UserApp.setRoleInfo(parentApp, userApp, 1);

        userApp.setUserName(params.get("phone").toString());
        userApp.setUserType("agent");
        userApp.setLevel(1);
        userApp.setStatus(0);

        userApp.setCreateDt(new Date());
        userApp.setInviteNum(StringUtil.genRandomNum(5));
        baseMapper.insert(userApp);
        ipRecordService.saveRegIp(userInfo.getId() + "", userInfo.getId() + "");
        PhoneValidateCode phoneValidate = new PhoneValidateCode();
        if (StringUtil.isNotEmpty(params.get("phone").toString())) {
            phoneValidate.setPhone(params.get("phone").toString());
            phoneValidateCodeService.deletePhoneValidateCode(phoneValidate);
        }
        //保存业务员考核数据
        if(UserRoleEnum.ZY_BST.getCode().equals(userApp.getRoleCode())){
            //新开的业务员
            UserRole role = userRoleMapper.getByRoleCode(userApp.getRoleCode());
            UserAssess assess = new UserAssess(userApp,role);
            userAssessMapper.insert(assess);
        }

        //TODO 贝斯特开代理也同步用户到积分商城
        jfShopHandler.syncJfShopUser(userApp, userInfo);
    }

    @Override
    public UserApp checkApiToken() {
        UserApp userApp = queryUserAppByToken();
        if (userApp == null) {
            MsgException.throwException("登录用户异常");
        }
        return userApp;
    }

    /**
     * 根据手机号获取用户信息
     *
     * @param phone
     * @return
     */
    @Override
    public UserApp getUserAppByPhone(String phone, UserApp userApp) {
        MsgException.checkBlank(phone, "手机号不能为空！");
        List<UserApp> list = baseMapper.getUserInfoByPhone(phone);
        if (list.isEmpty()) {
            MsgException.throwException("手机号有误！");
        }
        UserApp app = list.get(0);
        if (list.size() != 1) {
            for (UserApp ua : list) {
                if ("agent".equals(ua.getUserType())) {
                    app = ua;
                    break;
                }
            }
        }
        app.getLevelCode().replace("LV", "VIP");
        MsgException.check(userApp.getUserId().equals(app.getUserId()), "无法选择自己");
        return app;
    }
}