package com.crm.web.service.impl;

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.pojo.table.SysEmailTemplateTable;
import com.crm.rely.backend.core.exception.ServiceException;
import com.crm.rely.backend.model.dto.web.notice.record.WebNoticeRecordDto;
import com.crm.rely.backend.model.entity.web.notice.record.WebNoticeRecordAddEntity;
import com.crm.rely.backend.model.entity.web.notice.record.WebNoticeRecordReadEntity;
import com.crm.rely.backend.model.entity.web.notice.record.WebNoticeRecordSearchPageEntity;
import com.crm.rely.backend.model.pojo.table.WebNoticeRecordTable;
import com.crm.rely.backend.util.DateUtil;
import com.crm.rely.backend.util.FileProcessUtil;
import com.crm.rely.backend.util.TemplateUtil;
import com.crm.web.dao.mapper.WebNoticeRecordMapper;
import com.crm.web.dao.repository.SysEmailTemplateRepository;
import com.crm.web.dao.repository.WebNoticeRecordRepository;
import com.crm.web.service.WebNoticeRecordService;
import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Slf4j
@Service
public class WebNoticeRecordServiceImpl implements WebNoticeRecordService {

    @Autowired
    private WebNoticeRecordRepository webNoticeRecordRepository;

    @Autowired
    private WebNoticeRecordMapper webNoticeRecordMapper;

