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

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liquidnet.client.admin.zhengzai.adam.service.IAdamMemberAdminService;
import com.liquidnet.commons.lang.util.IDGenerator;
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.base.ResponseDto;
import lombok.extern.slf4j.Slf4j;
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 org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

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

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

        List<AdamMember> existList = adamMemberMapper.selectList(Wrappers.lambdaQuery());

        adamMember.setMemberId(CollectionUtils.isEmpty(existList) ? "1" : IDGenerator.nextSnowId().toString());
        adamMember.setType(1);
        adamMember.setStartNo(10000);
        adamMember.setCreatedAt(LocalDateTime.now());
        adamMember.setUpdatedAt(LocalDateTime.now());

        adamMemberMapper.insert(adamMember);

        AdamMemberVo vo = AdamMemberVo.getNew().copy(adamMember);

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

//        adamRdmService.setMemberVoByMemberId(vo.getMemberId(), vo);

        return vo;
    }

    @Override
    public ResponseDto<Object> sync() {
        List<AdamMember> list = adamMemberMapper.selectList(Wrappers.lambdaQuery(AdamMember.class).orderByAsc(AdamMember::getMemberId));
        if (CollectionUtils.isEmpty(list)) {
            return ResponseDto.failure("会员数据不存在，请核实");
        }
        mongoTemplate.remove(Query.query(Criteria.where("_id").exists(true)), AdamMemberVo.class.getSimpleName());
        AdamMemberVo vo = AdamMemberVo.getNew().copy(list.get(0));
        mongoTemplate.insert(vo, AdamMemberVo.class.getSimpleName());
//        adamRdmService.delMemberVoByMemberId(vo.getMemberId());
        return ResponseDto.success();
    }
}
