package com.simuwang.manage.api.email;

import com.simuwang.base.common.page.TableDataInfo;
import com.simuwang.base.common.result.AjaxResult;
import com.simuwang.base.pojo.vo.MailboxInfoTableVO;
import com.simuwang.base.pojo.vo.MailboxInfoVO;
import com.simuwang.manage.api.base.BaseController;
import com.simuwang.manage.service.EmailConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * FileName: EmailConfigController
 * Author:   chenjianhua
 * Date:     2024/9/9 11:40
 * Description: ${DESCRIPTION}
 */
@RestController
@RequestMapping("/email")
public class EmailConfigController extends BaseController {

    @Autowired
    private EmailConfigService emailConfigService;
    private static final Logger logger = LoggerFactory.getLogger(EmailConfigController.class);

    /**
     * 表格查询
     * @param email
     * @return
     */
    @RequestMapping("search-email-list")
    public TableDataInfo searchEmailConfigList(@RequestParam(value = "email",required = false)String email){
        List<MailboxInfoTableVO> result = emailConfigService.searchEmailConfigList(email);
        return getDataTable(result);
    }
    /**
     * 保存邮箱配置
     * @param mailboxInfoVO
     * @return
     */
    @RequestMapping("save-email-config")
    public AjaxResult saveEmailConfig(@RequestBody MailboxInfoVO mailboxInfoVO){
        try{
            if(mailboxInfoVO.getId() == null && emailConfigService.checkEmailUnique(mailboxInfoVO.getEmail())){
                return AjaxResult.error("邮箱地址已存在，无需添加");
            }
            emailConfigService.saveEmailConfig(mailboxInfoVO);
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            return AjaxResult.error("保存失败");
        }
        return AjaxResult.success();
    }

    /**
     * 保存邮箱配置
     * @param ids
     * @return
     */
    @RequestMapping("delete-email-config")
    public AjaxResult deleteEmailConfig(String ids){
        try{
            emailConfigService.deleteEmailConfig(ids);
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            return AjaxResult.error();
        }
        return AjaxResult.success();
    }

    @RequestMapping("connect-test")
    public AjaxResult connectTest(@RequestBody MailboxInfoVO mailboxInfoVO){
        String msg = "";
        try{
            msg = emailConfigService.connectTest(mailboxInfoVO);
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            return AjaxResult.error("链接失败");
        }
        return AjaxResult.success(msg);
    }
}
