package com.crm.manager.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.crm.manager.dao.mapper.BusinessEmailSentRecordMapper;
import com.crm.manager.dao.repository.BusinessEmailSentRecordRepository;
import com.crm.manager.service.BusinessEmailSentRecordService;
import com.crm.manager.service.UserInfoService;
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.business.email.sent.BusinessEmailSentRecordDto;
import com.crm.rely.backend.core.dto.user.info.UserInfoSearchDto;
import com.crm.rely.backend.core.entity.tenant.email.sent.BusinessEmailSentRecordAddEntity;
import com.crm.rely.backend.core.entity.tenant.email.sent.BusinessEmailSentRecordSearchEntity;
import com.crm.rely.backend.core.entity.system.email.SysEmailSendEntity;
import com.crm.rely.backend.core.pojo.table.BusinessEmailSentRecordTable;
import com.crm.rely.backend.exception.ServiceException;
import com.crm.rely.backend.service.MqSendService;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Log4j
@Service
public class BusinessEmailSentRecordServiceImpl implements BusinessEmailSentRecordService {

    private final static String BUSINESS_EMAIL_SENT_RECORD = "BUSINESS_EMAIL.SENT_RECORD";
    @Autowired
    private BusinessEmailSentRecordRepository repository;
    @Autowired
    private BusinessEmailSentRecordMapper mapper;
    @Autowired
    private MqSendService mqSendService;
    @Autowired
    private UserInfoService userInfoService;

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


        BusinessEmailSentRecordTable table = new BusinessEmailSentRecordTable();
        BeanUtils.copyProperties(entity, table);

        UserInfoSearchDto agent = userInfoService.searchSingle(entity.getAgentId());
        table.setAgentIbNo(agent.getIbNo());
        table.setAgentName(agent.getName());

        repository.save(table);

        SysEmailSendEntity sysEmailSendEntity = createSendEmailEntity(table);
        mqSendService.send(Constants.ACTIVEMQ_JMS_URL_EMAIL, sysEmailSendEntity, 5 * 1000);
    }

    @JmsListener(destination = BUSINESS_EMAIL_SENT_RECORD)
    @Transactional(rollbackFor = {Exception.class})
    public void callbackSentEmail(String content) {
        JSONObject callbackEntity = JSON.parseObject(content);
        if (callbackEntity == null) {
            log.error("BUSINESS_EMAIL_SENT_RECORD callback error:" + content);
        }

        Long id = Long.valueOf(callbackEntity.getString("note"));
        BusinessEmailSentRecordTable table = repository.findFirstById(id);

        if (table == null) {
            log.error("BUSINESS_EMAIL_SENT_RECORD callback note id error:" + content);
            return;
        }

        Date sentDate = callbackEntity.getDate("sendDate");
        table.setSendDate(sentDate);

        String errorMsg = callbackEntity.getString("errorMsg");
        table.setErrorMsg(errorMsg);
        repository.save(table);
    }

    @Override
    public ResultWithPagerDto<BusinessEmailSentRecordDto> searchList(BusinessEmailSentRecordSearchEntity entity) throws ServiceException {

        int count = selectCount(entity);
        PageDto pageDto = PageDto.format(entity, count);
        if (count <= 0) {
            return ResultWithPagerDto.success(pageDto);
        }
        List<BusinessEmailSentRecordDto> dtos = getDto(entity);
        if (dtos == null) {
            throw ServiceException.exception(Constants.SYSTEM_ERROR);
        }
        return ResultWithPagerDto.success(pageDto, dtos);
    }

    private List<BusinessEmailSentRecordDto> getDto(BusinessEmailSentRecordSearchEntity search) {
        List<BusinessEmailSentRecordTable> tables = mapper.selectList(search);
        if (tables == null || tables.size() <= 0) {
            return null;
        }
        List<BusinessEmailSentRecordDto> dtos = new ArrayList<>(tables.size());
        for (BusinessEmailSentRecordTable table : tables) {
            BusinessEmailSentRecordDto dto = transform(table);
            dto.setContent(null);
            dtos.add(dto);
        }
        return dtos;
    }

    @Override
    public int selectCount(BusinessEmailSentRecordSearchEntity searchCount) {
        return mapper.selectCount(searchCount);
    }

    @Override
    public BusinessEmailSentRecordDto searchSingle(Long id) throws ServiceException {
        BusinessEmailSentRecordTable financeRateTable = repository.getFirstById(id);
        if (financeRateTable == null) {
            throw ServiceException.exception(Constants.INFO_NOT_FOUND);
        }
        return transform(financeRateTable);
    }


    private SysEmailSendEntity createSendEmailEntity(BusinessEmailSentRecordTable table) {
        SysEmailSendEntity sysEmailSendEntity = new SysEmailSendEntity();

        sysEmailSendEntity.setAddIp(table.getAddIp());
        sysEmailSendEntity.setAddTime(table.getAddTime());

        sysEmailSendEntity.setUsers(table.getUsers());

        sysEmailSendEntity.setSubject(table.getSubject());
        sysEmailSendEntity.setContent(table.getContent());
        sysEmailSendEntity.setSetSent(1);
        sysEmailSendEntity.setCallbackMq(BUSINESS_EMAIL_SENT_RECORD);
        sysEmailSendEntity.setNote(String.valueOf(table.getId()));


        return sysEmailSendEntity;
    }


    private BusinessEmailSentRecordDto transform(BusinessEmailSentRecordTable table) {
        BusinessEmailSentRecordDto dto = new BusinessEmailSentRecordDto();
        BeanUtils.copyProperties(table, dto);
        return dto;
    }
}
