package com.xhkjedu.sapi.service.itemtool;

import com.xhkjedu.sapi.mapper.itemtool.ReadDateMapper;
import com.xhkjedu.sapi.model.itemtool.TRead;
import com.xhkjedu.sapi.model.itemtool.TReadDate;
import com.xhkjedu.utils.N_Utils;
import com.xhkjedu.sapi.vo.itemtool.ReadDateVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author ywx
 * @classname ReadDateService
 * @description
 * @date 2021/12/28 9:15
 **/
@Service
public class ReadDateService {
    @Resource
    private ReadDateMapper readDateMapper;

    //关联阅读开放时间
    public void setReads(List<TRead> reads) {
        for (TRead tRead : reads) {
            setRead(tRead);
        }
    }

    //关联阅读开放时间
    public Integer setRead(TRead tRead) {
        Integer readable = 0;
        List<TReadDate> dateList = readDateMapper.listByReadId(tRead.getReadid());
        if (N_Utils.isListEmpty(dateList)) return readable;
        List<ReadDateVo> dates = new ArrayList<>();
        Map<String, List<TReadDate>> collect = dateList.stream().collect(
                Collectors.groupingBy(d -> d.getBegintime() + "_" + d.getEndtime(), LinkedHashMap::new, Collectors.toList()));
        for (Map.Entry c : collect.entrySet()) {
            String key = c.getKey().toString();
            String[] begin_end = key.split("_");
            List<TReadDate> list = (List<TReadDate>) c.getValue();
            List<Integer> datenum = new ArrayList<>();
            List<String> timestr = new ArrayList<>();
            timestr.add(begin_end[0]);
            timestr.add(begin_end[1]);
            ReadDateVo d = new ReadDateVo();
            d.setTimestr(timestr);
            for (TReadDate rd : list) {
                datenum.add(rd.getWeeknum());
                if (rd.getReadable().equals(1)) {
                    readable = 1;
                }
            }
            d.setDatenum(datenum);
            dates.add(d);
        }
        tRead.setReadable(readable);
        tRead.setDates(dates);
        return readable;
    }

    public void insertList(List<TReadDate> dateList) {
        readDateMapper.insertList(dateList);
    }

    public void deleteByReadId(Integer readid) {
        readDateMapper.deleteByReadId(readid);
    }

    public List<TReadDate> listByReadId(Integer readid) {
        return readDateMapper.listByReadId(readid);
    }
}
