package com.crm.email.service.impl;

import com.alibaba.fastjson.JSON;
import com.crm.email.dao.mapper.SysEmailUnsubscribeMapper;
import com.crm.email.dao.repository.SysEmailUnsubscribeRepository;
import com.crm.email.service.SysConfigService;
import com.crm.email.service.SysEmailUnsubscribeService;
import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.core.constant.GlobalConfigConstants;
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.system.email.unsubscribe.SysEmailUnsubscribeSearchDto;
import com.crm.rely.backend.core.entity.base.SingleLongEntity;
import com.crm.rely.backend.core.entity.system.email.unsubscribe.*;
import com.crm.rely.backend.core.exception.ServiceException;
import com.crm.rely.backend.core.pojo.table.SysConfigTable;
import com.crm.rely.backend.core.pojo.table.SysEmailUnsubscribeTable;
import com.crm.rely.backend.util.RSAUtil;
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.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: houn
 * @Date: 2020/12/25 20:19
 * @Description:
 */
@Service
public class SysEmailUnsubscribeServiceImpl implements SysEmailUnsubscribeService {


    private static final String enc = "UTF-8";
    private static final String publicKey = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAI" +
            "+YnamJYvtr3tJPqceIaLnKJ2Lj6hBq9PJgbBy9iCC3Y8Q/hx05WsY2GF1LxV+BzA4LR/Y40rhdaiXMcJ4Hj7MCAwEAAQ==";
    private static final String privateKey = "MIIBUwIBADANBgkqhkiG9w0BAQEFAASCAT0wggE5AgEAAkEAj5idqYli+2ve0k" +
            "+px4houconYuPqEGr08mBsHL2IILdjxD+HHTlaxjYYXUvFX4HMDgtH9jjSuF1qJcxwngePswIDAQABAkBr4tc55G4IxlAAJThDINrGE" +
            "/spkmFuel2UqRsxMLlREja" +
            "+DKXQGAncP6ET4gBFiC4uyzPltv2i2RtlEc2IB6NJAiEA0kmXh7X8QXSETwQX309UhqUaET0HbnAYV1RttPuFnScCIQCuz65IvQUYFzOjaGDqyqgrb2nEgmO1A+cPwoUyvMMolQIgTE8UQ9UQUxhbIulTWF/LRokHKpZA6hyXWKl0niZf2CUCIEqvAZej4axEJVSXwGgvAp/j7nz889oe+7V49m0RxhLtAiB126F98BpiZ9XaoUyZL/Fo6pSSUvQbZMqEpXHlWFQ0ow==";


    @Autowired
    private SysEmailUnsubscribeRepository sysEmailUnsubscribeRepository;

    @Autowired
    private SysEmailUnsubscribeMapper sysEmailUnsubscribeMapper;

    @Autowired
    private SysConfigService sysConfigService;

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

        SysEmailUnsubscribeTable table = new SysEmailUnsubscribeTable();

        BeanUtils.copyProperties(entity, table);
        sysEmailUnsubscribeRepository.save(table);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(SysEmailUnsubscribeRequestEntity entity) throws Exception {
        String sysEmailUnsubscribeUrlEntityJson = RSAUtil.decryptByPublicKey(entity.getUnsubscribe(), publicKey);
        SysEmailUnsubscribeUrlEntity sysEmailUnsubscribeUrlEntity = JSON.parseObject(sysEmailUnsubscribeUrlEntityJson
                , SysEmailUnsubscribeUrlEntity.class);

        if (sysEmailUnsubscribeRepository.existsByFromAccountAndToAccount(sysEmailUnsubscribeUrlEntity.getFromAccount(), sysEmailUnsubscribeUrlEntity.getToAccount())) {
            return;
        }
        SysEmailUnsubscribeTable table = new SysEmailUnsubscribeTable();

        BeanUtils.copyProperties(entity, table);
        table.setFromAccount(sysEmailUnsubscribeUrlEntity.getFromAccount());
        table.setToAccount(sysEmailUnsubscribeUrlEntity.getToAccount());
        sysEmailUnsubscribeRepository.save(table);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(SysEmailUnsubscribeDeleteEntity entity) throws ServiceException {
        List<SysEmailUnsubscribeTable> tables = sysEmailUnsubscribeRepository.findAllByIdIn(entity.getIds());
        if (tables != null) {
            sysEmailUnsubscribeRepository.delete(tables);
        }
    }

    @Override
    public ResultWithPagerDto<SysEmailUnsubscribeSearchDto> searchPageList(SysEmailUnsubscribeSearchListEntity entity) throws ServiceException {
        Integer count = sysEmailUnsubscribeMapper.searchPageCount(entity);
        PageDto pageDto = PageDto.format(entity, count);
        if (count == null || count <= 0) {
            return ResultWithPagerDto.success(pageDto);
        }
        List<SysEmailUnsubscribeTable> tables = sysEmailUnsubscribeMapper.searchPageList(entity);

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

            throw new ServiceException(Constants.SYSTEM_ERROR);
        }
        List<SysEmailUnsubscribeSearchDto> sysEmailRecordSearchDtos = transform(tables);

        return ResultWithPagerDto.success(pageDto, sysEmailRecordSearchDtos);
    }

