package com.bizzan.bitrade.controller.member;

import com.bizzan.bitrade.annotation.AccessLog;
import com.bizzan.bitrade.constant.AdminModule;
import com.bizzan.bitrade.constant.AuditStatus;
import com.bizzan.bitrade.constant.PageModel;
import com.bizzan.bitrade.controller.common.BaseAdminController;
import com.bizzan.bitrade.entity.AgentApply;
import com.bizzan.bitrade.entity.QAgentApply;
import com.bizzan.bitrade.model.screen.AgentApplyScreen;
import com.bizzan.bitrade.service.AgentApplyService;
import com.bizzan.bitrade.util.MessageResult;
import com.bizzan.bitrade.util.PredicateUtils;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.dsl.BooleanExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

import static org.springframework.util.Assert.notNull;

/**
 * 代理商申请管理后台接口（查询、审核通过、审核拒绝）
 *
 * @author admin
 * @date 2026-05-14
 */
@RestController
@RequestMapping("agent/apply")
public class AgentApplyAdminController extends BaseAdminController {

    @Autowired
    private AgentApplyService agentApplyService;

    /**
     * 分页查询代理商申请列表
     *
     * @param pageModel 分页参数
     * @param screen    筛选条件
     * @return 分页结果
     */
    @PostMapping("page-query")
    @AccessLog(module = AdminModule.MEMBER, operation = "分页查询代理商申请列表")
    public MessageResult pageQuery(PageModel pageModel, AgentApplyScreen screen) {
        // 1. 构建查询条件
        Predicate predicate = buildPredicate(screen);

        // 2. 执行分页查询
        Page<AgentApply> page = agentApplyService.findAll(predicate, pageModel.getPageable());
        return success(page);
    }

    /**
     * 查询代理商申请详情
     *
     * @param id 申请ID
     * @return 申请详情
     */
    @PostMapping("detail")
    @AccessLog(module = AdminModule.MEMBER, operation = "查询代理商申请详情")
    public MessageResult detail(@RequestParam("id") Long id) {
        // 1. 查询申请记录
        AgentApply agentApply = agentApplyService.findOne(id);
        notNull(agentApply, "申请记录不存在");
        return success(agentApply);
    }

    /**
     * 审核通过
     *
     * @param id 申请ID
     * @return 操作结果
     */
    @PatchMapping("{id}/pass")
    @AccessLog(module = AdminModule.MEMBER, operation = "代理商申请审核通过")
    public MessageResult pass(@PathVariable("id") Long id) {
        // 1. 查询申请记录
        AgentApply agentApply = agentApplyService.findOne(id);
        notNull(agentApply, "申请记录不存在");

        // 2. 校验当前状态
        if (AuditStatus.AUDIT_SUCCESS.equals(agentApply.getAuditStatus())) {
            return error("该申请已通过审核，请勿重复操作");
        }

        // 3. 执行审核通过
        agentApplyService.auditPass(agentApply);
        return success();
    }

    /**
     * 审核拒绝
     *
     * @param id           申请ID
     * @param rejectReason 拒绝原因
     * @return 操作结果
     */
    @PatchMapping("{id}/reject")
    @AccessLog(module = AdminModule.MEMBER, operation = "代理商申请审核拒绝")
    public MessageResult reject(
            @PathVariable("id") Long id,
            @RequestParam("rejectReason") String rejectReason) {
        // 1. 校验拒绝原因不能为空
        if (StringUtils.isEmpty(rejectReason)) {
            return error("请填写拒绝原因");
        }

        // 2. 查询申请记录
        AgentApply agentApply = agentApplyService.findOne(id);
        notNull(agentApply, "申请记录不存在");

        // 3. 校验当前状态
        if (AuditStatus.AUDIT_SUCCESS.equals(agentApply.getAuditStatus())) {
            return error("该申请已通过审核，无法拒绝");
        }

        // 4. 执行审核拒绝
        agentApplyService.auditReject(agentApply, rejectReason);
        return success();
    }

    /**
     * 构建 QueryDSL 查询条件
     *
     * @param screen 筛选参数
     * @return Predicate
     */
    private Predicate buildPredicate(AgentApplyScreen screen) {
        List<BooleanExpression> expressions = new ArrayList<>();
        QAgentApply qAgentApply = QAgentApply.agentApply;

        // 按审核状态筛选
        if (screen.getAuditStatus() != null) {
            expressions.add(qAgentApply.auditStatus.eq(screen.getAuditStatus()));
        }

        // 按关键词模糊搜索（姓名或手机号）
        if (!StringUtils.isEmpty(screen.getKeyword())) {
            expressions.add(
                qAgentApply.realName.like("%" + screen.getKeyword() + "%")
                    .or(qAgentApply.phone.like("%" + screen.getKeyword() + "%"))
            );
        }

        return PredicateUtils.getPredicate(expressions);
    }
}
