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

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liquidnet.common.cache.redis.util.RedisUtil;
import com.liquidnet.commons.lang.util.IDGenerator;
import com.liquidnet.commons.lang.util.JsonUtils;
import com.liquidnet.service.adam.constant.AdamRedisConst;
import com.liquidnet.service.adam.dto.AdamMemberParam;
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.service.admin.IAdamMemberAdminService;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
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.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Slf4j
@Service
public class AdamMemberServiceAdminImpl extends ServiceImpl<AdamMemberMapper, AdamMember> implements IAdamMemberAdminService {
    @Autowired
    AdamMemberMapper adamMemberMapper;
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    RedisUtil redisUtil;

    @Override
    public void add(AdamMemberParam info) {
        AdamMember adamMember = new AdamMember();
        BeanUtils.copyProperties(info, adamMember);

        adamMember.setMemberId(IDGenerator.nextSnowId().toString());
        adamMember.setStartNo(10000);
        adamMember.setCreatedAt(LocalDateTime.now());
        adamMember.setUpdatedAt(LocalDateTime.now());

        adamMemberMapper.insert(adamMember);

        mongoTemplate.insert(AdamMemberVo.getNew().copy(adamMember), AdamMemberVo.class.getSimpleName());
    }

    @Override
    public void edit(AdamMember info) {
        info.setUpdatedAt(LocalDateTime.now());

        AdamMemberVo updateVo = AdamMemberVo.getNew().copy(info);

        mongoTemplate.getCollection(AdamMemberVo.class.getSimpleName()).updateOne(
                Query.query(Criteria.where("mId").is(info.getMid())).getQueryObject(),
                new Document("$set", Document.parse(JsonUtils.toJson(updateVo)))
        );
        redisUtil.del(AdamRedisConst.INFO_MEMBER_CATEGORY.concat(info.getMemberId()));
    }
}
