package org.dromara.main.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.main.domain.MainBackCandidate;
import org.dromara.main.domain.MainBackRecord;
import org.dromara.main.domain.MainStudent;
import org.dromara.main.domain.bo.MainBackRecordBo;
import org.dromara.main.domain.vo.MainBackRecordVo;
import org.dromara.main.mapper.MainBackCandidateMapper;
import org.dromara.main.mapper.MainBackRecordMapper;
import org.dromara.main.mapper.MainStudentMapper;
import org.dromara.main.service.IMainBackRecordService;
import org.springframework.stereotype.Service;

/**
 * 背调执行记录Service业务层处理
 */
@RequiredArgsConstructor
@Service
public class MainBackRecordServiceImpl implements IMainBackRecordService {

    private final MainBackRecordMapper baseMapper;
    private final MainStudentMapper studentMapper;
    private final MainBackCandidateMapper candidateMapper;


    @Override
    public TableDataInfo<MainBackRecordVo> queryPageList(Long orderId, MainBackRecordBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<MainBackRecord> lqw = new LambdaQueryWrapper<>();

        // 1. 按订单ID过滤
        lqw.eq(orderId != null, MainBackRecord::getOrderId, orderId);

        // 2. 按状态过滤
        lqw.eq(StrUtil.isNotBlank(bo.getStatus()), MainBackRecord::getStatus, bo.getStatus());

        // 3. 分页查询
        Page<MainBackRecordVo> pageResult = baseMapper.selectVoPage(pageQuery.build(), lqw);

        TableDataInfo<MainBackRecordVo> result = TableDataInfo.build(pageResult);

        for (MainBackRecordVo vo : result.getRows()) {
            // 1. 先查询候选人信息
            MainBackCandidate candidate = candidateMapper.selectById(vo.getCandidateId());

            if (candidate != null) {
                // 2. 通过 student_id 查询最新的学员信息
                MainStudent student = studentMapper.selectById(candidate.getStudentId());
                if (student != null) {
                    vo.setStudentNo(student.getStudentNo()); // 新增：学员编号
                    vo.setStudentName(student.getName());
                    vo.setStudentMobile(student.getMobile());
                    vo.setStudentIdCard(student.getIdCardNumber());
                    vo.setStudentGender(student.getGender());
                    vo.setStudentStatus(student.getStatus());
                    vo.setStudentUserType(student.getUserType()); // 新增：用户类型
                }
            }
        }

        return result;
    }
}
