package com.cyksj.web.controller.manage.group;

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.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.annotation.Log;
import com.cyksj.common.annotation.NoSubmit;
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.manage.cms.CmsUserMapper;
import com.cyksj.model.entity.*;
import com.cyksj.model.manage.views.AccountView;
import com.cyksj.model.manage.views.GroupsRelationBackView;
import com.cyksj.model.request.*;
import com.cyksj.model.views.DisableAccountView;
import com.cyksj.model.views.GroupsRelationIndependentView;
import com.cyksj.model.views.GroupsRelationRechargeView;
import com.cyksj.model.views.OrderDonRenewView;
import com.cyksj.server.recharge.dto.TaskResult;
import com.cyksj.server.recharge.dto.TokenParseResult;
import com.cyksj.service.chatgpt.GptUserRechargeRecordService;
import com.cyksj.service.mange.gpt.GptRechargeService;
import com.cyksj.service.relation.GroupRelationClearService;
import com.cyksj.service.scheduler.SchedulerService;
import com.cyksj.web.controller.recharge.req.ParseTokenRequest;
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.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * admin/用户代充值列表
 * @author chan
 * @date 2022/9/27 6:45 PM
 */
@Slf4j
@RequestMapping("/manage/group/relation")
@RestController
@RequiredArgsConstructor
public class CmsGroupRelationController {

    private final BeanSearcher beanSearcher;

    private final HttpServletRequest request;

    private final SchedulerService schedulerService;

    private final GroupsRelationMapper groupsRelationMapper;

    private final CmsUserMapper cmsUserMapper;

    private final OrderDonMapper orderDonMapper;

    private final GoodsDonSkuMapper goodsDonSkuMapper;

    private final GroupsRelationIndependentRenewMapper groupsRelationIndependentRenewMapper;

    private final GroupRelationClearService groupRelationClearService;

    private final GptRechargeCardKeyMapper gptRechargeCardKeyMapper;

    private final GptUserRechargeRecordService gptUserRechargeRecordService;

    private final GptRechargeService gptRechargeService;

    @GetMapping("/get")
    public Result<List<GroupsRelationBackView>> get(){
        List<GroupsRelationBackView> search = beanSearcher.searchAll(GroupsRelationBackView.class, MapUtils.flatBuilder(request.getParameterMap())
                .field(GroupsRelationBackView::getIsVip, Boolean.FALSE)
                .field(GroupsRelationBackView::getStatus, List.of(GroupsRelation.Status.none.name(), GroupsRelation.Status.locking.name())).op(Operator.NotIn).build()
        );
        return GatewayResponse.SUCCESS.newBuilder().toResult(search);
    }

    /**
     * 账号被封,重新分配用户车票
     */
    @PutMapping("/disable/{groupsId}")
    @NoSubmit
    public Result<String> disable(@PathVariable Long groupsId) {
        schedulerService.assignUserGroupsRelation(groupsId);
        return GatewayResponse.SUCCESS.newBuilder().toResult("车队账号禁用成功");
    }

