package com.crm.manager.service.impl;

import com.crm.manager.dao.mapper.CustomEmailSubscribeRecordMapper;
import com.crm.manager.dao.repository.CustomEmailSubscribeRecordRepository;
import com.crm.manager.dao.repository.CustomInfoRepository;
import com.crm.manager.dto.export.CustomEmailSubscribeRecordExportDto;
import com.crm.manager.service.CustomEmailSubscribeRecordService;
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.entity.custom.email.subscribe.record.CustomEmailSubscribeRecordSearchEntity;
import com.crm.rely.backend.core.pojo.view.CustomEmailSubscribeRecordView;
import com.crm.rely.backend.exception.ServiceException;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * 邮件订阅记录
 * @author gao
 * @date 2025/7/21 14:38
 */
@Service
public class CustomEmailSubscribeRecordServiceImpl implements CustomEmailSubscribeRecordService {

    @Autowired
    private CustomEmailSubscribeRecordRepository customEmailSubscribeRecordRepository;

    @Autowired
    private CustomEmailSubscribeRecordMapper mapper;

    @Autowired
    private CustomInfoRepository customInfoRepository;

    /**
     * 分页列表
     */
    @Override
    public ResultWithPagerDto<CustomEmailSubscribeRecordView> searchPageList(CustomEmailSubscribeRecordSearchEntity entity) throws ServiceException{
        Integer count = mapper.countList(entity);
        PageDto pageDto = PageDto.format(entity, count);
        if (count == null || count <= 0) {
            return ResultWithPagerDto.success(pageDto);
        }
        List<CustomEmailSubscribeRecordView> tables = mapper.pageList(entity);
        if (CollectionUtils.isEmpty(tables)) {
            throw new ServiceException(Constants.SYSTEM_ERROR);
        }

        return ResultWithPagerDto.success(pageDto, tables);
    }

    /**
     * 导出
     */
    @Override
    public List<CustomEmailSubscribeRecordExportDto> export(CustomEmailSubscribeRecordSearchEntity entity) throws ServiceException {
        List<CustomEmailSubscribeRecordView> customEmailSubscribeRecordVies = mapper.pageList(entity);
        if (CollectionUtils.isEmpty(customEmailSubscribeRecordVies)){
            return Collections.emptyList();
        }
        List<CustomEmailSubscribeRecordExportDto> dtos = Lists.newArrayList();
        customEmailSubscribeRecordVies.forEach((item) -> {
            CustomEmailSubscribeRecordExportDto dto = new CustomEmailSubscribeRecordExportDto();
            BeanUtils.copyProperties(item, dto);
            dtos.add(dto);
        });
        return dtos;
    }

}
