package com.skr.mdm.api.index.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import com.skr.mdm.api.index.service.SecurityPolicyService;
import com.skr.mdm.bean.qo.controller.LargeScreenQO;
import com.skr.mdm.bean.vo.index.IndexStrategyStateStatisticsVO;
import com.skr.mdm.bean.vo.index.StrategyStatisticsVO;
import com.skr.mdm.dao.AppStrategyUserDao;
import com.skr.mdm.dto.LoginAdminDTO;
import com.skr.mdm.result.ResponseResult;
import com.skr.mdm.util.MdmThreadPoolUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * @ProjectName: mdm_new
 * @Package: com.skr.mdm.largeScreenManagement.service.serviceImpl
 * @ClassName: SecurityPolicyServiceImpl
 * @Author: Tty
 * @Description: 实现
 * @Date: 2020/9/10 9:18
 * @Version: 1.0
 */
@Slf4j
@Service
public class SecurityPolicyServiceImpl implements SecurityPolicyService {

	@Autowired
	private AppStrategyUserDao appStrategyUserDao;

	@Override
	public ResponseResult queryStrategyData(LoginAdminDTO admin, String startTime, String endTime) {
		//  封装查询对象
		LargeScreenQO largeScreenQO = LargeScreenQO.builder()
				.startTime(startTime)
				.endTime(endTime)
				.companyId(admin.getCompanyId())
				.build();
		TimeInterval timer = DateUtil.timer();
		StrategyStatisticsVO strategyStatisticsVO = StrategyStatisticsVO.builder().build();
		MdmThreadPoolUtil.execute(() -> {
			strategyStatisticsVO.setAppStrategyStatistics(buildIndexStrategyStateStatisticsVO(appStrategyUserDao.queryAppStrategyStatisticsList(largeScreenQO)));
			log.info("应用策略统计耗时：{}毫秒", timer.intervalMs());
		});
		return ResponseResult.success(strategyStatisticsVO);
	}

	private IndexStrategyStateStatisticsVO buildIndexStrategyStateStatisticsVO(List<Integer> strategyStateList) {
		if (CollectionUtils.isNotEmpty(strategyStateList)) {
			long issuedCount = strategyStateList.stream().filter(state -> state == 1).count();
			long issuedSuccessCount = strategyStateList.stream().filter(state -> state != 1).count();
			long executingCount = strategyStateList.stream().filter(state -> state == 3).count();
			long executeSuccessCount = strategyStateList.stream().filter(state -> state == 4).count();
			return IndexStrategyStateStatisticsVO.builder()
					.issuingCount(issuedCount)
					.issuedSuccessCount(issuedSuccessCount)
					.executingCount(executingCount)
					.executeSuccessCount(executeSuccessCount)
					.build();
		}
		return IndexStrategyStateStatisticsVO.builder().build();
	}
}