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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fzm.mall.server.admin.constant.MallResponseError;
import com.fzm.mall.server.admin.exception.MyException;
import com.fzm.mall.server.admin.marketing.entity.dto.MemberIntegralRecurrenceDTO;
import com.fzm.mall.server.admin.marketing.mapper.MemberIntegralRecurrenceMapper;
import com.fzm.mall.server.admin.marketing.model.MemberIntegralRecurrence;
import com.fzm.mall.server.admin.marketing.service.IMemberIntegralRecurrenceService;
import com.fzm.mall.server.admin.util.CopyUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 运营中心-积分返现 服务实现类
 * </p>
 *
 * @author wlx
 * @since 2021-06-04
 */
@Service
@Transactional
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class MemberIntegralRecurrenceServiceImpl extends ServiceImpl<MemberIntegralRecurrenceMapper, MemberIntegralRecurrence> implements IMemberIntegralRecurrenceService {

    private final MemberIntegralRecurrenceMapper recurrenceMapper;

    @Override
    public void update(List<MemberIntegralRecurrenceDTO> paramList, String merchantId) {
        List<MemberIntegralRecurrence> list = CopyUtil.toList(paramList, MemberIntegralRecurrence.class);

        list.forEach(item -> {
            UpdateWrapper<MemberIntegralRecurrence> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("merchant_id", merchantId)
                    .eq("level",item.getLevel())
                    .eq("id",item.getId())
                    .eq("update_time", item.getUpdateTime());
            int update = recurrenceMapper.update(item, updateWrapper);
            if (update == 0) {
                throw new MyException(MallResponseError.UPDATE_FAIL);
            }
        });
    }

    @Override
    public List<MemberIntegralRecurrenceDTO> listAll(String merchantId) {
        QueryWrapper<MemberIntegralRecurrence> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("merchant_id", merchantId).orderByAsc("level");
        List<MemberIntegralRecurrence> list = recurrenceMapper.selectList(queryWrapper);
        return CopyUtil.toList(list, MemberIntegralRecurrenceDTO.class);
    }
}
