package com.storlead.mail.controller;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.storlead.framework.common.util.encryptor.AccessKeyEncryptor;
import com.storlead.framework.util.LoginUserUtil;
import com.storlead.framework.common.result.Result;
import com.storlead.mail.connection.MailConnection;
import com.storlead.mail.connection.client.MailConnectionUtil;
import com.storlead.mail.connection.config.MailProperties;
import com.storlead.mail.pojo.entity.EmailsEntity;
import com.storlead.mail.pojo.entity.MailboxAutoReplySetEntity;
import com.storlead.mail.pojo.entity.SmtpPopSettingsEntity;
import com.storlead.mail.enums.EmailBoxEnum;
import com.storlead.mail.pojo.vo.MailAcountVO;
import com.storlead.mail.service.EmailsService;
import com.storlead.mail.service.SmtpPopSettingsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.log4j.Log4j2;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.mail.*;
import java.util.*;

/**
 * <p>
 * 邮箱smtp_setting 前端控制器
 * </p>
 *
 * @author chenkq
 * @since 2024-05-28
 */
@Log4j2
@RestController
@RequestMapping("/smtp/pop/setting")
@Api(tags = "邮件: 邮件管理")
public class SmtpPopSettingsApiController {

    @Resource
    private SmtpPopSettingsService smtpPopSettingsService;

    @Resource
    private EmailsService emailsService;


    @PostMapping(value = "/pageList")
    @ApiOperation(value = "获取我的邮箱配置信息" )
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = SmtpPopSettingsEntity.class)
    })
    public Result<?> pageList(com.storlead.framework.mybatis.page.Page dto) {
        Long currentUserId = LoginUserUtil.getCurrentUserId();
        if (Objects.isNull(currentUserId)) {
            return Result.result(null);
        }
        AccessKeyEncryptor encryptor = AccessKeyEncryptor.getAccessKeyEncryptor("");
        Page<SmtpPopSettingsEntity> page = new Page<>(dto.getPageIndex(),dto.getPageSize());
        LambdaQueryWrapper<SmtpPopSettingsEntity> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(SmtpPopSettingsEntity::getIsDelete,Integer.valueOf(0));
        queryWrapper.eq(SmtpPopSettingsEntity::getOwnerBy,currentUserId);
        IPage<SmtpPopSettingsEntity> pageList =  smtpPopSettingsService.page(page,queryWrapper);
        if (!CollectionUtils.isEmpty(pageList.getRecords())) {
            pageList.getRecords().forEach(e -> {
                e.setEmailPassword(encryptor.decrypt(e.getEmailPassword()));
            });
        }
        return Result.result(pageList);
    }

