package com.cyksj.web.controller.manage;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.annotation.Log;
import com.cyksj.common.constant.Constant;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.dto.Result;
import com.cyksj.enums.BusinessType;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.*;
import com.cyksj.mapper.corp.CorpUserFollowRelationMapper;
import com.cyksj.mapper.manage.cms.CmsUserMapper;
import com.cyksj.mapper.market.task.UserBindDetailMapper;
import com.cyksj.mapper.vip.VipUserMapper;
import com.cyksj.model.entity.*;
import com.cyksj.model.manage.views.MaliceUserView;
import com.cyksj.model.manage.views.UserView;
import com.cyksj.model.request.OpenVipReq;
import com.cyksj.model.request.UserBalanceReq;
import com.cyksj.model.request.UserFuncPropertyReq;
import com.cyksj.model.views.*;
import com.cyksj.service.relation.GroupRelationClearService;
import com.cyksj.service.user.UserBenefitsService;
import com.cyksj.service.user.UserBindRelationService;
import com.cyksj.service.user.UserPayOrderBlockService;
import com.cyksj.service.vip.CmsVipUserService;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.SearchResult;
import com.ejlchina.searcher.param.Operator;
import com.ejlchina.searcher.util.MapBuilder;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

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

/**
 * @author chan
 * @date 2022/9/27 4:42 PM
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/manage/user")
public class CmsUserController{

    private final HttpServletRequest request;

    private final BeanSearcher beanSearcher;

    private final UserFuncPropertyMapper userFuncPropertyMapper;

    private final UserMapper userMapper;

    private final UserBindDetailMapper userBindDetailMapper;

    private final GroupRelationClearService groupRelationClearService;

    private final GroupsRelationMapper groupsRelationMapper;

    private final UserBindRelationService userBindRelationService;

    private final CorpUserFollowRelationMapper cmsUserFollowRelationMapper;

    private final OrderDonMapper orderDonMapper;

    private final UserBenefitsService userBenefitsService;

    private final UserPayOrderBlockService userPayOrderBlockService;

    private final CmsUserMapper cmsUserMapper;

    private final UserCertRecordMapper userCertRecordMapper;

    private final UserDoubleVerifyCodeChangeRecordMapper userDoubleVerifyCodeChangeRecordMapper;

    private final VipUserMapper vipUserMapper;

    private final CmsVipUserService cmsVipUserService;

    private final List<Long> no_blacks_userIds = List.of(375274l, 545599l, 523937l, 507498l, 604146l, 613437l, 651728l, 614100l, 604148l);

    @GetMapping("/get")
    public Result<SearchResult<UserView>> get(Long id, String otherPhone, Long sharedId, String userid, Long businessId, String sort, String order, Boolean isCert, Boolean isAbroad, Boolean isVip) {
        MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
        String otherSql = StrUtil.EMPTY;
        if (StrUtil.isNotBlank(otherPhone)) {
            otherSql += String.format("(u.id in (select user_id from user_bind_detail where phone like '%s%%') or u.login_phone like '%s%%')", otherPhone, otherPhone);
        }
        if (businessId != null) {
            if (StrUtil.isNotBlank(otherSql)) {
                otherSql += " and ";
            }
            otherSql += String.format("us.shared_id in (select user_id from user_distribute where business_id = %s)", businessId);
        }
        if (id != null) {
            List<Long> relationUserIdList = null;
            try {
                relationUserIdList = userBindRelationService.getRelationUserIdList(id, null);
            } catch (Exception e) {
            }
            if (CollUtil.isNotEmpty(relationUserIdList)) {
                builder.field(UserView::getId, relationUserIdList).op(Operator.InList);
            }
        }
        if (isCert != null) {
            if (StrUtil.isNotBlank(otherSql)) {
                otherSql += " and ";
            }
            otherSql += "exists (select 1 from user_cert_record where user_id = u.id)";
        }
        if (isAbroad != null) {
            if (StrUtil.isNotBlank(otherSql)) {
                otherSql += " and ";
            }
            otherSql += String.format(" %s (select 1 from phone_code pc where pc.phone = u.login_phone and cid is not null and cid != 86)", isAbroad ? "exists" : "not exists");
        }
        if (isVip != null) {
            if (StrUtil.isNotBlank(otherSql)) {
                otherSql += " and ";
            }
            otherSql += String.format(" %s (select 1 from vip_user vu where vu.user_id = u.id and vu.expiry_time > now())", isVip ? "exists" : "not exists");
        }
        if (StrUtil.isNotBlank(otherSql)) {
            builder.put("otherConditionSql", otherSql);
        }
        DateTime now = DateTime.now();
        SearchResult<UserView> search = beanSearcher.search(UserView.class, builder.build());
        search.getDataList().forEach(data -> {
            Long userId = data.getId();
            UserBindDetail userBindDetail = beanSearcher.searchFirst(UserBindDetail.class, MapUtils.builder().field(UserBindDetail::getUserId, userId).onlySelect(UserBindDetail::getPhone, UserBindDetail::getEmail).build());
            Optional.ofNullable(userBindDetail).ifPresent(bind -> {
                data.setBindEmail(bind.getEmail());
                data.setBindPhone(bind.getPhone());
            });
            if (data.getSharedId() != null) {
                UserDistributeBusinessInfoView userDistributeBusinessInfoView = beanSearcher.searchFirst(UserDistributeBusinessInfoView.class, MapUtils.builder().field(UserDistributeBusinessInfoView::getUserId, data.getSharedId()).build());
                Optional.ofNullable(userDistributeBusinessInfoView).ifPresent(info -> {
                    data.setDistributeName(info.getDistributeName());
                    data.setBusinessName(info.getBusinessName());
                });
            }
            Integer selectCount = userCertRecordMapper.selectCount(Wrappers.lambdaQuery(UserCertRecord.class)
                    .eq(UserCertRecord::getUserId, userId));
            data.setIsCert(selectCount > 0 ? true : false);
            VipUser vipUser = vipUserMapper.selectOne(Wrappers.lambdaQuery(VipUser.class)
                    .eq(VipUser::getUserId, userId)
                    .last("limit 1"));
            if (vipUser != null && vipUser.getExpiryTime().after(now)) {
                data.setIsVip(true);
                data.setVipExpiryTime(vipUser.getExpiryTime());
            }
        });
        return GatewayResponse.SUCCESS.newBuilder().toResult(search);
    }

    /**
     * 查看排除绑定重复用户数 真实用户数
     * 会员用户数
     */
    @GetMapping("/get/userNum")
    public Result<UserNumJhView> getUserNum() {
        UserNumJhView userNumJhView = new UserNumJhView();
        Integer unBindUserNum = userMapper.selectUnBindUserNum();
        Integer bindUserNum = userBindDetailMapper.selectCount(null);
        userNumJhView.setRealUserNum(unBindUserNum + bindUserNum);
        userNumJhView.setVipNum(vipUserMapper.selectCount(Wrappers.lambdaQuery(VipUser.class)
                .gt(VipUser::getExpiryTime, DateTime.now())));
        return GatewayResponse.SUCCESS.newBuilder().toResult(userNumJhView);
    }

    /**
     * 修改用户的拉黑状态
     */
    @PutMapping("/put/black/status/{id}")
    @SaCheckPermission("user:black")
    @Log(module = "用户管理/拉黑用户", businessType = BusinessType.PUT, isSaveRequestData = true)
    public Result<String> putBlackStatus(@PathVariable Long id) {
        if (no_blacks_userIds.contains(id)) {
            throw BusinessRuntimeException.getInstance("张凯已处理");
        }
        User user = userMapper.selectById(id);
        Optional.ofNullable(user).ifPresent(u -> {
            u.setIsBlack(!u.getIsBlack());
            if (u.getIsBlack()) {
                List<Long> userIds = userBindRelationService.getRelationUserIdList(id, user);
                List<RenewalView> groupsRelations = beanSearcher.searchAll(RenewalView.class, MapUtils.builder()
                        .field(RenewalView::getUserId, 0).op(Operator.GreaterThan)
                        .field(RenewalView::getUserId, userIds).op(Operator.InList)
                        .field(RenewalView::getStatus, List.of("validity", "overdue", "outside")).op(Operator.InList)
                        .orderBy(RenewalView::getExpiryTime).asc()
                        .build());
                groupsRelations.forEach(ticket -> {
                    GroupsRelation relation = groupsRelationMapper.selectById(ticket.getRelationId());
                    groupRelationClearService.clearTicket(relation, UserTicketClearedRecord.Source.black);
                });
                //清会员
                Optional.ofNullable(vipUserMapper.selectOne(Wrappers.lambdaQuery(VipUser.class)
                        .in(VipUser::getUserId, userIds)
                        .gt(VipUser::getExpiryTime, DateTime.now())
                        .last("limit 1"))).ifPresent(vipUser -> {
                    //设置当天拉黑的时间
                    vipUser.setExpiryTime(DateUtil.beginOfDay(DateTime.now()));
                    vipUserMapper.updateById(vipUser);
                });
            }
            userMapper.updateById(u);
        });
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

    /**
     * 修改用户查看验证码次数
     */
    @PutMapping("/put/verifyCheck/num")
    public Result<String> updateCheckCodeNum(@RequestBody UserFuncPropertyReq req) {
        if (req.getUserId() == null) throw BusinessRuntimeException.getInstance("用户id为空");
        if (req.getVerifyCheckNum() == null || req.getVerifyCheckNum() < 0) {
            throw BusinessRuntimeException.getInstance("请输入正确的查看验证码次数");
        }
        UserFuncProperty userFuncProperty = userFuncPropertyMapper.selectOne(Wrappers.lambdaQuery(UserFuncProperty.class)
                .eq(UserFuncProperty::getUserId, req.getUserId()).last("limit 1"));
        Boolean isFirst = false;
        if (userFuncProperty == null) {
            try {
                userFuncProperty = new UserFuncProperty();
                userFuncProperty.setUserId(req.getUserId());
                userFuncProperty.setVerifyCheckNum(req.getVerifyCheckNum());
                userFuncPropertyMapper.insert(userFuncProperty);
                isFirst = true;
            } catch (DuplicateKeyException e) {

            }
        }
        if (isFirst || (userFuncProperty.getVerifyCheckNum() != req.getVerifyCheckNum())) {
            long adminId = StpUtil.getLoginIdAsLong();
            UserDoubleVerifyCodeChangeRecord userDoubleVerifyCodeChangeRecord = new UserDoubleVerifyCodeChangeRecord();
            userDoubleVerifyCodeChangeRecord.setUserId(req.getUserId());
            Optional.ofNullable(cmsUserMapper.selectById(adminId))
                    .ifPresent(cu -> userDoubleVerifyCodeChangeRecord.setOperator(cu.getNickname()));
            userDoubleVerifyCodeChangeRecord.setOldVerifyCheckNum(isFirst ? 1 : userFuncProperty.getVerifyCheckNum());
            userDoubleVerifyCodeChangeRecord.setVerifyCheckNum(req.getVerifyCheckNum());
            userDoubleVerifyCodeChangeRecordMapper.insert(userDoubleVerifyCodeChangeRecord);
        }
        userFuncProperty.setVerifyCheckNum(req.getVerifyCheckNum());
        userFuncPropertyMapper.updateById(userFuncProperty);
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

    /**
     * 查看用户验证码次数
     */
    @GetMapping("/get/verifyCheck/num")
    public Result<Integer> getVerifyCheckNum(Long userId) {
        if (userId==null) throw BusinessRuntimeException.getInstance("用户id为空");
        UserFuncProperty userFuncProperty = userFuncPropertyMapper.selectOne(Wrappers.lambdaQuery(UserFuncProperty.class)
                .eq(UserFuncProperty::getUserId, userId).last("limit 1"));
        //默认0次
        Integer verifyCheckNum = 0;
        if (userFuncProperty != null) verifyCheckNum = userFuncProperty.getVerifyCheckNum();
        return GatewayResponse.SUCCESS.newBuilder().toResult(verifyCheckNum);
    }

    /**
     * 用户验证码更变记录列表展示
     */
    @GetMapping("/get/verifyCode/change/list/{userId}")
    public Result<SearchResult<UserDoubleVerifyCodeChangeRecord>> getUserDoubleVerifyCodeChangeRecordByUserId(@PathVariable Long userId) {
        SearchResult<UserDoubleVerifyCodeChangeRecord> search = beanSearcher.search(UserDoubleVerifyCodeChangeRecord.class, MapUtils.flatBuilder(request.getParameterMap())
                .field(UserDoubleVerifyCodeChangeRecord::getUserId, userId)
                .orderBy(UserDoubleVerifyCodeChangeRecord::getId).desc()
                .build());
        return GatewayResponse.SUCCESS.newBuilder().toResult(search);
    }


    /**
     * 用户加入企业微信客服详情
     */
    @GetMapping("/get/corpFollow/detail/{userId}")
    public Result<String> getCorpFollowDetailById(@PathVariable Long userId) {
        User user = userMapper.selectById(userId);
        if (user == null || StrUtil.isEmpty(user.getUnionid())) {
            return GatewayResponse.SUCCESS.newBuilder().toResult();
        }
        Long wxCorpId = 2l;
        String corpCustomers = cmsUserFollowRelationMapper.selectCorpCustomers(user.getUnionid(), wxCorpId);
        return GatewayResponse.SUCCESS.newBuilder().toResult(corpCustomers);
    }

    /**
     * 企业微信客服列表
     */
    @GetMapping("/get/corpFollow")
    public Result<List<CorpFollow>> getCorpFollow() {
        List<CorpFollow> corpFollows = beanSearcher.searchAll(CorpFollow.class, MapUtils.flatBuilder(request.getParameterMap())
                .field(CorpFollow::getWxCorpId, 2)
                .build());
        return GatewayResponse.SUCCESS.newBuilder().toResult(corpFollows);
    }

    /**
     * 用户订单详情title
     */
    @GetMapping("/get/order/title")
    public Result<UserView> getUserOrderDetailTitle(Long userId) {
        UserView userView = new UserView();
        List<OrderDon> orderDons = orderDonMapper.selectList(Wrappers.lambdaQuery(OrderDon.class)
                .eq(OrderDon::getUserId, userId)
                .notIn(OrderDon::getStatus, Constant.noOrderStatus)
                .orderByAsc(OrderDon::getId));
        //首单产品
        Optional<OrderDon> firstOrder = orderDons.stream().filter(don -> don.getStatus() != OrderDon.Status.refund).findFirst();
        if (firstOrder.isPresent()) {
            OrderDon orderDon = firstOrder.get();
            BigDecimal money = orderDon.getMoney().divide(BigDecimal.valueOf(100));
            Optional.ofNullable(beanSearcher.searchFirst(GoodsDonSkuView.class, MapUtils.builder().field(GoodsDonSkuView::getSkuId, orderDon.getSkuId()).onlySelect(GoodsDonSkuView::getGoodsTitle, GoodsDonSkuView::getSpecVal).build()))
                    .ifPresent(goodsDonSkuView -> {
                        String msg = String.format("%s%s %s元", goodsDonSkuView.getGoodsTitle(), goodsDonSkuView.getSpecVal(), money);
                        if (orderDon.getCouponUserId() != 0) {
                            BigDecimal subMoney = orderDon.getCouponMoney().divide(BigDecimal.valueOf(100));
                            msg = String.format("%s（减免%s元）", msg, subMoney);
                        }
                        userView.setFirstOrderDetail(msg);
                    });
        }
        //有无路由器订单
        Optional<OrderDon> routeOrder = orderDons.stream().filter(don -> don.getGoodsId() == 15).findFirst();
        userView.setIsHadRouteOrder(routeOrder.isPresent() ? true : false);

        Integer noRefundOrders = 0;
        Integer refundOrders = 0;
        //除去退款 下单金额
        BigDecimal orderMoney = BigDecimal.ZERO;
        BigDecimal refundMoney = BigDecimal.ZERO;
        for (OrderDon orderDon : orderDons) {
            if (orderDon.getStatus() == OrderDon.Status.refund) {
                refundOrders++;
                if (orderDon.getRefundMoney() != null) {
                    refundMoney = refundMoney.add(orderDon.getRefundMoney());
                }
            }else {
                noRefundOrders++;
                orderMoney = orderMoney.add(orderDon.getMoney());
            }
        }
        BigDecimal refundRate = BigDecimal.ZERO;
        if (!orderDons.isEmpty()) {
            //退款率
            refundRate = BigDecimal.valueOf(refundOrders).divide(BigDecimal.valueOf(orderDons.size()), 2, RoundingMode.HALF_UP);
        }
        userView.setOrderMoney(orderMoney);
        userView.setNumOfOrder(noRefundOrders);
        userView.setRefundMoney(refundMoney);
        userView.setRefundRate(refundRate);
        return GatewayResponse.SUCCESS.newBuilder().toResult(userView);
    }

    /**
     * 用户下单详情
     */
    @GetMapping("/get/order/list")
    public Result<SearchResult<UserOrderDonDetail>> getUserOrderDetails() {
        SearchResult<UserOrderDonDetail> search = beanSearcher.search(UserOrderDonDetail.class, MapUtils.flatBuilder(request.getParameterMap())
                .field(UserOrderDonDetail::getStatus, Constant.noOrderAllStatus).op(Operator.NotIn)
                .build());
        return GatewayResponse.SUCCESS.newBuilder().toResult(search);
    }

    /**
     * 问卷回答列表
     */
    @GetMapping("/get/question/response/list")
    public Result<List<QuestionResponseRecordView>> getQuestionResponseList(String first, String end) {
        String timeSql = StrUtil.EMPTY;
        if (StrUtil.isNotBlank(first)) {
            timeSql += String.format(" and created_time >= '%s'", first);
        }
        if (StrUtil.isNotBlank(end)) {
            timeSql += String.format(" and created_time < '%s'", end);
        }
        MapBuilder builder = MapUtils.builder();
        if (StrUtil.isNotBlank(timeSql)) {
            builder.put("time", timeSql);
        }
        List<QuestionResponseRecordView> views = beanSearcher.searchAll(QuestionResponseRecordView.class, builder.build());
        return GatewayResponse.SUCCESS.newBuilder().toResult(views);
    }

    /**
     * 余额扣除
     */
    @PutMapping("/sub/balance")
    @Transactional(rollbackFor = Throwable.class)
    @Log(module = "用户管理/扣除用户余额", businessType = BusinessType.PUT, isSaveRequestData = true)
    public Result<String> subBalance(@RequestBody @Validated UserBalanceReq balanceReq) {
        BigDecimal deductBalance = balanceReq.getDeductBalance();
        if (deductBalance.compareTo(BigDecimal.ZERO) <= 0) {
            throw BusinessRuntimeException.getInstance("请扣除正确的余额数值");
        }
        long adminId = StpUtil.getLoginIdAsLong();
        CmsUser cmsUser = cmsUserMapper.selectById(adminId);
        Long userId = balanceReq.getUserId();
        User user = userMapper.selectById(userId);
        Assert.notNull(user, "用户不存在");
        if (user.getBalance().compareTo(deductBalance) < 0) {
            throw BusinessRuntimeException.getInstance("用户余额不足");
        }
        int update = userMapper.update(null, Wrappers.lambdaUpdate(User.class)
                .set(User::getBalance, user.getBalance().subtract(deductBalance))
                .eq(User::getId, userId)
                .eq(User::getBalance, user.getBalance()));
        if (update == 0) {
            throw BusinessRuntimeException.getInstance("扣除用户余额失败,请重试...");
        }
        userBenefitsService.recordBalanceBySource(userId, deductBalance.negate(), UserBalanceSourceRecord.Source.manual, null, UserBalanceSourceRecord.Source.manual.getDesc(), balanceReq.getRemark(), cmsUser.getNickname());
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

    /**
     * 增加余额
     */
    @PutMapping("/add/balance")
    @Transactional(rollbackFor = Throwable.class)
    @Log(module = "用户管理/增加用户余额", businessType = BusinessType.PUT, isSaveRequestData = true)
    public Result<String> addBalance(@RequestBody @Validated UserBalanceReq balanceReq) {
        long adminId = StpUtil.getLoginIdAsLong();
        CmsUser cmsUser = cmsUserMapper.selectById(adminId);
        Assert.notNull(cmsUser, "请重新登录");
        BigDecimal deductBalance = balanceReq.getDeductBalance();
        if (deductBalance.compareTo(BigDecimal.ZERO) <= 0) {
            throw BusinessRuntimeException.getInstance("请增加正确的余额数值");
        }
        Long userId = balanceReq.getUserId();
        User user = userMapper.selectById(userId);
        Assert.notNull(user, "用户不存在");
        int update = userMapper.update(null, Wrappers.lambdaUpdate(User.class)
                .set(User::getBalance, user.getBalance().add(deductBalance))
                .eq(User::getId, userId)
                .eq(User::getBalance, user.getBalance()));
        if (update == 0) {
            throw BusinessRuntimeException.getInstance("增加用户余额失败,请重试...");
        }
        userBenefitsService.recordBalanceBySource(userId, deductBalance, UserBalanceSourceRecord.Source.add, null, UserBalanceSourceRecord.Source.add.getDesc(), balanceReq.getRemark(), cmsUser.getNickname());
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

    /**
     * 新增用户下单拉黑记录
     */
    @PostMapping("/userOrder/block")
    public Result<String> blockUserOrder(@RequestBody UserPayOrderBlock payOrderBlock) throws AlipayApiException {
        String orderNo = payOrderBlock.getOrderNo();
        Assert.notEmpty(orderNo, "请输入订单号");
        userPayOrderBlockService.blockUserOrder(payOrderBlock);
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

    /**
     * 删除用户下单拉黑记录
     */
    @DeleteMapping("/userOrder/{id}")
    public Result<String> delBlockUserOrder(@PathVariable Long id) {
        userPayOrderBlockService.removeById(id);
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

    /**
     * 用户下单拉黑 列表
     */
    @GetMapping("/userOrder")
    public Result<SearchResult<UserPayOrderBlock>> getBlockUserOrder() {
        SearchResult<UserPayOrderBlock> search = beanSearcher.search(UserPayOrderBlock.class, MapUtils.flatBuilder(request.getParameterMap()).build());
        return GatewayResponse.SUCCESS.newBuilder().toResult(search);
    }

    /**
     * 用户每日活跃登录记录
     */
    @GetMapping("/get/user/login/record/{userId}")
    public Result<SearchResult<UserLoginRecord>> getUserLoginRecord(@PathVariable Long userId) {
        SearchResult<UserLoginRecord> search = beanSearcher.search(UserLoginRecord.class, MapUtils.flatBuilder(request.getParameterMap()).field(UserLoginRecord::getUserId, userId)
                .orderBy(UserLoginRecord::getCreatedTime).desc()
                .build());
        return GatewayResponse.SUCCESS.newBuilder().toResult(search);
    }

    /**
     * 大额度用户 列表
     */
    @GetMapping("/get/consume/large/user")
    public Result<SearchResult<UserView>> getLargeConsumer() {
        MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
        String largeLimit = "200000";
        String fu = String.format("(select distinct user_id from order_don o where o.relation_id != 0 and o.status not in ('close','noPayment','refund') group by user_id, date_format(o.created_time,'%%Y-%%m-%%d')" +
                "having sum(money) > %s) ln inner join", largeLimit);
        String fuOn = " on ln.user_id = u.id";
        builder.put("fu", fu);
        builder.put("fu_on", fuOn);
        SearchResult<UserView> search = beanSearcher.search(UserView.class, builder.build());
        return GatewayResponse.SUCCESS.newBuilder().toResult(search);
    }

    /**
     * 是否有最新的用户产生
     */
    @GetMapping("/get/consume/large/newUser")
    public Result<Boolean> getLargeNewConsumer() {
        String largeLimit = "200000";
        DateTime beginOfDay = DateUtil.beginOfDay(DateTime.now());
        Integer newConsumerCount = userMapper.getLargeNewConsumer(beginOfDay, largeLimit);
        return GatewayResponse.SUCCESS.newBuilder().toResult(newConsumerCount > 0 ? true : false);
    }

    /**
     * 超过恶意用户列表
     * 使用五个以上得支付宝
     */
    @GetMapping("/get/malice/user")
    public Result<SearchResult<MaliceUserView>> getMaliceUser() {
        MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
        SearchResult<MaliceUserView> search = beanSearcher.search(MaliceUserView.class, builder
                .orderBy(MaliceUserView::getId).asc()
                .build());
        return GatewayResponse.SUCCESS.newBuilder().toResult(search);
    }

    /**
     * 是否有最新恶意用户
     */
    @GetMapping("get/malice/user/newUser")
    public Result<Boolean> getNewMaliceUser() {
        DateTime beginOfDay = DateUtil.beginOfDay(DateTime.now());
        Integer newConsumerCount = userMapper.getNewMaliceUser(beginOfDay);
        return GatewayResponse.SUCCESS.newBuilder().toResult(newConsumerCount > 0 ? true : false);
    }

    /**
     * 用户ip列表
     */
    @GetMapping("/get/ip/list")
    public Result<SearchResult<OrderDonLocationRelateView>> orderDonLocationRelateResult(Long userId) {
        if (userId == null) {
            return GatewayResponse.SUCCESS.newBuilder().toResult();
        }
        List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
        SearchResult<OrderDonLocationRelateView> search = beanSearcher.search(OrderDonLocationRelateView.class, MapUtils.flatBuilder(request.getParameterMap()).put("userId", String.format("where user_id in (%s)", userIdList.toString().replaceAll("\\[", "").replaceAll("]", ""))).build());
        return GatewayResponse.SUCCESS.newBuilder().toResult(search);
    }

    /**
     * 用户支付宝列表
     */
    @GetMapping("/get/zfb/list")
    public Result<List<OrderDonBuyerView>> getZfbBuyers(Long userId) {
        if (userId == null) {
            return GatewayResponse.SUCCESS.newBuilder().toResult();
        }
        List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
        List<OrderDonBuyerView> orderDonBuyerViews = beanSearcher.searchAll(OrderDonBuyerView.class, MapUtils.flatBuilder(request.getParameterMap()).field(OrderDonBuyerView::getUserId, userIdList).op(Operator.InList).build());
        return GatewayResponse.SUCCESS.newBuilder().toResult(orderDonBuyerViews);
    }

    /**
     * 每月买过两单奈飞账号用户列表
     */
    @GetMapping("/get/more/netflix/user")
    public Result<SearchResult<UserNfView>> getMoreNetflixUser() {
        SearchResult<UserNfView> search = beanSearcher.search(UserNfView.class, MapUtils.flatBuilder(request.getParameterMap()).build());
        search.getDataList().forEach(data -> {
            Long userId = data.getId();
            UserBindDetail userBindDetail = beanSearcher.searchFirst(UserBindDetail.class, MapUtils.builder().field(UserBindDetail::getUserId, userId).onlySelect(UserBindDetail::getPhone, UserBindDetail::getEmail).build());
            Optional.ofNullable(userBindDetail).ifPresent(bind -> {
                data.setBindEmail(bind.getEmail());
                data.setBindPhone(bind.getPhone());
            });
        });
        return GatewayResponse.SUCCESS.newBuilder().toResult(search);
    }

    /**
     * 手动扣除用户操作记录
     */
    @GetMapping("/get/user/balance/sys/operate/record")
    public Result<SearchResult<UserBalanceSourceRecord>> sysOperate() {
        SearchResult<UserBalanceSourceRecord> search = beanSearcher.search(UserBalanceSourceRecord.class, MapUtils.flatBuilder(request.getParameterMap())
                .field(UserBalanceSourceRecord::getSource, List.of(UserBalanceSourceRecord.Source.manual.name(), UserBalanceSourceRecord.Source.add.name())).op(Operator.InList)
                .orderBy(UserBalanceSourceRecord::getId).desc()
                .build());
        return GatewayResponse.SUCCESS.newBuilder().toResult(search);
    }

    /**
     * 后台 开通会员
     */
    @PostMapping("/open/vip")
    public Result<String> openVip(@RequestBody OpenVipReq openVipReq) {
        long adminId = StpUtil.getLoginIdAsLong();
        openVipReq.setAdminId(adminId);
        cmsVipUserService.openVip(openVipReq);
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }
}
