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.FieldsVo;
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, FieldsVo.class, FieldsVo.class.getSimpleName());

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

        return info;
    }

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