package com.srs.comprehensive.service.impl;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.srs.common.core.domain.AjaxResult;
import com.srs.common.utils.DateUtils;
import com.srs.comprehensive.domain.*;
import com.srs.comprehensive.mapper.SchoolYearMapper;
import com.srs.comprehensive.mapper.SrsStuYearMapper;
import com.srs.comprehensive.mapper.SrsStudentMapper;
import com.srs.comprehensive.service.ISrsStuYearService;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 【学年表】Service业务层处理
 *
 * @author srs
 * @date 2023-06-28
 */
@Service
public class SrsStuYearServiceImpl implements ISrsStuYearService
{
    @Autowired
    private SrsStuYearMapper srsStuYearMapper;
    @Autowired
    private SchoolYearMapper schoolYearMapper;//学年中间表
    @Mapper
    private SrsStudentMapper srsStudentMapper;

    @Override
    public List<SrsStuYear> listEnableYear(){
        return srsStuYearMapper.listEnableYear();
    }

    @Override
    public AjaxResult listAllYear() {
        QueryWrapper<SrsStuYear> query = new QueryWrapper<>();
        query.orderByDesc("stu_year_name");
        List<SrsStuYear> list = srsStuYearMapper.selectList(query);
        return AjaxResult.success(list);
    }
    @Override
    public AjaxResult listQiyongYear() {
        List<SrsStuYear> list = srsStuYearMapper.selectQiYongList();
        return AjaxResult.success(list);
    }

    /**
     * 查询【请填写功能名称】
     *
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public SrsStuYear selectSrsStuYearById(Long id)
    {
        return srsStuYearMapper.selectSrsStuYearById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param srsStuYear 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<SrsStuYear> selectSrsStuYearList(SrsStuYear srsStuYear)
    {
        return srsStuYearMapper.selectSrsStuYearList(srsStuYear);
    }


    @Override
    public List<SrsStuYear> selectSrsStuYearLists() {
        return srsStuYearMapper.selectSrsStuYearLists();
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param srsStuYear 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertSrsStuYear(SrsStuYear srsStuYear)
    {
        srsStuYear.setCreateTime(DateUtils.getNowDate());
        return srsStuYearMapper.insertSrsStuYear(srsStuYear);
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param srsStuYear 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateSrsStuYear(SrsStuYear srsStuYear)
    {
        srsStuYear.setUpdateTime(DateUtils.getNowDate());
        return srsStuYearMapper.updateSrsStuYear(srsStuYear);
    }

    /**
     * 批量删除【请填写功能名称】
     *
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteSrsStuYearByIds(Long[] ids)
    {
        return srsStuYearMapper.deleteSrsStuYearByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteSrsStuYearById(Long id)
    {
        return srsStuYearMapper.deleteSrsStuYearById(id);
    }

    /**
     * 从中间表添加数据
     * @return
     */
    @Override
    public List<String> addStuYear() {
        List<SchoolYear> schoolYears = schoolYearMapper.selectSchoolYearAll();
        // List<SumSportTest> sumSportTests = sumSportTestMapper.selectSumSportTestAll();
        List<String> strings = new ArrayList<>();
        if (schoolYears.size()==0){
            strings.add("没有要处理的数据");
            return strings;
        }
        SrsStuYear srsStuYear = new SrsStuYear();
        //SrsSportTest srsSportTest = new SrsSportTest();
        try {
            for (SchoolYear s: schoolYears) {
                //SrsStudent srsStudent = srsStudentMapper.selectSrsStudentByStuNo(s.getStuNo());//查询是否有对应的学生
//                if (srsStudent==null){
//                    strings.add(s.getStuNo());
//                    continue;
//                }
                //srsStuYear.setId(s.getStuYearCode());
                srsStuYear.setStuYearName(s.getStuYearName());
                srsStuYear.setStartTime(s.getStartTime());
                srsStuYear.setEndTime(s.getEndTime());
                int i = srsStuYearMapper.insertSrsStuYear(srsStuYear);
                //更新课程学习中间表读取记录
                if (i>0){
                    s.setChmodStatus("2");
                    s.setReadTime(DateUtils.getNowDate());
                    schoolYearMapper.updateSchoolYear(s);
                }
            }
        }catch (Exception e){
            strings.add("导入中断");
            return strings;
        }
        return strings;
    }

