package com.fzm.mall.server.admin.user_center.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fzm.mall.server.admin.constant.MallResponseError;
import com.fzm.mall.server.admin.exception.MyException;
import com.fzm.mall.server.admin.user_center.entity.dto.MemberConfigDTO;
import com.fzm.mall.server.admin.user_center.entity.vo.MemberConfigVO;
import com.fzm.mall.server.admin.user_center.model.SysMember;
import com.fzm.mall.server.admin.user_center.mapper.SysMemberMapper;
import com.fzm.mall.server.admin.user_center.service.ISysMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.dozer.DozerBeanMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wangp
 * @date 2021/3/22 14:33
 * @description 会员配置表 服务实现类
 * @since JDK 1.8
 */
@Service
@Transactional
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SysMemberServiceImpl extends ServiceImpl<SysMemberMapper, SysMember> implements ISysMemberService {

    private final DozerBeanMapper beanMapper;

    @Override
    public void init(Integer level) {
        SysMember member = new SysMember();
        member.setLevel(level);
        member.setTotalConsume(BigDecimal.ZERO);
        member.setTotalRecommend(0);
        member.setFee(BigDecimal.ZERO);
        boolean save = save(member);
        if (!save) {
            throw new MyException(MallResponseError.SAVE_ERROR);
        }
    }

    @Override
    @Transactional
    public void edit(List<MemberConfigDTO> memberDTOList) {
        for (MemberConfigDTO dto : memberDTOList) {
            SysMember sysMember = beanMapper.map(dto, SysMember.class);

            UpdateWrapper<SysMember> uw = new UpdateWrapper<>();
            uw.lambda().eq(SysMember::getLevel, sysMember.getLevel());
            boolean update = update(sysMember, uw);

            if (!update) {
                throw new MyException(MallResponseError.UPDATE_ERROR);
            }
        }
    }

    @Override
    public List<MemberConfigVO> listSelfDefine() {
        List<MemberConfigVO> configVOList = list().stream()
                .map(v1 -> beanMapper.map(v1, MemberConfigVO.class))
                .collect(Collectors.toList());
        return configVOList;
    }

    @Override
    public boolean memberSettingsExist(Integer level) {
        QueryWrapper<SysMember> qw = new QueryWrapper<>();
        qw.lambda().eq(SysMember::getLevel, level);
        return getOne(qw) != null;
    }
}
