package com.crm.manager.service.impl;

import com.crm.manager.dao.repository.FollowCommissionConfigRepository;
import com.crm.manager.service.follow.FollowCommissionConfigService;
import com.crm.rely.backend.core.dto.follow.config.FollowCommissionConfigDto;
import com.crm.rely.backend.core.entity.follow.config.FollowCommissionConfigAddEntity;
import com.crm.rely.backend.core.pojo.table.FollowCommissionConfigTable;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

/**
 * @author y
 * @create 2022/6/21
 */
@Service
public class FollowCommissionConfigServiceImpl implements FollowCommissionConfigService {

    @Autowired
    private FollowCommissionConfigRepository followCommissionConfigRepository;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(List<FollowCommissionConfigAddEntity> entities) throws Exception {

        List<FollowCommissionConfigTable> tables = followCommissionConfigRepository.findAll();
        if (tables == null) {
            tables = Lists.newArrayList();
        }

        for (FollowCommissionConfigAddEntity entity : entities) {

            FollowCommissionConfigTable fcct = null;

            for (FollowCommissionConfigTable table : tables) {
                if (table.getType().equals(entity.getType())) {
                    fcct = table;
                    break;
                }
            }

            if (fcct == null) {
                FollowCommissionConfigTable table = new FollowCommissionConfigTable();
                table.setPoint(entity.getPoint());
                table.setType(entity.getType());
                table.setAddTime(new Date());
                tables.add(table);
            } else {
                fcct.setPoint(entity.getPoint());
                fcct.setModifyTime(new Date());
            }

        }

        if (!CollectionUtils.isEmpty(tables)) {
            for (FollowCommissionConfigTable table : tables) {
                followCommissionConfigRepository.save(table);
            }
        }
    }

    @Override
    public List<FollowCommissionConfigDto> getList() throws Exception {

        List<FollowCommissionConfigTable> tables = followCommissionConfigRepository.findAll();
        List<FollowCommissionConfigDto> dtos = Lists.newArrayList();
        for (FollowCommissionConfigTable table : tables) {
            FollowCommissionConfigDto dto = new FollowCommissionConfigDto();
            BeanUtils.copyProperties(table, dto);
            dtos.add(dto);
        }
        return dtos;
    }
}
