package com.liquidnet.service.adam.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liquidnet.common.cache.redis.util.RedisUtil;
import com.liquidnet.service.adam.constant.AdamRedisConst;
import com.liquidnet.service.adam.dto.vo.AdamMemberPriceVo;
import com.liquidnet.service.adam.dto.vo.AdamMemberVo;
import com.liquidnet.service.adam.entity.AdamMember;
import com.liquidnet.service.adam.mapper.AdamMemberMapper;
import com.liquidnet.service.adam.mapper.AdamMemberPriceMapper;
import com.liquidnet.service.adam.service.IAdamMemberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.convert.MongoConverter;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

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


@Slf4j
@Service
public class AdamMemberServiceImpl extends ServiceImpl<AdamMemberMapper, AdamMember> implements IAdamMemberService {
    @Autowired
    AdamMemberMapper adamMemberMapper;
    @Autowired
    AdamMemberPriceMapper adamMemberPriceMapper;
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    MongoConverter mongoConverter;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    RedisUtil redisUtil;

    @Override
    public AdamMemberVo queryMemberInfo() {
        AdamMember firstMember = adamMemberMapper.getFirstMember();
        String memberId = firstMember.getMemberId();

        AdamMemberVo info = null;
        List<AdamMemberPriceVo> memberPrice = new ArrayList<>();
        info = (AdamMemberVo) redisUtil.hget(AdamRedisConst.INFO_MEMBERS_INFO.concat(memberId), memberId);
        Map<Object, Object> tempMemberPrice = redisUtil.hmget(AdamRedisConst.INFO_MEMBERS_PRICE_INFO.concat(memberId));
        Iterator<Object> iterator = tempMemberPrice.keySet().iterator();
        while(iterator.hasNext()){
            AdamMemberPriceVo tempAmp  = (AdamMemberPriceVo) tempMemberPrice.get(iterator.next());
            memberPrice.add(tempAmp);
        }
        if (null == info) {
            info = mongoTemplate.findOne(Query.query(Criteria.where("memberId").is(memberId)),
                    AdamMemberVo.class, AdamMemberVo.class.getSimpleName());
        }
        if (null == tempMemberPrice) {
            memberPrice = mongoTemplate.find(Query.query(Criteria.where("memberId").is(memberId)),
                    AdamMemberPriceVo.class, AdamMemberPriceVo.class.getSimpleName());
        }
        if (memberPrice.size() > 0) {
            info.setAdamMemberPrice(memberPrice);
        }
        return info;
    }

}
