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.applytask.TimePeriodReq;
import com.qmth.exam.reserve.bean.timeperiod.TimePeriodExamSiteBean;
import com.qmth.exam.reserve.cache.impl.ApplyTaskCacheService;
import com.qmth.exam.reserve.dao.TimePeriodDao;
import com.qmth.exam.reserve.entity.ApplyTaskEntity;
import com.qmth.exam.reserve.entity.TimePeriodEntity;
import com.qmth.exam.reserve.enums.EventType;
import com.qmth.exam.reserve.service.ApplyTaskService;
import com.qmth.exam.reserve.service.OperateLogService;
import com.qmth.exam.reserve.service.TimePeriodService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TimePeriodServiceImpl extends ServiceImpl<TimePeriodDao, TimePeriodEntity> implements TimePeriodService {

    @Autowired
    private ApplyTaskService taskService;

    @Autowired
    private OperateLogService logService;

    @Autowired
    private ApplyTaskCacheService cacheService;

    @Override
    public void saveTimePeriod(Long userId, Long id, List<TimePeriodReq> timeList) {
        ApplyTaskEntity task = taskService.getById(id);
        if (task == null)
            throw new StatusException("预约任务不存在！");
        for (TimePeriodReq time : timeList) {
            TimePeriodEntity timePeriod = new TimePeriodEntity();
            BeanUtils.copyProperties(time, timePeriod);
            timePeriod.setApplyTaskId(id);
            //保存或更新
            if (time.getId() == null) {
                save(timePeriod);
                //更新剩余可约数量的缓存
                cacheService.initApplyAvailableCountCacheForTimePeriods(timePeriod.getId());
            } else {
                updateById(timePeriod);
            }
        }
        logService.insertOperateLog(userId, EventType.SAVE_TIME_PERIOD, null);
    }

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

    @Override
    public List<String> listTimePeriodDate(Long taskId) {
        return baseMapper.listTimePeriodDate(taskId);
    }

    @Override
    public List<TimePeriodExamSiteBean> listTimePeriodByExamSiteId(Long taskId, Long examSiteId) {
        return baseMapper.listTimePeriodByExamSiteId(taskId, examSiteId);
    }

    @Override
    public List<TimePeriodExamSiteBean> listTimePeriodByTask(Long taskId) {
        return baseMapper.listTimePeriodByTask(taskId);
    }

}
