package com.yh.saas.platform.service.impl;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.winsea.svc.base.security.util.AuthSecurityUtils;
import com.yh.saas.common.support.util.IdGenerator;
import com.yh.saas.platform.entity.FuncClickInfo;
import com.yh.saas.platform.mapper.FuncClickInfoMapper;
import com.yh.saas.platform.service.IFuncClickInfoService;

/**
 * <p>
 * APP功能点击次数记录表 服务实现类
 * </p>
 *
 * @author wxg
 * @since 2019-11-12
 */
@Service
public class FuncClickInfoServiceImpl extends ServiceImpl<FuncClickInfoMapper, FuncClickInfo>
		implements IFuncClickInfoService {

	@Override
	public List<FuncClickInfo> queryFuncClickInfoList(String userId) {
		// 查询功能点击次数记录列表
		Wrapper<FuncClickInfo> itemWrapper = new EntityWrapper<>();
		itemWrapper.eq(FuncClickInfo.QueryFields.USER_ID, userId);
		// itemWrapper.orderBy(FuncClickInfo.QueryFields.CLICK_COUNT, false);
		List<FuncClickInfo> itemList = selectList(itemWrapper);

		// 按点击次数倒序排序
		return itemList.stream().sorted(Comparator.comparing(FuncClickInfo::getClickCount).reversed())
				.collect(Collectors.toList());
	}

	@Override
	public String saveFuncClickInfo(FuncClickInfo funcClickInfo) {
		if (StringUtils.isBlank(funcClickInfo.getCompId())) {
			funcClickInfo.setCompId(AuthSecurityUtils.getCurrentUserInfo().getCompId());
		}

		// 查询用户功能点击次数记录
		Wrapper<FuncClickInfo> itemWrapper = new EntityWrapper<>();
		itemWrapper.eq(FuncClickInfo.QueryFields.USER_ID, funcClickInfo.getUserId());
		itemWrapper.eq(FuncClickInfo.QueryFields.FUNC_TYPE, funcClickInfo.getFuncType());
		FuncClickInfo funcClick = this.selectOne(itemWrapper);

		if (funcClick == null) {
			// 如果不存在新增
			funcClickInfo.setId(IdGenerator.generateLongIncrId());
			funcClickInfo.setClickCount(1L);
			this.insert(funcClickInfo);
		} else {
			// 如果存在更新
			funcClickInfo.setId(funcClick.getId());
			funcClickInfo.setClickCount(funcClick.getClickCount() + 1);
			this.updateById(funcClickInfo);
		}

		return funcClickInfo.getId();
	}

}
