package com.qmth.exam.reserve.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.boot.core.exception.StatusException;
import com.qmth.exam.reserve.bean.apply.ExamSiteTimePeriodInfo;
import com.qmth.exam.reserve.bean.apply.ExamSiteTimePeriodQuery;
import com.qmth.exam.reserve.bean.timeperiod.TimePeriodExamSiteBean;
import com.qmth.exam.reserve.bean.timeperiod.TimePeriodExamSiteInfo;
import com.qmth.exam.reserve.bean.timeperiod.TimePeriodExamSiteReq;
import com.qmth.exam.reserve.bean.timeperiod.TimePeriodExamSiteVo;
import com.qmth.exam.reserve.dao.TimePeriodExamSiteDao;
import com.qmth.exam.reserve.entity.ApplyTaskEntity;
import com.qmth.exam.reserve.entity.TimePeriodExamSiteEntity;
import com.qmth.exam.reserve.service.ApplyTaskService;
import com.qmth.exam.reserve.service.TimePeriodExamSiteService;
import com.qmth.exam.reserve.service.TimePeriodService;
import com.qmth.exam.reserve.util.DateUtil;
import com.qmth.exam.reserve.util.UnionUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class TimePeriodExamSiteServiceImpl extends ServiceImpl<TimePeriodExamSiteDao, TimePeriodExamSiteEntity> implements TimePeriodExamSiteService {

    @Autowired
    private ApplyTaskService applyTaskService;

    @Autowired
    private TimePeriodService timePeriodService;

    @Override
    public List<String> listTimePeriod(Long taskId) {
        taskId = getTaskId(taskId);
        return timePeriodService.listTimePeriod(taskId);
    }

    private Long getTaskId(Long taskId) {
        if (taskId == null) {
            ApplyTaskEntity task = applyTaskService.findApplyTask();
            if (task != null) {
                taskId = task.getId();
            }
        }
        return taskId;
    }

    @Override
    public List<TimePeriodExamSiteVo> ListDetail(Long examSiteId) {
        Long taskId = getTaskId(null);
        // 所有的预约日期
        List<String> dateList = timePeriodService.listTimePeriodDate(taskId);
        if (CollectionUtils.isEmpty(dateList)) {
            return Collections.emptyList();
        }
        //教学点管理员设置的所有的考点时段
        List<TimePeriodExamSiteBean> timePeriodExamSiteList = timePeriodService.listTimePeriodByExamSiteId(taskId, examSiteId);
        //学校管理员设置的所有预约时段
        List<TimePeriodExamSiteBean> timePeriodList = timePeriodService.listTimePeriodByTask(taskId);
        List<TimePeriodExamSiteBean> resultList;
        if (CollectionUtils.isEmpty(timePeriodExamSiteList)) {
            resultList = timePeriodList;
        } else {
            //取并集
            resultList = UnionUtil.unionByAttribute(timePeriodExamSiteList, timePeriodList, TimePeriodExamSiteBean::getTimePeriodId);
        }

        //按日期封装
        List<TimePeriodExamSiteVo> list = new ArrayList<>();
        for (String date : dateList) {
            TimePeriodExamSiteVo timePeriodVo = new TimePeriodExamSiteVo();
            timePeriodVo.setDateStr(getDateStr(date));
            timePeriodVo.setTimePeriodList(filterTimePeriod(date, resultList));
            list.add(timePeriodVo);
        }
        return list;
    }

    @Override
    @Transactional
    public void save(Long operateId, Long examSiteId, List<TimePeriodExamSiteReq> timePeriodExamSiteList) {
        Long taskId = getTaskId(null);
        //所有的时段
        List<TimePeriodExamSiteBean> timePeriodList = timePeriodService.listTimePeriodByExamSiteId(taskId, examSiteId);

        List<TimePeriodExamSiteEntity> timePeriodExamSiteEntityList = new ArrayList<>(timePeriodExamSiteList.size());
        // 第一次设置
        if (CollectionUtils.isEmpty(timePeriodList)) {
            //直接保存
            timePeriodExamSiteList.forEach(item -> {
                TimePeriodExamSiteEntity timePeriodExamSiteEntity = new TimePeriodExamSiteEntity();
                timePeriodExamSiteEntity.setExamSiteId(examSiteId);
                timePeriodExamSiteEntity.setEnable(item.getEnable());
                timePeriodExamSiteEntity.setTimePeriodId(item.getTimePeriodId());
                timePeriodExamSiteEntity.setOperateId(operateId);
                timePeriodExamSiteEntityList.add(timePeriodExamSiteEntity);
            });
            //批量保存
            saveBatch(timePeriodExamSiteEntityList);
        } else {
            //保存或更新
            timePeriodExamSiteList.forEach(item -> {
                TimePeriodExamSiteEntity timePeriodExamSiteEntity = new TimePeriodExamSiteEntity();
                BeanUtils.copyProperties(item, timePeriodExamSiteEntity);
                timePeriodExamSiteEntity.setExamSiteId(examSiteId);
                timePeriodExamSiteEntity.setOperateId(operateId);
                timePeriodExamSiteEntityList.add(timePeriodExamSiteEntity);
            });
            saveOrUpdateBatch(timePeriodExamSiteEntityList);
        }
    }

    private String getDateStr(String date) {
        if (StringUtils.isEmpty(date)) {
            return "";
        }
        String[] dateArr = date.split("-");
        if (dateArr.length != 3) {
            return "";
        }
        return dateArr[1] + "月" + dateArr[2] + "日";
    }

    private List<TimePeriodExamSiteInfo> filterTimePeriod(String date, List<TimePeriodExamSiteBean> timePeriodList) {
        List<TimePeriodExamSiteInfo> list = new ArrayList<>();
        List<TimePeriodExamSiteBean> filterTimePerildList = timePeriodList.stream()
                .filter(item -> DateUtil.getShortDateByLongTime(item.getStartTime()).equals(date))
                .collect(Collectors.toList());

        //排序
        filterTimePerildList = filterTimePerildList.stream()
                .sorted(Comparator.comparing(TimePeriodExamSiteBean::getStartTime))
                .collect(Collectors.toList());

        for (TimePeriodExamSiteBean time : filterTimePerildList) {
            TimePeriodExamSiteInfo bean = new TimePeriodExamSiteInfo();
            bean.setId(time.getId());
            bean.setTimePeriodId(time.getTimePeriodId());
            bean.setEnable(time.getEnable());
            bean.setTimePeriodStr(DateUtil.getStartToEndTime(time.getStartTime(), time.getEndTime()));
            list.add(bean);
        }
        return list;
    }

    @Override
    public List<ExamSiteTimePeriodInfo> findExamSiteTimePeriods(ExamSiteTimePeriodQuery query) {
        if (query.getApplyTaskId() == null) {
            throw new StatusException("预约任务ID不能为空");
        }
        if (query.getExamSiteId() == null) {
            throw new StatusException("考点ID不能为空");
        }

        // 获取考点下所有相关的时段列表（含启用禁用状态）
        return baseMapper.findExamSiteTimePeriods(query);
    }

    @Override
    public ExamSiteTimePeriodInfo findOneExamSiteTimePeriod(Long applyTaskId, Long examSiteId, Long timePeriodId) {
        if (timePeriodId == null) {
            throw new StatusException("预约时段ID不能为空");
        }

        // 获取考点下某个具体的时段（含启用禁用状态）
        ExamSiteTimePeriodQuery periodQuery = new ExamSiteTimePeriodQuery();
        periodQuery.setApplyTaskId(applyTaskId);
        periodQuery.setExamSiteId(examSiteId);
        periodQuery.setTimePeriodId(timePeriodId);

        List<ExamSiteTimePeriodInfo> periods = this.findExamSiteTimePeriods(periodQuery);
        return CollectionUtils.isEmpty(periods) ? null : periods.get(0);
    }

}
