package org.springblade.gateway.common_gateway.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springblade.common.listener.OnlinePeopleListener;
import org.springblade.common.utils.BeanPropertyUtil;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.gateway.common_gateway.dto.IndexCensusDto;
import org.springblade.gateway.common_gateway.service.IndexCensusService;
import org.springblade.sing.active.entity.ActiveProductRecord;
import org.springblade.sing.active.entity.ActiveRecord;
import org.springblade.sing.active.service.IActiveProductRecordService;
import org.springblade.sing.active.service.IActiveRecordService;
import org.springblade.sing.point.entity.PointRecord;
import org.springblade.sing.user.entity.LoginUser;
import org.springblade.sing.user.service.ILoginUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: Silent
 * @Description
 * @Date: Created in 16:21 2021/11/19
 * @Modified By:
 */
@Service
public class IndexCensusServiceImpl implements IndexCensusService {
	@Autowired
	private IActiveRecordService activeRecordService;

	@Autowired
	private IActiveProductRecordService activeProductRecordService;

	@Autowired
	private ILoginUserService loginUserService;

	/**
	 * 统计平台各项数据总次数
	 * @return
	 */
	@Override
	public IndexCensusDto censusTotalCount(boolean today) {
		//判断今日SQL语句
		if(today){
			String lastSQL = new StringBuilder("and date_format(")
				.append(BeanPropertyUtil.getFieldNameToUnder(PointRecord::getCreateTime))
				.append(",\"%Y-%m-%d\")=\"")
				.append(DateUtil.format(DateUtil.now(), "yyyy-MM-dd").trim()).append("\"").toString();
			return IndexCensusDto.builder()
				.userCount(loginUserService.count(Wrappers.<LoginUser>lambdaQuery().last(lastSQL)))
				.activeCount(activeRecordService.count(Wrappers.<ActiveRecord>lambdaQuery().last(lastSQL)))
				.activeProductCount(activeProductRecordService.count(Wrappers.<ActiveProductRecord>lambdaQuery().last(lastSQL)))
				.onlinePeopleNumber(OnlinePeopleListener.userCount.longValue())
				.build();
		}else{
			return IndexCensusDto.builder()
				.userCount(loginUserService.count())
				.activeCount(activeRecordService.count())
				.activeProductCount(activeProductRecordService.count())
				.onlinePeopleNumber(OnlinePeopleListener.userCount.longValue())
				.build();
		}
	}

	@Override
	public List<Map<String,Object>> activeTotal() {
		List<Map<String,Object>> list = new ArrayList<>();
		List<ActiveRecord> activeRecords = activeRecordService.list();
		for (ActiveRecord activeRecord : activeRecords) {
			HashMap<String, Object> map = new HashMap<>();
			map.put("name",activeRecord.getTitle());
			map.put("value",activeProductRecordService.selectProductCountByActiveId(activeRecord.getId()));
			list.add(map);
		}

		return list;
	}
}