    @Override
    public SysEmailUnsubscribeSearchDto searchSingle(SingleLongEntity entity) throws ServiceException {
        SysEmailUnsubscribeTable sysEmailUnsubscribeTable = sysEmailUnsubscribeRepository.getFirstById(entity.getId());
        if (sysEmailUnsubscribeTable == null) {
            throw ServiceException.exception(Constants.INFO_NOT_FOUND);
        }
        return transform(sysEmailUnsubscribeTable);
    }

    @Override
    public boolean exist(String fromAccount, String toAccount) throws ServiceException {
        return sysEmailUnsubscribeRepository.existsByFromAccountAndToAccount(fromAccount, toAccount);
    }

    @Override
    public String getUnsubscribeUrl(String fromAccount, String toAccount) throws Exception {
        List<String> codes = new ArrayList<>(2);

        String unsubscribeUrl = "";
        String myUrl = "";
        String unsubscribeConfig = "";
        codes.add(GlobalConfigConstants.WEB_MY_URE_CONFIG);
        codes.add(GlobalConfigConstants.UNSUBSCRIBE_CONFIG);
        List<SysConfigTable> sysConfigTables = sysConfigService.getByCodes(codes);

        if (sysConfigTables == null || sysConfigTables.size() < 2) {
            throw ServiceException.exception(Constants.SYSTEM_ERROR);
        }
        for (SysConfigTable sysConfigTable : sysConfigTables) {
            if (GlobalConfigConstants.WEB_MY_URE_CONFIG.equals(sysConfigTable.getCode())) {
                myUrl = sysConfigTable.getValue();
            }
            if (GlobalConfigConstants.UNSUBSCRIBE_CONFIG.equals(sysConfigTable.getCode())) {
                unsubscribeConfig = sysConfigTable.getValue();
            }
        }

        SysEmailUnsubscribeUrlEntity sysEmailUnsubscribeUrlEntity = new SysEmailUnsubscribeUrlEntity();
        sysEmailUnsubscribeUrlEntity.setFromAccount(fromAccount);
        sysEmailUnsubscribeUrlEntity.setToAccount(toAccount);

        String sysEmailUnsubscribeUrlEntityJsonString = JSON.toJSONString(sysEmailUnsubscribeUrlEntity);

        String sysEmailUnsubscribeUrlEntityRsa = RSAUtil.encryptByPrivateKey(sysEmailUnsubscribeUrlEntityJsonString,
                privateKey);

        unsubscribeUrl = String.format("%s%s?unsubscribe=%s", myUrl, unsubscribeConfig,
                URLEncoder.encode(sysEmailUnsubscribeUrlEntityRsa, enc));
        return unsubscribeUrl;
    }

    private List<SysEmailUnsubscribeSearchDto> transform(List<SysEmailUnsubscribeTable> sysEmailUnsubscribeTables) {
        if (sysEmailUnsubscribeTables == null && sysEmailUnsubscribeTables.size() <= 0) {
            return null;
        }
        List<SysEmailUnsubscribeSearchDto> sysEmailUnsubscribeSearchDtos =
                new ArrayList<>(sysEmailUnsubscribeTables.size());
        for (SysEmailUnsubscribeTable sysEmailUnsubscribeTable : sysEmailUnsubscribeTables) {
            SysEmailUnsubscribeSearchDto sysEmailRecordSearchDto = transform(sysEmailUnsubscribeTable);

            sysEmailUnsubscribeSearchDtos.add(sysEmailRecordSearchDto);
        }
        return sysEmailUnsubscribeSearchDtos;
    }

    private SysEmailUnsubscribeSearchDto transform(SysEmailUnsubscribeTable sysEmailUnsubscribeTable) {
        SysEmailUnsubscribeSearchDto sysEmailUnsubscribeSearchDto = new SysEmailUnsubscribeSearchDto();

        BeanUtils.copyProperties(sysEmailUnsubscribeTable, sysEmailUnsubscribeSearchDto);
        return sysEmailUnsubscribeSearchDto;
    }
}