    /**
     * 给指定标签的学年分配标签
     * @param tag
     * @param yearId
     * @return
     */
    @Override
    @Transactional
    public AjaxResult assignTagToYear(String tag, Long yearId) {
        try {
            // 参数校验
            if (tag == null || tag.trim().isEmpty() || yearId == null) {
                return AjaxResult.error("参数无效");
            }

            // 支持批量标签处理，按逗号分割
            String[] tags = tag.split(",");
            List<String> tagList = new ArrayList<>();
            for (String t : tags) {
                if (t != null && !t.trim().isEmpty()) {
                    tagList.add(t.trim());
                }
            }

            if (tagList.isEmpty()) {
                return AjaxResult.error("未提供有效标签");
            }

            // 对每个标签执行分配操作
            for (String singleTag : tagList) {
                // 从所有包含该标签的学年中移除该标签
                srsStuYearMapper.removeTagDirectly(singleTag);
            }

            // 将所有标签添加到目标学年
            SrsStuYear targetYear = srsStuYearMapper.selectSrsStuYearById(yearId);
            if (targetYear != null) {
                String currentTags = targetYear.getModuleTags();
                Set<String> tagSet = new LinkedHashSet<>();

                // 保留现有标签
                if (currentTags != null && !currentTags.isEmpty()) {
                    String[] existingTags = currentTags.split(",");
                    for (String existingTag : existingTags) {
                        String cleanTag = existingTag.trim();
                        if (!cleanTag.isEmpty()) {
                            tagSet.add(cleanTag);
                        }
                    }
                }

                // 添加所有新标签
                tagSet.addAll(tagList);

                // 更新标签
                String newTags = String.join(",", tagSet);
                targetYear.setModuleTags(newTags);
                srsStuYearMapper.updateSrsStuYear(targetYear);

                return AjaxResult.success("标签分配成功");
            } else {
                return AjaxResult.error("指定的学年不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("标签分配失败：" + e.getMessage());
        }
    }

    /**
     * 获取指定标签的学年列表
     * @param tag
     * @return
     */
    @Override
    public List<SrsStuYear> getYearsByTag(String tag) {
        return srsStuYearMapper.selectYearsByTag(tag);
    }

    /**
     * 删除指定标签的指定学年
     * @param tags
     * @param yearId
     * @return
     */
   /* @Override
    public AjaxResult removeTagFromYear(List<String> tags, Long yearId) {
        try {
            // 参数校验
            if (tags == null || tags.isEmpty() || yearId == null) {
                return AjaxResult.error("参数无效");
            }
            // 获取指定学年
            SrsStuYear targetYear = srsStuYearMapper.selectSrsStuYearById(yearId);
            if (targetYear == null) {
                return AjaxResult.error("指定的学年不存在");
            }
            System.out.println("找到学年: " + targetYear.getStuYearName() + ", 当前标签: " + targetYear.getModuleTags());
            String currentTags = targetYear.getModuleTags();
            if (currentTags == null || currentTags.isEmpty()) {
                return AjaxResult.success("该学年没有标签");
            }
            // 分割标签并移除指定标签
            String[] tagsArray = currentTags.split(",");
            List<String> remainingTags = new ArrayList<>();
            Set<String> tagsToRemove = new HashSet<>();
            // 清理标签列表，去除空格
            for (String tag : tags) {
                if (tag != null && !tag.trim().isEmpty()) {
                    tagsToRemove.add(tag.trim());
                }
            }
            int removedCount = 0;
            for (String existingTag : tagsArray) {
                String trimmedTag = existingTag.trim();
                if (tagsToRemove.contains(trimmedTag)) {
                    removedCount++; // 找到要移除的标签
                } else {
                    remainingTags.add(trimmedTag); // 保留其他标签
                }
            }
            if (removedCount == 0) {
                return AjaxResult.success("该学年未包含指定标签");
            }
            // 更新标签
            String newTags = remainingTags.isEmpty() ? null : String.join(",", remainingTags);
            targetYear.setModuleTags(newTags);
            int result = srsStuYearMapper.updateSrsStuYear(targetYear);
            if (result > 0) {
                return AjaxResult.success("成功移除" + removedCount + "个标签");
            } else {
                return AjaxResult.error("标签移除失败");
            }
        } catch (Exception e) {
            return AjaxResult.error("标签移除失败：" + e.getMessage());
        }
    }*/
}
