package com.centreproject.system.service.concierge.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.centreproject.common.constant.GuestConstants;
import com.centreproject.common.constant.KeyConstants;
import com.centreproject.common.utils.DateUtils;
import com.centreproject.system.domain.kpi.concierge.KpiConcierge;
import com.centreproject.system.mapper.kpi.KpiConciergeMapper;
import com.centreproject.system.service.concierge.IKpiConciergeService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * KPI Concierge Service Implementation
 * search last 60 days data
 * @author zhonglei.xu
 */
@Service
public class KpiConciergeServiceImpl  extends ServiceImpl<KpiConciergeMapper, KpiConcierge>
        implements IKpiConciergeService {

    @Autowired
    private KpiConciergeMapper mapper;

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;
    /**
     * concierge kpi last 60 days data
     *
     * @return KpiConcierge
     */
    @Override
    public KpiConcierge getConcierge(String department) {
        String redisKey = KeyConstants.CONCIERGE + DateUtils.getRiDate() + GuestConstants.LATEST_60_DAYS;
        // 1. 查缓存
        KpiConcierge cached = (KpiConcierge) redisTemplate.opsForValue().get(redisKey);
        if (cached != null) {
            return cached;
        }
        KpiConcierge result=new KpiConcierge();
        List<KpiConcierge> lists = mapper.selectDepartmentKpiSummaryLast60Days();
        Map<String, KpiConcierge> map = lists.stream().collect(Collectors.toMap(KpiConcierge::getDepartment, Function.identity()));
        if(map.containsKey(department)){
            KpiConcierge kpiConcierge = map.get(department);
            if(ObjectUtils.isNotEmpty(kpiConcierge)){
                result = kpiConcierge;
            }
            // 获取总计revenueGenerated
            int totalRevenue = lists.stream()
                    .filter(item -> item.getRevenueGenerated() != null)
                    .mapToInt(KpiConcierge::getRevenueGenerated)
                    .sum();
            if(totalRevenue>0) {
                result.setDay(DateUtils.getShortYearDate());
                result.setRevenueGenerated(totalRevenue);
                redisTemplate.opsForValue().set(redisKey, result, 1, TimeUnit.HOURS);
            }
        }
        return result;
    }
}
