package com.srs.comprehensive.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import com.srs.comprehensive.mapper.CphProRankingAllMapper;
import com.srs.comprehensive.domain.CphProRankingAll;
import com.srs.comprehensive.service.ICphProRankingAllService;

import static com.srs.common.utils.DateUtils.getNowDate;
import static com.srs.common.utils.SecurityUtils.getUsername;

/**
 * 总学分绩排名Service业务层处理
 *
 * @author srs
 * @date 2025-07-10
 */
@Service
public class CphProRankingAllServiceImpl extends ServiceImpl<CphProRankingAllMapper, CphProRankingAll> implements ICphProRankingAllService {
    @Autowired
    private CphProRankingAllMapper cphProRankingAllMapper;

    public String importData(List<CphProRankingAll> list) {
        try {
            if (list.isEmpty()) {
                throw new Exception("导入数据不能为空！");
            }

            // 获取所有学号
            List<String> stuNoList = list.stream()
                    .map(CphProRankingAll::getStuNo)
                    .distinct()
                    .collect(Collectors.toList());

            // 查询数据库中已存在的记录
            QueryWrapper<CphProRankingAll> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("stu_no", stuNoList);
            List<CphProRankingAll> dbList = cphProRankingAllMapper.selectList(queryWrapper);

            // 构建数据库中学号的Set，用于快速查找
            Set<String> dbStuNoSet = dbList.stream()
                    .map(CphProRankingAll::getStuNo)
                    .collect(Collectors.toSet());

            // 分离需要插入和更新的数据
            List<CphProRankingAll> insertList = new ArrayList<>();
            List<CphProRankingAll> updateList = new ArrayList<>();

            for (CphProRankingAll item : list) {
                if (dbStuNoSet.contains(item.getStuNo())) {
                    // 更新操作：找到数据库中对应的记录并更新
                    CphProRankingAll dbItem = dbList.stream()
                            .filter(db -> db.getStuNo().equals(item.getStuNo()))
                            .findFirst()
                            .orElse(null);
                    if (dbItem != null) {
                        // 更新已有记录
                        dbItem.setUpdateDate(getNowDate());
                        dbItem.setUpdateBy(getUsername());
                        dbItem.setCourseCredit(item.getCourseCredit());
                        dbItem.setTotalCredit(item.getTotalCredit());
                        dbItem.setTotalScore(item.getTotalScore());
                        dbItem.setCourseNum(item.getCourseNum());
                        dbItem.setAvgScore(item.getAvgScore());
                        dbItem.setAvgCredit(item.getAvgCredit());
                        dbItem.setRanking(item.getRanking());
                        dbItem.setNopass(item.getNopass());
                        updateList.add(dbItem);
                    }
                } else {
                    // 插入操作：设置创建信息
                    item.setCreateDate(getNowDate());
                    item.setCreateBy(getUsername());
                    insertList.add(item);
                }
            }

            // 批量插入新记录
            if (!insertList.isEmpty()) {
                boolean res = this.saveBatch(insertList);
                if(!res){
                    throw new Exception("新增数据失败！");
                }
            }

            // 批量更新已有记录
            if (!updateList.isEmpty()) {
                boolean res = this.updateBatchById(updateList);
                if(!res){
                    throw new Exception("更新数据失败！");
                }
            }

            return "导入成功！新增 " + insertList.size() + " 条，更新 " + updateList.size() + " 条";
        } catch (Exception e) {
            return "导入失败：" + e.getMessage();
        }
    }

    /**
     * 查询总学分绩排名
     *
     * @param id 总学分绩排名主键
     * @return 总学分绩排名
     */
    @Override
    public CphProRankingAll selectCphProRankingAllById(Long id) {
        return cphProRankingAllMapper.selectCphProRankingAllById(id);
    }

    /**
     * 查询总学分绩排名列表
     *
     * @param cphProRankingAll 总学分绩排名
     * @return 总学分绩排名
     */
    @Override
    public List<CphProRankingAll> selectCphProRankingAllList(CphProRankingAll cphProRankingAll) {
        return cphProRankingAllMapper.selectCphProRankingAllList(cphProRankingAll);
    }

    /**
     * 新增总学分绩排名
     *
     * @param cphProRankingAll 总学分绩排名
     * @return 结果
     */
    @Override
    public int insertCphProRankingAll(CphProRankingAll cphProRankingAll) {
        return cphProRankingAllMapper.insertCphProRankingAll(cphProRankingAll);
    }

    /**
     * 修改总学分绩排名
     *
     * @param cphProRankingAll 总学分绩排名
     * @return 结果
     */
    @Override
    public int updateCphProRankingAll(CphProRankingAll cphProRankingAll) {
        return cphProRankingAllMapper.updateCphProRankingAll(cphProRankingAll);
    }

    /**
     * 批量删除总学分绩排名
     *
     * @param ids 需要删除的总学分绩排名主键
     * @return 结果
     */
    @Override
    public int deleteCphProRankingAllByIds(Long[] ids) {
        return cphProRankingAllMapper.deleteCphProRankingAllByIds(ids);
    }

    /**
     * 删除总学分绩排名信息
     *
     * @param id 总学分绩排名主键
     * @return 结果
     */
    @Override
    public int deleteCphProRankingAllById(Long id) {
        return cphProRankingAllMapper.deleteCphProRankingAllById(id);
    }
}