    @Autowired
    private SysEmailTemplateRepository sysEmailTemplateRepository;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(List<WebNoticeRecordAddEntity> entities) throws ServiceException, InterruptedException {

        if (entities == null || entities.size() <= 0) {
            return;
        }
        List<WebNoticeRecordTable> tables = new ArrayList<>(entities.size());

        for (WebNoticeRecordAddEntity emailRecordAddEntity : entities) {

            WebNoticeRecordTable marketEmailRecordTable = new WebNoticeRecordTable();

            BeanUtils.copyProperties(emailRecordAddEntity, marketEmailRecordTable);
            setContent(marketEmailRecordTable);
            tables.add(marketEmailRecordTable);
        }
        webNoticeRecordRepository.save(tables);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(WebNoticeRecordAddEntity entity) throws ServiceException {

        if (entity == null) {
            return;
        }
        WebNoticeRecordTable table = new WebNoticeRecordTable();

        BeanUtils.copyProperties(entity, table);
        setContent(table, entity);

        webNoticeRecordRepository.save(table);
    }

    private void setContent(List<WebNoticeRecordTable> tables) throws ServiceException {
        for (WebNoticeRecordTable table : tables) {
            setContent(table);
        }
    }

    private void setContent(WebNoticeRecordTable marketEmailRecordTable) throws ServiceException {
        setContent(marketEmailRecordTable, null);
    }

    private void setContent(WebNoticeRecordTable marketEmailRecordTable, WebNoticeRecordAddEntity entity) throws ServiceException {
        if (marketEmailRecordTable == null) {
            throw ServiceException.exception(Constants.SYSTEM_ERROR);
        }

        Map<String, String> map = new HashMap<>(2);

        map.put(MapConstants.DATE_TIME, DateUtil.formatTime());
        if (entity != null) {
            if (!Strings.isNullOrEmpty(entity.getTemplateName())) {
                String content;
                /**
                 * 根据模版名称是否为null或者"" 判断是否是模版发送
                 */
                if (!Strings.isNullOrEmpty(entity.getTemplateName())) {
                    //根据模版名称到数据库中获取模版内容
                    SysEmailTemplateTable sysEmailTemplateTable = sysEmailTemplateRepository.getByCode(entity.getTemplateName());
                    if (sysEmailTemplateTable == null) {

                        //在根据模本名称(地址)获取模版内容
                        content = FileProcessUtil.getFileContent(entity.getTemplateName());
                    } else {
                        content = sysEmailTemplateTable.getContent();
                        marketEmailRecordTable.setSubject(sysEmailTemplateTable.getSubject());
                    }
                    marketEmailRecordTable.setContent(content);
                }
            }

            if (entity.getMap() != null && entity.getMap().size() > 0) {
                map.putAll(entity.getMap());
            }
        }

        marketEmailRecordTable.setRead(0);
        if (!Strings.isNullOrEmpty(marketEmailRecordTable.getContent())) {
            marketEmailRecordTable.setContent(TemplateUtil.replace(marketEmailRecordTable.getContent(), map));
        }

    }

    @Override
    public ResultWithPagerDto<WebNoticeRecordDto> searchPageList(WebNoticeRecordSearchPageEntity entity) throws Exception {
        Integer count = webNoticeRecordMapper.countList(entity);

        PageDto pageDto = PageDto.format(entity, count);
        if (count == null || count <= 0) {
            return ResultWithPagerDto.success(pageDto);
        }
        List<WebNoticeRecordDto> sysEmailTemplateSearchDtos = getWebNoticeRecordDto(entity);
        if (sysEmailTemplateSearchDtos == null) {
            throw ServiceException.exception(Constants.SYSTEM_ERROR);
        }

        return ResultWithPagerDto.success(pageDto, sysEmailTemplateSearchDtos);
    }

    @Override
    public WebNoticeRecordDto searchSingle(SingleLongEntity entity) throws Exception {
        WebNoticeRecordTable marketEmailRecordTable = webNoticeRecordRepository.getFirstById(entity.getId());
        if (marketEmailRecordTable == null) {
            throw ServiceException.exception(Constants.INFO_NOT_FOUND);
        }
        return transform(marketEmailRecordTable);
    }

    @Override
    public Integer countRead(WebNoticeRecordSearchPageEntity entity) throws Exception {
        Integer count = webNoticeRecordMapper.countList(entity);

        return count;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void read(WebNoticeRecordReadEntity entity) throws Exception {
        List<WebNoticeRecordTable> webNoticeRecordTables;
        if (entity.getIds() == null) {
            webNoticeRecordTables =
                    webNoticeRecordRepository.findFirstByCustomIdAndRead(entity.getCustomId(), 0);
        } else {
            webNoticeRecordTables =
                    webNoticeRecordRepository.findFirstByIdInAndCustomIdAndRead(entity.getIds(), entity.getCustomId(), 0);
        }

        if (webNoticeRecordTables == null || webNoticeRecordTables.size() <= 0) {
            return;
        }
        List<WebNoticeRecordTable> webNoticeRecordTableSaves = new ArrayList<>(webNoticeRecordTables.size());
        for (WebNoticeRecordTable webNoticeRecordTable : webNoticeRecordTables) {
            if (webNoticeRecordTable.getRead() == null || webNoticeRecordTable.getRead().equals(0)) {
                BeanUtils.copyProperties(entity, webNoticeRecordTable);
                webNoticeRecordTableSaves.add(webNoticeRecordTable);
            }
        }

        if (webNoticeRecordTableSaves != null && webNoticeRecordTableSaves.size() > 0) {
            webNoticeRecordRepository.save(webNoticeRecordTableSaves);
        }

    }

    private List<WebNoticeRecordDto> getWebNoticeRecordDto(WebNoticeRecordSearchPageEntity entity) throws ServiceException {
        List<WebNoticeRecordTable> marketEmailRecordTables = webNoticeRecordMapper.pageList(entity);

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

            return null;
        }
        List<WebNoticeRecordDto> sysEmailTemplateSearchDtos = new ArrayList<>(marketEmailRecordTables.size());

        for (WebNoticeRecordTable emailRecordTable : marketEmailRecordTables) {
            WebNoticeRecordDto marketEmailRecordListDto = transform(emailRecordTable);
            sysEmailTemplateSearchDtos.add(marketEmailRecordListDto);
        }
        return sysEmailTemplateSearchDtos;
    }

    private WebNoticeRecordDto transform(WebNoticeRecordTable marketEmailRecordTable) {
        WebNoticeRecordDto marketEmailRecordListDto = new WebNoticeRecordDto();
        BeanUtils.copyProperties(marketEmailRecordTable, marketEmailRecordListDto);
        return marketEmailRecordListDto;
    }
}
