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

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
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.AdamRdmService;
import com.liquidnet.service.adam.service.IAdamUserMemberService;
import com.liquidnet.service.adam.service.admin.IAdamMemberCodeAdminService;
import com.liquidnet.service.adam.util.MemberUtil;
import lombok.extern.slf4j.Slf4j;
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.StringUtils;

import java.time.LocalDateTime;

@Slf4j
@Service
public class AdamMemberCodeAdminServiceImpl extends ServiceImpl<AdamMemberCodeMapper, AdamMemberCode> implements IAdamMemberCodeAdminService {
    @Autowired
    AdamMemberCodeMapper adamMemberCodeMapper;
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    IAdamUserMemberService adamUserMemberService;
    @Autowired
    AdamRdmService adamRdmService;

    @Override
    public String createGiftCode(AdamMemberCodeParam param) {
        String mCode, memberNo;
        boolean exists;
        do {
            mCode = MemberUtil.freeCode();
            exists = mongoTemplate.exists(
                    Query.query(Criteria.where("code").is(mCode)), AdamMemberCodeVo.class.getSimpleName()
            );
        } while (exists);

        // 需要主动生成会员编号
        memberNo = adamUserMemberService.getNextMemberNo(param.getMemberId());

        if (StringUtils.isEmpty(memberNo)) return "";

        AdamMemberCode initMemberCode = new AdamMemberCode();
        initMemberCode.setCode(mCode);
        initMemberCode.setType(param.getType());
        initMemberCode.setMemberId(param.getMemberId());
        initMemberCode.setMemberPriceId(param.getMemberPriceId());
        initMemberCode.setMemberNo(memberNo);
        initMemberCode.setState(0);// 0-未使用,1-已使用,2-不可用
        initMemberCode.setCreatedAt(LocalDateTime.now());

        adamMemberCodeMapper.insert(initMemberCode);

        AdamMemberCodeVo vo = AdamMemberCodeVo.getNew().copy(initMemberCode);
        mongoTemplate.insert(vo, AdamMemberCodeVo.class.getSimpleName());

        adamRdmService.setMemberCodeVoByCode(mCode, vo);

        return initMemberCode.getCode();
    }
}
