package com.crm.manager.service.impl;

import com.crm.manager.dao.mapper.UserReferralMapper;
import com.crm.manager.dao.repository.UserReferralRepository;
import com.crm.manager.service.UserReferralService;
import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.core.dto.base.PageDto;
import com.crm.rely.backend.core.dto.base.ResultWithPagerDto;
import com.crm.rely.backend.core.dto.user.info.UserReferralDto;
import com.crm.rely.backend.core.entity.user.info.UserReferralAddEntity;
import com.crm.rely.backend.core.entity.user.info.UserReferralEntity;
import com.crm.rely.backend.core.entity.user.info.UserReferralUpdateEntity;
import com.crm.rely.backend.core.pojo.table.UserReferralTable;
import com.crm.rely.backend.exception.ServiceException;
import com.crm.rely.backend.util.GetRandom;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserReferralServiceImpl implements UserReferralService {

    private static String randUpperCaseString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    @Autowired
    private UserReferralRepository userReferralRepository;

    @Autowired
    private UserReferralMapper userReferralMapper;

    @Override
    public void add(UserReferralAddEntity entity) throws Exception {
        UserReferralTable table = new UserReferralTable();
        BeanUtils.copyProperties(entity, table);
        table.setReferralCode(GetRandom.getRandom(randUpperCaseString,6));
        table.setReferralNum(0);
        table.setReferralSuccessNum(0);
        userReferralRepository.save(table);
    }

    @Override
    public ResultWithPagerDto<UserReferralDto> searchPageList(UserReferralEntity entity) throws Exception {
        Integer count = userReferralMapper.countList(entity);
        PageDto pageDto = PageDto.format(entity, count);
        List<UserReferralDto> list = userReferralMapper.getReferralList(entity);
        return ResultWithPagerDto.success(pageDto,list) ;
    }

    @Override
    public void update(UserReferralUpdateEntity entity) throws Exception {
        UserReferralTable table = userReferralRepository.findFirstById(entity.getId());
        if (table == null) {
            throw ServiceException.exception(Constants.INFO_NOT_FOUND);
        }
        BeanUtils.copyProperties(entity, table);
        userReferralRepository.save(table);
    }

    @Override
    public ResultWithPagerDto<UserReferralDto> getSuccessPageList(UserReferralEntity entity) throws Exception {
        Integer count = userReferralMapper.getSuccessRefeeralCount(entity);
        PageDto pageDto = PageDto.format(entity, count);
        List<UserReferralDto> list = userReferralMapper.getSuccessRefeeralList(entity);
        return ResultWithPagerDto.success(pageDto,list);
    }

}