    /**
     * 代充平台 用户账号车票列表
     */
    @GetMapping("/get/recharge")
    public Result<SearchResult<GroupsRelationRechargeView>> getRechargeList(String rechargeStatus, String orderNo, Boolean isVipError) {
        MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
        if (StrUtil.isEmpty(rechargeStatus)) {
            builder.field(GroupsRelationRechargeView::getRechargeStatus).op(Operator.NotNull);
        }
        if (StrUtil.isNotBlank(orderNo)) {
            OrderDon orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
                    .eq(OrderDon::getOrderNo, orderNo)
                    .last("limit 1"));
            Long relationId = 0l;
            if (orderDon != null) {
                relationId = orderDon.getRelationId();
                builder.field(GroupsRelationRechargeView::getUserId, orderDon.getUserId());
            }
            builder.field(GroupsRelationRechargeView::getRelationId, relationId);
        }
        if (isVipError != null) {
            builder.field(GroupsRelationRechargeView::getRechargeStatus, GroupsRelation.RechargeStatus.recharge_error.name());
            if (isVipError) {
                builder.field(GroupsRelationRechargeView::getRechargeErrorInfo, "会员").op(Operator.Contain);
            } else {
                builder.put("errorInfo", "(gr.recharge_error_info is null or gr.recharge_error_info not like '%会员%')");
            }
        }
        SearchResult<GroupsRelationRechargeView> search = beanSearcher.search(GroupsRelationRechargeView.class, builder
                .field(GroupsRelationRechargeView::getStatus, List.of(GroupsRelation.Status.validity.name(), GroupsRelation.Status.outside.name())).op(Operator.InList)
                .build());
        search.getDataList().forEach(data -> {
            OrderDon orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
                    .eq(OrderDon::getUserId, data.getUserId())
                    .eq(OrderDon::getRelationId, data.getRelationId())
                    .notIn(OrderDon::getStatus, Constant.noOrderAllStatus)
                    .orderByDesc(OrderDon::getId)
                    .last("limit 1"));
            if (orderDon != null) {
                data.setOrderNo(orderDon.getOrderNo());
            }
        });
        return GatewayResponse.SUCCESS.newBuilder().toResult(search);
    }

    /**
     * 代充账号 状态变更
     */
    @PostMapping("/set/recharge")
    @Transactional(rollbackFor = Throwable.class)
    public Result<String> updateRechargeStatus(@RequestBody GroupsRelationRechargeView rechargeView) {
        long adminId = StpUtil.getLoginIdAsLong();
        Long relationId = rechargeView.getRelationId();
        String account = rechargeView.getAccount();
        String password = rechargeView.getPassword();
        GroupsRelation relation = groupsRelationMapper.selectById(relationId);
        Assert.notNull(relation, "代充车票不存在");
        if (relation.getRenewStatus() == null || relation.getRechargeStatus() == GroupsRelation.RechargeStatus.complete) {
            throw BusinessRuntimeException.getInstance("");
        }
        CmsUser cmsUser = cmsUserMapper.selectById(adminId);
        GroupsRelation.RechargeStatus relation_rechargeStatus = relation.getRechargeStatus();
        GroupsRelation.RechargeStatus rechargeStatus = rechargeView.getRechargeStatus();
        if (relation_rechargeStatus == rechargeStatus) {
            throw BusinessRuntimeException.getInstance("状态重复");
        }
        relation.setRechargeStatus(rechargeStatus);
        relation.setOperator(cmsUser.getNickname());
        //邀请制家庭组链接
        relation.setInviteLink(rechargeView.getInviteLink());
        if (StrUtil.isNotEmpty(account)) {
            relation.setAccount(account);
        }
        if (StrUtil.isNotEmpty(password)) {
            relation.setPassword(password);
        }
        String contact = rechargeView.getContact();
        if (StrUtil.isNotBlank(contact)) {
            relation.setContact(contact);
        }
        OrderDon orderDon = null;
        if (rechargeStatus == GroupsRelation.RechargeStatus.complete) {
            relation.setSendTime(DateTime.now());
            orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
                    .eq(OrderDon::getUserId, relation.getUserId())
                    .eq(OrderDon::getRelationId, relationId)
                    .notIn(OrderDon::getStatus, Constant.noOrderAllStatus)
                    .orderByDesc(OrderDon::getId)
                    .last("limit 1"));
            if (orderDon == null){
                orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
                        .eq(OrderDon::getUserId, relation.getUserId())
                        .eq(OrderDon::getRelationId, relationId)
                        .notIn(OrderDon::getStatus, Constant.noOrderStatus)
                        .orderByDesc(OrderDon::getId)
                        .last("limit 1"));
                if (orderDon == null) {
                    throw BusinessRuntimeException.getInstance("该代充订单不存在");
                }
            }
            if (orderDon.getStatus() == OrderDon.Status.refund) {
                throw BusinessRuntimeException.getInstance("该代充订单已退款");
            }
            orderDon.setStatus(OrderDon.Status.complete);

            orderDonMapper.updateById(orderDon);

            relation.setStartTime(DateTime.now());
            GoodsDonSku sku = goodsDonSkuMapper.selectById(orderDon.getSkuId());
            DateTime expiryTime;
            if (sku.getDays() != null && sku.getDays() > 0) {
                expiryTime = DateUtil.offsetDay(relation.getStartTime(), sku.getDays());
            } else {
                expiryTime = DateUtil.offsetMonth(relation.getStartTime(), sku.getMonths());
            }
            relation.setExpiryTime(expiryTime);
        }
        groupsRelationMapper.updateById(relation);
        //GPT代充
        if (orderDon != null) {
            //扣除次数
            Integer rechargeRemainNum = relation.getRechargeRemainNum();
            if (rechargeRemainNum != null && rechargeRemainNum > 0) {
                int update = groupsRelationMapper.update(null, Wrappers.lambdaUpdate(GroupsRelation.class)
                        .set(GroupsRelation::getRechargeRemainNum, rechargeRemainNum - 1)
                        .eq(GroupsRelation::getId, relationId)
                        .eq(GroupsRelation::getRechargeRemainNum, rechargeRemainNum));
                if (update == 0) {
                    throw BusinessRuntimeException.getInstance("更新用户代充剩余次数失败，请重试");
                }
                //记录gpt代充记录
                gptUserRechargeRecordService.recordGptUserRechargeNum(relation.getUserId(), relation.getId(), relation.getAccount(), -1, cmsUser != null ? cmsUser.getNickname() : null, "客服手动充值");
            }
        }
        return GatewayResponse.SUCCESS.newBuilder().toResult("状态修改成功");
    }

    /**
     * 代充账号 待处理列表
     */
    @GetMapping("/get/recharge/waiting")
    public Result<Boolean> getRechargeWaiting() {
        Number number = beanSearcher.searchCount(GroupsRelationRechargeView.class, MapUtils.flatBuilder(request.getParameterMap())
                .field(GroupsRelationRechargeView::getSpecialType, GoodsDon.SpecialType.recharge.name())
                .field(GroupsRelationRechargeView::getRechargeStatus, GroupsRelation.RechargeStatus.waiting.name())
                .build());
        if (number.intValue() > 0) {
            return GatewayResponse.SUCCESS.newBuilder().toResult(true);
        }
        return GatewayResponse.SUCCESS.newBuilder().toResult(false);
    }

    /**
     * GPT代充 设置剩余次数
     */
    @PutMapping("/recharge/update/remain/num")
    public Result<String> updateRechargeRemainNum(@RequestBody RechargeRemainNumReq req) {
        long adminId = StpUtil.getLoginIdAsLong();
        Long relationId = req.getRelationId();
        //正数是增加 负数是扣除
        Integer num = -req.getNum();
        GroupsRelation relation = groupsRelationMapper.selectById(relationId);
        if (relation.getRechargeNum() != null) {
            Integer rechargeRemainNum = relation.getRechargeRemainNum();
            if (rechargeRemainNum == 0 && num < 0) {
                throw BusinessRuntimeException.getInstance("剩余代充次数为0");
            }
            Integer subAfterNum = rechargeRemainNum - num;
            if (subAfterNum < 0) {
                throw BusinessRuntimeException.getInstance("扣除次数不能为负数");
            }
            int update = groupsRelationMapper.update(null, Wrappers.lambdaUpdate(GroupsRelation.class)
                    .set(GroupsRelation::getRechargeNum, relation.getRechargeNum() + req.getNum())
                    .set(GroupsRelation::getRechargeRemainNum, subAfterNum)
                    .eq(GroupsRelation::getId, relationId)
                    .eq(GroupsRelation::getRechargeRemainNum, rechargeRemainNum));
            if (update == 0) {
                throw BusinessRuntimeException.getInstance("修改用户代充次数错误，请重试");
            }
            //记录gpt代充记录
            CmsUser cmsUser = cmsUserMapper.selectById(adminId);
            gptUserRechargeRecordService.recordGptUserRechargeNum(relation.getUserId(), relation.getId(), relation.getAccount(), req.getNum(), cmsUser != null ? cmsUser.getNickname() : null, req.getRemark());
        }
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

    /**
     * 更新剩余次数 针对之前的代充账号
     */
    @PostMapping("/recharge/set/remainNumBf")
    public Result<String> setRechargeRemainNumBf(@RequestBody RechargeRemainNumReq req) {
        long adminId = StpUtil.getLoginIdAsLong();
        Long relationId = req.getRelationId();
        GroupsRelation relation = groupsRelationMapper.selectById(relationId);
        if (relation.getRechargeRemainNum() == null) {
            Integer num = req.getNum();
            if (num <= 0) {
                throw BusinessRuntimeException.getInstance("剩余次数需大于0");
            }
            relation.setRechargeNum(num);
            relation.setRechargeRemainNum(num);
            Date startTime = relation.getStartTime();
            DateTime now = DateTime.now();
            relation.setSubmitTime(startTime != null ? startTime : now);
            relation.setSendTime(relation.getSubmitTime());
            groupsRelationMapper.updateById(relation);
            //记录gpt代充记录
            CmsUser cmsUser = cmsUserMapper.selectById(adminId);
            gptUserRechargeRecordService.recordGptUserRechargeNum(relation.getUserId(), relation.getId(), relation.getAccount(), req.getNum(), cmsUser != null ? cmsUser.getNickname() : null, req.getRemark());
        }
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

    /**
     * GPT代充卡密列表
     */
    @GetMapping("/get/gpt/cardKey")
    public Result<SearchResult<GptRechargeCardKey>> getGptCardKey() {
        SearchResult<GptRechargeCardKey> search = beanSearcher.search(GptRechargeCardKey.class, MapUtils.flatBuilder(request.getParameterMap()).build());
        return GatewayResponse.SUCCESS.newBuilder().toResult(search);
    }



    /**
     * 编辑GPT代充卡密
     */
    @PutMapping("/update/gpt/cardKey")
    public Result<SearchResult<GptRechargeCardKey>> updateGptCardKey(@RequestBody GptRechargeCardKey cardKey) {
        Long id = cardKey.getId();
        GptRechargeCardKey gptRechargeCardKey = gptRechargeCardKeyMapper.selectById(id);
        if (gptRechargeCardKey == null) {
            throw BusinessRuntimeException.getInstance("卡密不存在");
        }
        gptRechargeCardKeyMapper.updateById(cardKey);
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }


    /**
     * 删除GPT代充卡密
     */
    @DeleteMapping("/del/gpt/cardKey/{id}")
    public Result<SearchResult<GptRechargeCardKey>> deleteGptCardKeyById(@PathVariable Long id) {
        GptRechargeCardKey gptRechargeCardKey = gptRechargeCardKeyMapper.selectById(id);
        if (gptRechargeCardKey == null) {
            throw BusinessRuntimeException.getInstance("卡密不存在");
        }
        if (gptRechargeCardKey.getStatus()) {
            throw BusinessRuntimeException.getInstance("已使用的卡密不可删除");
        }
        gptRechargeCardKeyMapper.deleteById(id);
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

    /**
     * 批量删除GPT代充卡密
     */
    @DeleteMapping("/batch/del/gpt/cardKey")
    public Result<SearchResult<GptRechargeCardKey>> batchDeleteGptCardKeyById(@RequestBody BatchDelCardKeyReq req) {
        List<Long> ids = req.getIds();
        ids.forEach(id -> {
            GptRechargeCardKey gptRechargeCardKey = gptRechargeCardKeyMapper.selectById(id);
            if (gptRechargeCardKey == null) {
                return;
            }
            if (gptRechargeCardKey.getStatus()) {
                return;
            }
            gptRechargeCardKeyMapper.deleteById(id);
        });
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }


    /**
     * 新增GPT代充卡密
     */
    @PostMapping("/post/gpt/cardKey")
    public Result<String> postGptCardKey(@RequestBody GptRechargeCardKeyReq req) {
        List<String> cardKey = req.getCardKey();
        cardKey.forEach(key -> {
            try {
                GptRechargeCardKey gptRechargeCardKey = new GptRechargeCardKey();
                gptRechargeCardKey.setCardKey(key);
                gptRechargeCardKeyMapper.insert(gptRechargeCardKey);
            } catch (DuplicateKeyException e) {

            }
        });
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

    /**
     * GPT代充操作记录
     */
    @GetMapping("/get/recharge/operate/record")
    public Result<List<GptUserRechargeNumRecord>> getGptUserRechargeNumRecord(Long relationId, Long userId) {
        GroupsRelation relation = groupsRelationMapper.selectById(relationId);
        if (relation.getSubmitTime() == null && relation.getStartTime() == null) {
            return GatewayResponse.SUCCESS.newBuilder().toResult();
        }
        Date filterDate = relation.getSubmitTime();
        if (filterDate == null) {
            filterDate = relation.getStartTime();
        }
        List<GptUserRechargeNumRecord> gptUserRechargeNumRecords = beanSearcher.searchAll(GptUserRechargeNumRecord.class, MapUtils.flatBuilder(request.getParameterMap())
                .field(GptUserRechargeNumRecord::getRelationId, relationId)
                .field(GptUserRechargeNumRecord::getUserId, userId)
                .field(GptUserRechargeNumRecord::getCreatedTime, filterDate).op(Operator.GreaterEqual)
                .build());
        return GatewayResponse.SUCCESS.newBuilder().toResult(gptUserRechargeNumRecords);
    }

    /**
     * 验证GPT代充凭证
     */
    @PostMapping("/parse-token")
    public Result<TokenParseResult> parseToken(@RequestBody ParseTokenRequest request) {
        TokenParseResult tokenParseResult = gptRechargeService.parseToken(request.getAccessToken());
        return GatewayResponse.SUCCESS.newBuilder().toResult(tokenParseResult);
    }

    /**
     * 确认充值
     */
    @PostMapping("/confirm")
    public Result<String> confirmRecharge(@RequestBody @Validated GroupsRelationRechargeReq req) {
        long adminId = StpUtil.getLoginIdAsLong();
        String taskId = gptRechargeService.confirmRecharge(adminId, req);
        return GatewayResponse.SUCCESS.newBuilder().toResult(taskId);
    }


    /**
     * 查询任务状态
     */
    @GetMapping("/task-status/{taskId}")
    public Result<TaskResult> getTaskStatus(@PathVariable String taskId) {
        return GatewayResponse.SUCCESS.newBuilder().toResult(gptRechargeService.getTaskResult(taskId));
    }

    /**
     * 订单号车票详情
     */
    @GetMapping("/get/order/relation")
    public Result<GroupsRelation> getOrderRelation(String orderNo) {
        GroupsRelation relation = gptRechargeService.getOrderRelation(orderNo);
        return GatewayResponse.SUCCESS.newBuilder().toResult(relation);
    }

    /**
     * GPT独立会员导入代充列表
     */
    @PostMapping("/gpt/independent/export/recharge")
    @Log(module = "账号管理/用户代充/导入GPT独立会员订单", businessType = BusinessType.POST, isSaveRequestData = true)
    public Result<String> gptIndependentExportRecharge(@RequestBody GptIndependentExportRechargeReq rechargeReq) {
        long adminId = StpUtil.getLoginIdAsLong();
        rechargeReq.setAdminId(adminId);
        gptRechargeService.gptIndependentExportRecharge(rechargeReq);
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }


    /**
     * Chat GPT独立规格续费 列表
     */
    @GetMapping("/get/chatGPT/independent/renew")
    public Result<SearchResult<GroupsRelationIndependentView>> getIndependentRenew(String account) {
        String condition = " o.sku_id in (select id from goods_don_sku sku where sku.goods_id in (18,26) and sku.num = 1)" +
                " and o.status not in ('close','noPayment','refund') and o.order_type = 2";
        if (StrUtil.isNotEmpty(account)) {
            List<AccountView> dbAccounts = beanSearcher.searchAll(AccountView.class, MapUtils.builder().field(AccountView::getAccount, account).op(Operator.Contain).build());
            if (CollUtil.isNotEmpty(dbAccounts)) {
                String collect = dbAccounts.stream().map(e -> String.valueOf(e.getGroupsId())).collect(Collectors.joining(","));
                condition += String.format(" and groups_id in (%s)", collect);
            }
        }
        SearchResult<GroupsRelationIndependentView> search = beanSearcher.search(GroupsRelationIndependentView.class, MapUtils.flatBuilder(request.getParameterMap())
                .put("condition", condition)
                .build());
        return GatewayResponse.SUCCESS.newBuilder().toResult(search);
    }

    /**
     * 编辑车票独立续费状态
     */
    @PutMapping("/update/independent/renew/status")
    public Result<String> updateRenewStatus(@RequestBody GroupsRelationIndependentView view) {
        long adminId = StpUtil.getLoginIdAsLong();
        Long relationId = view.getRelationId();
        Long userId = view.getUserId();
        Boolean isRenew = view.getIsRenew();
        if (ObjectUtil.hasEmpty(relationId, userId, isRenew)) {
            throw BusinessRuntimeException.getInstance("参数错误");
        }
        GroupsRelationIndependentRenew groupsRelationIndependentRenew = Optional.ofNullable(groupsRelationIndependentRenewMapper.selectOne(Wrappers.lambdaQuery(GroupsRelationIndependentRenew.class)
                .eq(GroupsRelationIndependentRenew::getOrderId, view.getOrderId())
                .eq(GroupsRelationIndependentRenew::getUserId, userId)
                .eq(GroupsRelationIndependentRenew::getRelationId, relationId).last("limit 1"))).orElse(new GroupsRelationIndependentRenew());
        CmsUser cmsUser = cmsUserMapper.selectById(adminId);
        if (cmsUser != null) {
            groupsRelationIndependentRenew.setOperator(cmsUser.getNickname());
        }
        groupsRelationIndependentRenew.setOrderId(view.getOrderId());

        if (groupsRelationIndependentRenew.getId() == null) {
            groupsRelationIndependentRenew.setRelationId(relationId);
            groupsRelationIndependentRenew.setUserId(userId);
            groupsRelationIndependentRenew.setIsRenew(isRenew);
            groupsRelationIndependentRenewMapper.insert(groupsRelationIndependentRenew);
        } else {
            groupsRelationIndependentRenew.setIsRenew(isRenew);
            groupsRelationIndependentRenewMapper.updateById(groupsRelationIndependentRenew);
        }
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

    /**
     * 独立账号续费记录
     */
    @GetMapping("/get/independent/renew/record")
    public Result<SearchResult<OrderDonRenewView>> getIndependentRenewRecord(Long userId, Long relationId) {
        if (ObjectUtil.hasEmpty(relationId, userId)) {
            throw BusinessRuntimeException.getInstance("参数错误");
        }
        SearchResult<OrderDonRenewView> search = beanSearcher.search(OrderDonRenewView.class, MapUtils.flatBuilder(request.getParameterMap())
                .field(OrderDonRenewView::getUserId, userId)
                .field(OrderDonRenewView::getRelationId, relationId)
                .field(OrderDonRenewView::getOrderType, 2)
                .field(OrderDonRenewView::getStatus, Constant.noOrderAllStatus).op(Operator.NotIn)
                .build());
        return GatewayResponse.SUCCESS.newBuilder().toResult(search);
    }

    /**
     * 删除用户对应车票
     */
    @DeleteMapping("/clear/ticket/{relationId}")
    @Log(module = "删除用户车票", businessType = BusinessType.DELETE, isSaveRequestData = true)
    public Result<String> clearUserTicket(@PathVariable Long relationId) {
        GroupsRelation relation = groupsRelationMapper.selectById(relationId);
        if (relation == null) {
            throw BusinessRuntimeException.getInstance("车票不存在");
        }
        groupRelationClearService.clearTicket(relation, UserTicketClearedRecord.Source.manual);
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

    /**
     * GPT PLUS 禁用账号列表
     */
    @GetMapping("/get/disable/account")
    public Result<SearchResult<DisableAccountView>> getDisableAccount() {
        SearchResult<DisableAccountView> search = beanSearcher.search(DisableAccountView.class, MapUtils.flatBuilder(request.getParameterMap())
                .field(DisableAccountView::getGoodsId, 18)
                .build());
        return GatewayResponse.SUCCESS.newBuilder().toResult(search);
    }
}