package com.storlead.mail.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.util.LoginUserUtil;
import com.storlead.framework.common.result.Result;
import com.storlead.mail.pojo.entity.MailboxAutoReplySetEntity;
import com.storlead.mail.pojo.entity.SmtpPopSettingsEntity;
import com.storlead.mail.pojo.dto.EmailTemplatesDTO;
import com.storlead.mail.service.MailboxAutoReplySetService;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 邮箱自动回复内容 前端控制器
 * </p>
 *
 * @author chenkq
 * @since 2025-02-24
 */
@RestController
@RequestMapping("/mail/mailbox/reply")
@Api(tags = "邮件: 邮件管理")
@Log4j2
public class MailboxAutoReplySetController {

    @Resource
    private MailboxAutoReplySetService replySetService;

    @Resource
    private SmtpPopSettingsService popSettingsService;

    @PostMapping(value = "/page_list")
    @ApiOperation(value = "获取邮件自动回复配置" )
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = MailboxAutoReplySetEntity.class)
    })
    public Result<?> pageList(EmailTemplatesDTO dto) {

        Long currentUserId = LoginUserUtil.getCurrentUserId();
        Page<MailboxAutoReplySetEntity> page = new Page<>(dto.getPageIndex(),dto.getPageSize());
        LambdaQueryWrapper<MailboxAutoReplySetEntity> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(MailboxAutoReplySetEntity::getOwnerBy,currentUserId);
        queryWrapper.eq(MailboxAutoReplySetEntity::getIsDelete,Integer.valueOf(0));
        IPage<MailboxAutoReplySetEntity> pageList = replySetService.page(page,queryWrapper);
        if (!CollectionUtils.isEmpty(pageList.getRecords())) {
            List<Long> popIds = pageList.getRecords().stream().map(MailboxAutoReplySetEntity::getSmtpPopId).collect(Collectors.toList());
            List<SmtpPopSettingsEntity> smtpPopSettings = popSettingsService.list(new LambdaQueryWrapper<SmtpPopSettingsEntity>().in(SmtpPopSettingsEntity::getId, popIds));
            if (!CollectionUtils.isEmpty(smtpPopSettings)) {
                Map<Long,String> smtpPopMap =  smtpPopSettings.stream().collect(Collectors.toMap(SmtpPopSettingsEntity::getId,SmtpPopSettingsEntity::getEmailAddress, (existing, replacement) -> existing));
                pageList.getRecords().forEach(e -> {
                    e.setMailAddress(smtpPopMap.get(e.getSmtpPopId()));
                });
            }
        }
        return Result.result(pageList);
    }

    @PostMapping(value = "/list")
    @ApiOperation(value = "获取邮件模板" )
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = MailboxAutoReplySetEntity.class)
    })
    public Result<?> list(EmailTemplatesDTO dto) {

        Long currentUserId = LoginUserUtil.getCurrentUserId();
        Page<MailboxAutoReplySetEntity> page = new Page<>(dto.getPageIndex(),dto.getPageSize());
        LambdaQueryWrapper<MailboxAutoReplySetEntity> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(MailboxAutoReplySetEntity::getOwnerBy,currentUserId);
        queryWrapper.eq(MailboxAutoReplySetEntity::getIsDelete,Integer.valueOf(0));
        queryWrapper.eq(MailboxAutoReplySetEntity::getEnabled,dto.getEnabled());
        IPage<MailboxAutoReplySetEntity> pageList = replySetService.page(page,queryWrapper);
        if (!CollectionUtils.isEmpty(pageList.getRecords())) {
           List<Long> popIds = pageList.getRecords().stream().map(MailboxAutoReplySetEntity::getSmtpPopId).collect(Collectors.toList());
           List<SmtpPopSettingsEntity> smtpPopSettings = popSettingsService.list(new LambdaQueryWrapper<SmtpPopSettingsEntity>().in(SmtpPopSettingsEntity::getId, popIds));
           if (!CollectionUtils.isEmpty(smtpPopSettings)) {
              Map<Long,String> smtpPopMap =  smtpPopSettings.stream().collect(Collectors.toMap(SmtpPopSettingsEntity::getId,SmtpPopSettingsEntity::getEmailAddress, (existing, replacement) -> existing));
               pageList.getRecords().forEach(e -> {
                   e.setMailAddress(smtpPopMap.get(e.getSmtpPopId()));
               });
           }
        }
        return Result.result(pageList);
    }

    @PostMapping(value = "/save")
    @ApiOperation(value = "保存" )
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = MailboxAutoReplySetEntity.class)
    })
    public Result<?> save(MailboxAutoReplySetEntity entity) {
        replySetService.saveOrUpdate(entity);
        return Result.ok();
    }

    @ApiOperation(value = "删除")
    @PostMapping("deleteIds")
    public Result delete(Long [] ids) {
        if(Objects.isNull(ids)) {
            return Result.error("参数错误");
        }
        replySetService.lgDelete(Arrays.asList(ids));
        return Result.ok();
    }


    @ApiOperation("禁用或启用")
    @PostMapping("enabled")
    public Result enabled(Long id,Boolean enable) {
        LambdaUpdateWrapper<MailboxAutoReplySetEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(MailboxAutoReplySetEntity::getEnabled,enable);
        updateWrapper.eq(MailboxAutoReplySetEntity::getId,id);
        replySetService.update(updateWrapper);
        return Result.ok();
    }

}
