package com.njcn.serviceimpl.advanced;

import com.njcn.mapper.advanced.RangeMapper;
import com.njcn.pojo.advanced.EventAssObj;
import com.njcn.pojo.commons.AreaGeneralData;
import com.njcn.service.advanced.RangeService;
import com.njcn.shiro.token.TokenManager;
import com.njcn.utils.PubUtils;
import com.njcn.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class RangeServiceImpl implements RangeService {
    @Autowired
    private RangeMapper rangeMapper;
    @Autowired
    private UserUtil userUtil;

    @Override
    public List<EventAssObj> queryEventsByTime(String startTime, String endTime) throws Exception {
        Date dateStart = PubUtils.string2Date(startTime + " 00:00:00", ("yyyy-MM-dd HH:mm:ss"));
        Date dateEnd = PubUtils.string2Date(endTime + " 23:59:59", ("yyyy-MM-dd HH:mm:ss"));
        String time;

        //根据监测点id查询guid
        String area = userUtil.getDeptsIndex(TokenManager.getToken().getUserIndex());
        List<AreaGeneralData> deptdLists = userUtil.getAreaDataByInfo(area);
        List<String> list1 = new ArrayList<>();

        for (AreaGeneralData areaGeneralData : deptdLists) {
            if (!areaGeneralData.getLineIndexs().isEmpty()) {
                list1.addAll(rangeMapper.getEventAssIndex(areaGeneralData.getLineIndexs(), dateStart, dateEnd));
            }
        }

        if (list1.isEmpty()) {
            return new ArrayList<>();
        }
        List<EventAssObj> list = new ArrayList<>();
        if (list1.size() > 1000) {
            for (int i = 1; i <= list1.size(); i++) {
                List<String> tmplist = new ArrayList<>();
                if (list1.size() > 1000) {
                    tmplist = list1.subList(0, 1000);
                } else {
                    tmplist = list1;
                }
                List<EventAssObj> tmp = rangeMapper.queryEventsByTime(dateStart, dateEnd, tmplist);
                list.addAll(tmp);
                tmplist.clear();
            }
        } else {
            list = rangeMapper.queryEventsByTime(dateStart, dateEnd, list1);
        }

        for (EventAssObj eventAssObj : list) {
            time = PubUtils.date2String(eventAssObj.getTime(), "yyyy-MM-dd HH:mm:ss");
            eventAssObj.setStrTime(time);
        }

        return list;
    }

    /*
     * @see
     * com.pqs9200.service.advanced.RangeService#updatebRangeByGUID(java.lang.
     * String, int)
     * 如果bRange等于1则未进行范围分析，处理范围分析，并更新pqs_eventass表range字段置为0(已进行范围分析)
     * 如果bRange等于0表示已经进行范围分析处理，查询数据库调出处理结果
     */
    @Override
    @Transactional
    public void updatebRangeByGUID(String indexEventAss) {
        rangeMapper.updatebRangeByGUID(indexEventAss);
    }
}