//    @PostMapping(value = "/listAutoReplySettings")
//    @ApiOperation(value = "获取我的邮箱配置信息" )
//    @ApiResponses({
//            @ApiResponse(code = 200, message = "", response = SmtpPopSettingsEntity.class)
//    })
//    public Result<?> listAutoReplySettings(com.storlead.common.object.Page dto) {
//        Long currentUserId = LoginUserUtil.getCurrentUserId();
//        if (Objects.isNull(currentUserId)) {
//            return Result.result(null);
//        }
//        AccessKeyEncryptor encryptor = AccessKeyEncryptor.getAccessKeyEncryptor("");
//        Page<SmtpPopSettingsEntity> page = new Page<>(dto.getPageIndex(),dto.getPageSize());
//        LambdaQueryWrapper<SmtpPopSettingsEntity> queryWrapper = new LambdaQueryWrapper();
//        queryWrapper.eq(SmtpPopSettingsEntity::getIsDelete,Integer.valueOf(0));
//        queryWrapper.eq(SmtpPopSettingsEntity::getOwnerBy,currentUserId);
//        IPage<SmtpPopSettingsEntity> pageList =  smtpPopSettingsService.page(page,queryWrapper);
//        if (!CollectionUtils.isEmpty(pageList.getRecords())) {
//            pageList.getRecords().forEach(e -> {
//                e.setEmailPassword(encryptor.decrypt(e.getEmailPassword()));
//            });
//        }
//        return Result.result(pageList);
//    }
    @PostMapping(value = "/setReplyContent")
    @ApiOperation(value = "设置自动回复内容，并且开始" )
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = MailboxAutoReplySetEntity.class)
    })
    public Result<?> setReplyContent(Long id,String replyContent,String replyTitle,Integer autoReplyStatus) {
        if (Objects.isNull(id) || Objects.isNull(autoReplyStatus)) {
            return Result.error("参数错误");
        }
        if (Integer.valueOf(1).equals(autoReplyStatus)) {
            if(StrUtil.isBlank(replyContent) || StrUtil.isBlank(replyTitle)) {
                return Result.error("参数错误");
            }
        }
        LambdaUpdateWrapper<SmtpPopSettingsEntity> updateWrapper = new LambdaUpdateWrapper();
        updateWrapper.set(SmtpPopSettingsEntity::getReplyContent,replyContent);
        updateWrapper.set(SmtpPopSettingsEntity::getReplyTitle,replyTitle);
        updateWrapper.set(SmtpPopSettingsEntity::getReplyOnTime,new Date());
        updateWrapper.set(SmtpPopSettingsEntity::getIsAutoReply,autoReplyStatus);
        updateWrapper.eq(SmtpPopSettingsEntity::getId,id);
        smtpPopSettingsService.update(updateWrapper);
        return Result.ok();
    }

    @PostMapping(value = "/setAutoReplyStatus")
    @ApiOperation(value = "设置自动回复是否开启：1：开启，0：关闭" )
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = MailboxAutoReplySetEntity.class)
    })
    public Result<?> setAutoReplyStatus(Long id,Integer autoReplyStatus) {
        if (Objects.isNull(id) || Objects.isNull(autoReplyStatus)) {
            return Result.error("参数错误");
        }
        LambdaUpdateWrapper<SmtpPopSettingsEntity> updateWrapper = new LambdaUpdateWrapper();
        updateWrapper.set(SmtpPopSettingsEntity::getIsAutoReply,autoReplyStatus);
        updateWrapper.set(SmtpPopSettingsEntity::getReplyOnTime,new Date());
        updateWrapper.eq(SmtpPopSettingsEntity::getId,id);
        smtpPopSettingsService.update(updateWrapper);
        return Result.ok();
    }

