package com.bizzan.bitrade.service;

import com.bizzan.bitrade.constant.AuditStatus;
import com.bizzan.bitrade.dao.AgentApplyDao;
import com.bizzan.bitrade.entity.AgentApply;
import com.bizzan.bitrade.entity.Member;
import com.bizzan.bitrade.entity.QAgentApply;
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.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 代理商申请业务层
 *
 * @author admin
 * @date 2026-05-14
 */
@Service
public class AgentApplyService {

    @Autowired
    private AgentApplyDao agentApplyDao;
    @Autowired
    private MemberService memberService;

    /**
     * 分页查询代理商申请列表
     *
     * @param predicate 查询条件
     * @param pageable  分页参数
     * @return 分页结果
     */
    @Transactional(readOnly = true)
    public Page<AgentApply> findAll(Predicate predicate, Pageable pageable) {
        return agentApplyDao.findAll(predicate, pageable);
    }

    /**
     * 查询用户是否有在途申请（待审核状态）
     *
     * @param memberId 会员ID
     * @return true=有在途申请, false=无
     */
    @Transactional(readOnly = true)
    public boolean hasPendingApply(Long memberId) {
        BooleanExpression predicate = QAgentApply.agentApply.memberId.eq(memberId)
                .and(QAgentApply.agentApply.auditStatus.eq(AuditStatus.AUDIT_ING));
        return agentApplyDao.findAll(predicate).iterator().hasNext();
    }

    /**
     * 根据ID查询单条申请记录
     *
     * @param id 申请ID
     * @return 申请记录，不存在返回 null
     */
    @Transactional(readOnly = true)
    public AgentApply findOne(Long id) {
        return agentApplyDao.findOne(id);
    }

    /**
     * 新增代理商申请
     *
     * @param agentApply 申请信息
     * @return 保存后的实体
     */
    @Transactional(rollbackFor = Exception.class)
    public AgentApply save(AgentApply agentApply) {
        return agentApplyDao.save(agentApply);
    }

    /**
     * 审核通过
     *
     * @param agentApply 申请记录
     */
    @Transactional(rollbackFor = Exception.class)
    public void auditPass(AgentApply agentApply) {
        // 更新审核状态为通过
        agentApply.setAuditStatus(AuditStatus.AUDIT_SUCCESS);
        agentApplyDao.save(agentApply);
        memberService.updateSuperPartner(agentApply.getMemberId(), "1");
    }

    /**
     * 审核拒绝
     *
     * @param agentApply   申请记录
     * @param rejectReason 拒绝原因
     */
    @Transactional(rollbackFor = Exception.class)
    public void auditReject(AgentApply agentApply, String rejectReason) {
        // 更新审核状态为失败，并记录原因
        agentApply.setAuditStatus(AuditStatus.AUDIT_DEFEATED);
        agentApply.setRejectReason(rejectReason);
        agentApplyDao.save(agentApply);
    }
}
