package com.liquidnet.service.kylin.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liquidnet.common.cache.redis.util.RedisUtil;
import com.liquidnet.service.kylin.constant.KylinRedisConst;
import com.liquidnet.service.kylin.dto.vo.KylinFieldsVo;
import com.liquidnet.service.kylin.entity.KylinFields;
import com.liquidnet.service.kylin.mapper.KylinFieldsMapper;
import com.liquidnet.service.kylin.service.KylinFieldsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.HashMap;


@Service
public class FieldsServiceImpl extends ServiceImpl<KylinFieldsMapper, KylinFields> implements KylinFieldsService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public HashMap<String,Object> fieldList(int page, int size, int city_id) {
        HashMap<String,Object> info = new HashMap<>();

        // 排序 分页
        Pageable pageable = PageRequest.of(0, size, Sort.by(Sort.Direction.DESC, "createdAt"));

        //条件
        Query query = Query.query(Criteria.where("cityId").is(city_id));

        // 查询总数
        long count = mongoTemplate.count(query, KylinFieldsVo.class, KylinFieldsVo.class.getSimpleName());

        query.with(pageable);
        info.put("total",count);
        info.put("data", mongoTemplate.find(query, KylinFieldsVo.class, KylinFieldsVo.class.getSimpleName()));

        return info;
    }

    /**
     * 获取场地详情
     *
     * @param fieldId
     * @return FieldsVo
     */
    @Override
    public KylinFieldsVo fieldDetails(String fieldId) {
        KylinFieldsVo info = null;
        // 获取 redis数据
        info = (KylinFieldsVo) redisUtil.hget(KylinRedisConst.FIELDS, fieldId + "");
        //不存在 获取 mongo数据
        if (null == info) {
            info = mongoTemplate.findOne(Query.query(Criteria.where("fieldsId").is(fieldId)), KylinFieldsVo.class, KylinFieldsVo.class.getSimpleName());
            redisUtil.hset(KylinRedisConst.FIELDS, fieldId + "",info);
        }
        return info;
    }
}