//    @PostMapping(value = "/list")
//    @ApiOperation(value = "获取我的邮箱配置信息" )
//    @ApiResponses({
//            @ApiResponse(code = 200, message = "", response = SmtpPopSettingsEntity.class)
//    })
//    public Result<?> list(com.storlead.common.object.Page dto) {
//        Long currentUserId = LoginUserUtil.getCurrentUserId();
//        if (Objects.isNull(currentUserId)) {
//            return Result.result(null);
//        }
//        Page<SmtpPopSettingsEntity> page = new Page<>(dto.getPageIndex(),dto.getPageSize());
//        LambdaQueryWrapper<SmtpPopSettingsEntity> queryWrapper = new LambdaQueryWrapper();
//        queryWrapper.eq(SmtpPopSettingsEntity::getOwnerBy,currentUserId);
//        IPage<SmtpPopSettingsEntity> pageList =  smtpPopSettingsService.page(page,queryWrapper);
//        return Result.result(pageList);
//    }

    @PostMapping(value = "/delete")
    @ApiOperation(value = "删除" )
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = SmtpPopSettingsEntity.class)
    })
    public Result<?> delete(Long id) {
        Long currentUserId = LoginUserUtil.getCurrentUserId();
        if (Objects.isNull(currentUserId)) {
            return Result.result(null);
        }
        SmtpPopSettingsEntity smtpPop = smtpPopSettingsService.getById(id);
        if (Objects.isNull(smtpPop)) {
            return Result.error("参数错误");
        }

        LambdaUpdateWrapper<SmtpPopSettingsEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(SmtpPopSettingsEntity::getIsDelete,Integer.valueOf(1));
        updateWrapper.eq(SmtpPopSettingsEntity::getId,id);
        smtpPopSettingsService.update(updateWrapper);
        return Result.ok();
    }

    @PostMapping(value = "/save")
    @ApiOperation(value = "保存或修改" )
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = Result.class)
    })
    public Result<?> save(@RequestBody SmtpPopSettingsEntity entity) {

        Long currentUserId = LoginUserUtil.getCurrentUserId();
        if (Objects.isNull(currentUserId)) {
            return Result.result(null);
        }
        /**
         * 保存邮箱先校验
         */
        if ("POP3".equals(entity.getProtocolType())) {
            if (!testPop3(entity)) {
                MailProperties properties = new MailProperties(entity);
                MailConnection mailConnection = MailConnectionUtil.receiveEmailsConnection(properties);
                if (Objects.isNull(mailConnection)) {
                    return Result.error("邮箱校验失败,请输入正确的账号密码");
                }
                mailConnection.close();
            }
        }else if("IMAP".equals(entity.getProtocolType())) {
            MailProperties properties = new MailProperties(entity);
            MailConnection mailConnection = MailConnectionUtil.receiveEmailsConnection(properties);
            if (!testImap(entity)) {
                return Result.error("邮箱校验失败,请输入正确的账号密码");
            }
            mailConnection.close();
        } else {
            return Result.error("邮箱校验失败,请输入正确的账号密码");
        }
        if (!testSmtp(entity)) {
            return Result.error("邮箱校验失败,请输入正确的账号密码");
        }
        /**
         * 修改和增加根据邮箱进行查重
         */
        AccessKeyEncryptor encryptor = AccessKeyEncryptor.getAccessKeyEncryptor("");
        entity.setEmailPassword(encryptor.encrypt(entity.getEmailPassword()));
        if (!Integer.valueOf(1).equals(entity.getUseDefault())) {
            LambdaQueryWrapper<SmtpPopSettingsEntity> queryWrapper = new LambdaQueryWrapper();
            queryWrapper.eq(SmtpPopSettingsEntity::getUseDefault, Integer.valueOf(1));
            queryWrapper.eq(SmtpPopSettingsEntity::getOwnerBy, currentUserId);
            queryWrapper.eq(SmtpPopSettingsEntity::getIsDelete, Integer.valueOf(0));
            queryWrapper.last("limit 1");
            SmtpPopSettingsEntity c = smtpPopSettingsService.getOne(queryWrapper);
            if (Objects.isNull(c)) {
                return Result.error("请设置默认邮箱");
            }
            if (Objects.nonNull(c) && c.getId().equals(entity.getId())) {
                return Result.error("请设置默认邮箱");
            }
        }

        if (Objects.nonNull(entity.getId())) {
            // 修改
            SmtpPopSettingsEntity old = smtpPopSettingsService.getById(entity.getId());
            if (Objects.nonNull(old)) {
                if(!old.getEmailAddress().equals(entity.getEmailAddress())){
                    return Result.error("已绑定的邮箱无法修改,可新增邮箱配置!");
                }
            }
        }
        Boolean b = smtpPopSettingsService.saveOrUpdate(entity);
        if (Integer.valueOf(1).equals(entity.getUseDefault()) && b) {
            // 如果设置了默认邮箱，则将所有默认邮箱改为非默认
            LambdaUpdateWrapper<SmtpPopSettingsEntity> updateWrapper = new LambdaUpdateWrapper();
            updateWrapper.set(SmtpPopSettingsEntity::getUseDefault,Integer.valueOf(0));
            updateWrapper.eq(SmtpPopSettingsEntity::getOwnerBy,currentUserId);
            updateWrapper.ne(SmtpPopSettingsEntity::getId,entity.getId());
            smtpPopSettingsService.update(updateWrapper);
        }

        return Result.ok();
    }

    @PostMapping(value = "/defaultUse")
    @ApiOperation(value = "设置默认邮箱" )
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = Result.class)
    })
    public Result<?> defaultUse(Long id) {
        Long currentUserId = LoginUserUtil.getCurrentUserId();
        if (Objects.isNull(currentUserId) || Objects.isNull(id)) {
            return Result.result(null);
        }

        LambdaUpdateWrapper<SmtpPopSettingsEntity> updateWrapper = new LambdaUpdateWrapper();
        updateWrapper.set(SmtpPopSettingsEntity::getUseDefault,Integer.valueOf(0));
        updateWrapper.eq(SmtpPopSettingsEntity::getOwnerBy,currentUserId);
        smtpPopSettingsService.update(updateWrapper);

        updateWrapper = new LambdaUpdateWrapper();
        updateWrapper.eq(SmtpPopSettingsEntity::getId,id);
        updateWrapper.eq(SmtpPopSettingsEntity::getOwnerBy,currentUserId);
        updateWrapper.set(SmtpPopSettingsEntity::getUseDefault,Integer.valueOf(1));
        smtpPopSettingsService.update(updateWrapper);
        /**
         * 需要当前默认邮箱的邮件和未读数
         */
        return Result.ok();
    }


    @PostMapping(value = "/isEnabledDelete")
    @ApiOperation(value = "是否开启删除服务器邮件;0 不开启，1：开启" )
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = SmtpPopSettingsEntity.class)
    })
    public Result<?> setReplyContent(Long id,Integer isEnabled) {
        if (Objects.isNull(id) || Objects.isNull(isEnabled)) {
            return Result.error("参数错误");
        }
        LambdaUpdateWrapper<SmtpPopSettingsEntity> updateWrapper = new LambdaUpdateWrapper();
        updateWrapper.set(SmtpPopSettingsEntity::getIsDeleteMail,isEnabled);
        updateWrapper.eq(SmtpPopSettingsEntity::getId,id);
        smtpPopSettingsService.update(updateWrapper);
        return Result.ok();
    }


    @PostMapping(value = "/personal_mail_account")
    @ApiOperation(value = "获取个人邮箱账户" )
    public Result personalMailAccount() {

        Long currentUserId = LoginUserUtil.getCurrentUserId();
        List<SmtpPopSettingsEntity> emails =  smtpPopSettingsService.getEmailAccount(currentUserId);
        QueryWrapper<EmailsEntity> queryWrapper = new QueryWrapper<EmailsEntity>();
        queryWrapper.select("smtp_pop_id", "COUNT(*) AS email_count");
        queryWrapper.eq("owner_by", currentUserId);
        queryWrapper.eq("folder", EmailBoxEnum.INBOX.code);
        queryWrapper.eq("is_trash", Integer.valueOf(0));
        queryWrapper.eq("is_read", Integer.valueOf(0));
        queryWrapper.eq("is_delete", Integer.valueOf(0));
        queryWrapper.isNotNull("smtp_pop_id");
        queryWrapper.ne("`from`", "system@storlead.com");
        queryWrapper.groupBy("smtp_pop_id");
        List<Map<String,Object>> readMapls = emailsService.listMaps(queryWrapper);
        Map<Long, Integer> readMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(readMapls)) {
            for (Map<String, Object> map : readMapls) {
                Long key = Long.valueOf(map.get("smtp_pop_id").toString());
                Integer val = Integer.valueOf(map.get("email_count").toString());
                readMap.put(key, val);
            }
        }

        List<MailAcountVO> mails = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(emails)) {
            emails.forEach(e -> {
                MailAcountVO mailvo = new MailAcountVO();
                mailvo.setMailAccount(e.getEmailAddress());
                mailvo.setId(e.getId());
                mailvo.setUseDefault(e.getUseDefault());
                Integer readNum = readMap.get(e.getId());
                if (Objects.nonNull(readNum)) {
                    mailvo.setUnReadCount(readNum);
                } else {
                    mailvo.setUnReadCount(0);
                }
                mails.add(mailvo);
            });
        }
        return Result.result(mails);
    }

    @PostMapping(value = "/test_connect")
    @ApiOperation(value = "测试" )
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = SmtpPopSettingsEntity.class)
    })
    public Result<?> receiveMail(@RequestBody SmtpPopSettingsEntity mailSet) {

        if (!testSmtp(mailSet)) {
            return Result.error("邮箱校验失败,请输入正确的账号密码");
        }
        if ("POP3".equals(mailSet.getProtocolType())) {
            if (!testPop3(mailSet)) {
                return Result.error("邮箱校验失败,请输入正确的账号密码");
            }
        }else if("IMAP".equals(mailSet.getProtocolType())) {
            if (!testImap(mailSet)) {
                return Result.error("邮箱校验失败,请输入正确的账号密码");
            }
        } else {
            return Result.error("邮箱校验失败,请输入正确的账号密码");
        }
        return Result.ok();
    }



    public Boolean testImap(SmtpPopSettingsEntity mailSet){
        try {
            MailProperties properties = new MailProperties(mailSet);
            MailConnection mailConnection = MailConnectionUtil.testReceiveEmailsConnection(properties);
            if (Objects.isNull(mailConnection)) {
                return false;
            }
            log.error("mailConnection -- testImap == "+mailConnection);
//            String host = mailSet.getReceiveServer();
//            String port = mailSet.getReceivePort();
//            String username = mailSet.getEmailAddress();
//            String password = mailSet.getEmailPassword();;
//
//            Properties properties = new Properties();
//            properties.put("mail.imap.host", host);
//            properties.put("mail.imap.port", port);
//            properties.put("mail.imap.ssl.enable",Integer.valueOf(1).equals(mailSet.getReceiveSsl()) ? "true" : "false");
//            Session session = Session.getDefaultInstance(properties);
//            Store store = session.getStore("imap");
//            store.connect(username, password);
//            store.close();
//            session = null;
            mailConnection.close();

            return true;
        } catch (Exception e) {
            log.error("testImap - error",e);
            return false;
        }
    }

    public Boolean testPop3(SmtpPopSettingsEntity mailSet){
        try {
            MailProperties properties = new MailProperties(mailSet);
            MailConnection mailConnection = MailConnectionUtil.testReceiveEmailsConnection(properties);
            if (Objects.isNull(mailConnection)) {
                return false;
            }
            log.error("mailConnection -- testPop3 == "+mailConnection);
            mailConnection.close();

            return true;
        } catch (Exception e) {
            log.error("testPop3 - error",e);
            return false;
        }
    }

    public Boolean testSmtp(SmtpPopSettingsEntity smtpPop){
        try {
            Properties properties = new Properties();
            properties.put("mail.smtp.host", smtpPop.getSmtpServer());
            properties.put("mail.smtp.port", smtpPop.getSmtpPort());
            properties.put("mail.smtp.auth", "true");
            properties.put("mail.user", smtpPop.getEmailAddress());
            properties.put("mail.smtp.starttls.enable",Integer.valueOf(1).equals(smtpPop.getSmtpTls()) ? "true" : "false");
            properties.put("mail.smtp.ssl.enable", Integer.valueOf(1).equals(smtpPop.getSmtpSsl()) ? "true" : "false");

            String username = smtpPop.getEmailAddress();
            String password = smtpPop.getEmailPassword();

            Session session = Session.getInstance(properties, new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });
            Transport transport = session.getTransport("smtp");
            transport.connect();
            transport.close();
            return true;
        } catch (Exception e) {
            log.error("testSmtp - error",e);
            return false;
        }
    }

}
