package com.sdut.labex.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sdut.labex.entity.Experiment;
import com.sdut.labex.entity.SubmitRecord;
import com.sdut.labex.entity.User;
import com.sdut.labex.mapper.ExperimentsMapper;
import com.sdut.labex.mapper.SubmitRecordsMapper;
import com.sdut.labex.mapper.UserMapper;
import com.sdut.labex.service.ExperimentsService;
import com.sdut.labex.utils.FormatDate;
import com.sdut.labex.utils.ResVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author springforest
 * @description 针对表【experiments(实验)】的数据库操作Service实现
 * @createDate 2023-06-12 08:07:15
 */
@Slf4j
@Service
public class ExperimentsServiceImpl extends ServiceImpl<ExperimentsMapper, Experiment>
        implements ExperimentsService {
    @Resource
    private ExperimentsMapper experimentsMapper;
    @Resource
    private UserMapper usersMapper;

    @Resource
    private SubmitRecordsMapper submitRecordsMapper;

    @Override
    public ResVo applyExperiment(Experiment experiment) {
        try {
            experimentsMapper.insert(experiment);
        } catch (Exception e) {
            e.printStackTrace();
            return ResVo.error();
        }
        return ResVo.ok("申请成功,请等待审核");
    }

    @Override
    public ResVo deleteExperiment(String id) {
        if (experimentsMapper.selectById(id) == null)
            return ResVo.error("该实验不存在");

        try {
            experimentsMapper.deleteById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return ResVo.error();
        }
        return ResVo.ok();
    }

    @Override
    public ResVo updateExperiment(Experiment experiment) {
        if (experimentsMapper.selectById(experiment.getId()) == null)
            return ResVo.error("该实验不存在");

        try {
            experimentsMapper.updateById(experiment);
        } catch (Exception e) {
            e.printStackTrace();
            return ResVo.error();
        }
        return ResVo.ok();
    }

    @Override
    public ResVo getExperiment(String id) {
        QueryWrapper<Experiment> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", id);

        Experiment experiment = experimentsMapper.selectOne(queryWrapper);
        if (experiment == null)
            return ResVo.error("该实验不存在");
        Map<String, Object> map = new HashMap<>();
        map.put("experiment", experiment);
        return ResVo.ok(map);

    }

    @Override
    public ResVo getExperiments(Experiment experiment, int pageNum, int pageSize) {
        log.info("getExperiments: experiment = " + experiment + ", pageNum = " + pageNum + ", pageSize = " + pageSize);
        Page<Experiment> page = new Page<>(pageNum, pageSize);
        experimentsMapper.getExperimentsByPage(page, experiment);

        List<Experiment> list = page.getRecords();
        for (Experiment e : list) {
            e.setApplyTimeStr(FormatDate.formatDate(e.getApplyTime()));
        }

        Map<String, Object> res = new HashMap<>();
        res.put("list", list);
        res.put("total", page.getTotal());
        res.put("current", page.getCurrent());
        return ResVo.ok(res);
    }

    @Override
    public ResVo getUnreviewedExperiments() {
        QueryWrapper<Experiment> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("status", "0");
        List<Experiment> list = experimentsMapper.selectList(queryWrapper);
        Map<String, Object> map = new HashMap<>();
        map.put("list", list);
        return ResVo.ok(map);
    }

    @Override
    @Transactional
    public ResVo isAdmitted(int id, int status) {
        Experiment experiment = experimentsMapper.selectById(id);
        if (experiment == null)
            return ResVo.error("该实验不存在");
        experiment.setStatus(status);

        if (status == 1) {
            //为实验中包含的班级添加实验记录
            String[] classList = experiment.getClassName().split(";");
            List<User> users;
            List<SubmitRecord> submitRecordList = new ArrayList<>();
            for (String className : classList) {
                QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("class_name", className);
                users = usersMapper.selectList(queryWrapper);
                for (User user : users) {
                    SubmitRecord submitRecord = new SubmitRecord();
                    submitRecord.setExperimentId(experiment.getId());
                    submitRecord.setStudentId(user.getId());
                    submitRecordList.add(submitRecord);
                }
            }
            if (submitRecordList.size() == 0) {
                return ResVo.error("该实验没有班级");
            }
            try {
                submitRecordsMapper.insertBatch(submitRecordList);
            } catch (Exception e) {
                e.printStackTrace();
                return ResVo.error("添加实验记录失败");
            }
        }

        try {
            experimentsMapper.updateById(experiment);
        } catch (Exception e) {
            e.printStackTrace();
            return ResVo.error();
        }

        return ResVo.ok();
    }
}




