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.AdamMemberCodeParam;
import com.liquidnet.service.adam.dto.vo.AdamMemberCodeVo;
import com.liquidnet.service.adam.entity.AdamMemberCode;
import com.liquidnet.service.adam.mapper.AdamMemberCodeMapper;
import com.liquidnet.service.adam.service.IAdamMemberCodeService;
import com.liquidnet.service.adam.util.MemberUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
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.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class AdamMemberCodeServiceImpl extends ServiceImpl<AdamMemberCodeMapper, AdamMemberCode> implements IAdamMemberCodeService {

    @Autowired
    AdamMemberCodeMapper adamMemberCodeMapper;
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    MongoConverter mongoConverter;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    RedisUtil redisUtil;

    @Override
    public void add(AdamMemberCodeParam param) {

        AdamMemberCode adamMemberCode = new AdamMemberCode();
        adamMemberCode.setType(param.getType());
        adamMemberCode.setCode(MemberUtil.buyCode());
        adamMemberCode.setMemberId(param.getMemberId());
        adamMemberCode.setMemberPriceId(param.getMemberPriceId());
        adamMemberCode.setState(1);// 1-生成


        // mysql
        adamMemberCodeMapper.insert(adamMemberCode);

        // mongo
        AdamMemberCodeVo vo = new AdamMemberCodeVo();
        BeanUtils.copyProperties(adamMemberCode, vo);
        vo.setCreatedAt(adamMemberCode.getCreatedAt());
        vo.setUpdatedAt(adamMemberCode.getUpdatedAt());

        mongoTemplate.insert(vo, AdamMemberCodeVo.class.getSimpleName());

        // redis
        Map<String, Object> redisMap = new HashMap<>();
        redisMap.put(AdamRedisConst.INFO_MEMBERS_CODE_INFO.concat(adamMemberCode.getMemberPriceId()), vo);
        redisUtil.hmset(AdamRedisConst.INFO_MEMBERS_CODE_INFO.concat(adamMemberCode.getBuyUid()) , redisMap);
    }
}
