package com.crm.manager.service.impl;

import com.crm.manager.dao.mapper.MarketEmailMapper;
import com.crm.manager.dao.repository.MarketEmailRepository;
import com.crm.manager.service.CustomInfoService;
import com.crm.manager.service.MarketEmailRecordService;
import com.crm.manager.service.MarketEmailService;
import com.crm.manager.service.SysConfigService;
import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.core.constant.MapConstants;
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.base.SingleLongEntity;
import com.crm.rely.backend.core.entity.system.email.SysEmailSendEntity;
import com.crm.rely.backend.core.exception.ServiceException;
import com.crm.rely.backend.core.pojo.table.SysConfigTable;
import com.crm.rely.backend.model.dto.market.email.MarketEmailListDto;
import com.crm.rely.backend.model.entity.market.MarketEmailAddEntity;
import com.crm.rely.backend.model.entity.market.MarketEmailSearchPageEntity;
import com.crm.rely.backend.model.entity.market.MarketEmailTestEntity;
import com.crm.rely.backend.model.pojo.table.CustomInfoTable;
import com.crm.rely.backend.model.pojo.table.MarketEmailTable;
import com.crm.rely.backend.service.EmailService;
import com.crm.rely.backend.util.DateUtil;
import com.crm.rely.backend.util.RexUtil;
import com.google.common.base.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MarketEmailServiceImpl implements MarketEmailService {

    @Autowired
    private MarketEmailRepository marketEmailRepository;

    @Autowired
    private MarketEmailMapper marketEmailMapper;

    @Autowired
    private MarketEmailRecordService marketEmailRecordService;

    @Autowired
    private SysConfigService sysConfigService;

    @Autowired
    private EmailService emailService;

    @Autowired
    private CustomInfoService customInfoService;


    @Override
//    @Transactional(rollbackFor = Exception.class)
    public MarketEmailTable add(MarketEmailAddEntity entity) throws ServiceException {
        Long emailConfigId = getEmailConfigId();

        MarketEmailTable marketEmailTable = new MarketEmailTable();
        BeanUtils.copyProperties(entity, marketEmailTable);
        marketEmailTable.setEmailConfigId(emailConfigId);
        marketEmailRepository.save(marketEmailTable);
        entity.setId(marketEmailTable.getId());
        Integer number = marketEmailRecordService.add(entity);
        marketEmailTable.setNumber(number);
        marketEmailRepository.save(marketEmailTable);
        return marketEmailTable;
    }

    @Override
    public void test(MarketEmailTestEntity entity) throws ServiceException {
        Long emailConfigId = getEmailConfigId();
        SysEmailSendEntity sysEmailSendEntity = new SysEmailSendEntity();
        sysEmailSendEntity.setEmailConfigId(emailConfigId);
        sysEmailSendEntity.setSubject(entity.getSubject());
        sysEmailSendEntity.setContent(entity.getContent());
        sysEmailSendEntity.setUsers(entity.getEmail());

        Map<String, String> map = new HashMap<>(3);
        map.put(MapConstants.DATE_TIME, DateUtil.formatTime());
        CustomInfoTable customInfoTable = customInfoService.getSingleCustomInfoByEmail(entity.getEmail());
        if (customInfoTable != null) {
            map.put(MapConstants.NAME, RexUtil.rexName(customInfoTable.getFirstName()));
            map.put(MapConstants.C_ID, String.valueOf(customInfoTable.getCId()));
        }
        sysEmailSendEntity.setMap(map);
        emailService.sendEmail(sysEmailSendEntity, Constants.ACTIVEMQ_JMS_URL_EMAIL_MARKETS);
    }

    private Long getEmailConfigId() {
        Long emailConfigId;
        SysConfigTable sysConfigTable = sysConfigService.getByCode("EMAIL_CONFIG");
        if (sysConfigTable == null) {
            emailConfigId = null;
        } else {
            if (Strings.isNullOrEmpty(sysConfigTable.getValue())) {
                emailConfigId = null;
            } else {
                try {
                    emailConfigId = Long.parseLong(sysConfigTable.getValue());
                } catch (Exception e) {
                    emailConfigId = null;
                }
            }
        }
        return emailConfigId;
    }

    @Override
    public ResultWithPagerDto<MarketEmailListDto> searchPageList(MarketEmailSearchPageEntity entity) throws Exception {
        Integer count = marketEmailMapper.countList(entity);
        PageDto pageDto = PageDto.format(entity, count);
        if (count == null || count <= 0) {
            return ResultWithPagerDto.success(pageDto);
        }
        List<MarketEmailListDto> sysEmailTemplateSearchDtos = getMarketEmailListDto(entity);
        if (sysEmailTemplateSearchDtos == null) {
            throw ServiceException.exception(Constants.SYSTEM_ERROR);
        }

        return ResultWithPagerDto.success(pageDto, sysEmailTemplateSearchDtos);
    }

    @Override
    public MarketEmailListDto searchSingle(SingleLongEntity entity) throws Exception {
        MarketEmailTable marketEmailTable = marketEmailRepository.getFirstById(entity.getId());
        if (marketEmailTable == null) {
            throw ServiceException.exception(Constants.INFO_NOT_FOUND);
        }
        return transform(marketEmailTable);
    }

    private List<MarketEmailListDto> getMarketEmailListDto(MarketEmailSearchPageEntity entity) throws ServiceException {
        List<MarketEmailTable> marketEmailTables = marketEmailMapper.pageList(entity);

        if (marketEmailTables == null || marketEmailTables.size() <= 0) {

            return null;
        }
        List<MarketEmailListDto> marketEmailListDtos = new ArrayList<>(marketEmailTables.size());

        for (MarketEmailTable marketEmailTable : marketEmailTables) {
            MarketEmailListDto marketEmailRecordListDto = transform(marketEmailTable);
            marketEmailListDtos.add(marketEmailRecordListDto);
        }
        return marketEmailListDtos;
    }


    private MarketEmailListDto transform(MarketEmailTable marketEmailTable) {
        MarketEmailListDto marketEmailRecordListDto = new MarketEmailListDto();
        BeanUtils.copyProperties(marketEmailTable, marketEmailRecordListDto);
        return marketEmailRecordListDto;
    }
}
