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.commons.lang.util.DateUtil;
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.Collections;
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(DateUtil.format(adamMemberCode.getCreatedAt(), DateUtil.Formatter.yyyyMMddHHmmss));
        vo.setUpdatedAt(DateUtil.format(adamMemberCode.getUpdatedAt(), DateUtil.Formatter.yyyyMMddHHmmss));

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

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