package cn.reghao.devops.mgr.admin.controller.page;

import cn.reghao.devops.mgr.admin.db.repository.EmailAccountRepository;
import cn.reghao.devops.mgr.admin.model.po.EmailAccount;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author reghao
 * @date 2024-01-26 20:52:54
 */
@Api(tags = "邮件帐号管理页面")
@Controller
@RequestMapping("/sys/notify/email")
public class EmailPageController {
    private final EmailAccountRepository emailAccountRepository;

    public EmailPageController(EmailAccountRepository emailAccountRepository) {
        this.emailAccountRepository = emailAccountRepository;
    }

    @ApiOperation(value = "邮箱帐号列表页面", notes = "N")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @GetMapping("")
    public String emailIndex(Model model) {
        PageRequest pageRequest = PageRequest.of(0, 100);
        Page<EmailAccount> page = emailAccountRepository.findAll(pageRequest);
        page.getContent().forEach(emailAccount -> {
            emailAccount.setPassword("******");
        });

        model.addAttribute("page", page);
        model.addAttribute("list", page.getContent());
        return "/admin/notify/email";
    }

    @ApiOperation(value = "添加邮箱帐号页面", notes = "N")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @GetMapping("/add")
    public String emailAdd(Model model) {
        return "/admin/notify/emailadd";
    }

    @ApiOperation(value = "更新邮箱帐号页面", notes = "N")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @GetMapping("/edit/{username}")
    public String emailEdit(@PathVariable("username") String username, Model model) throws Exception {
        List<EmailAccount> list = emailAccountRepository.findAll();
        model.addAttribute("emailAccount", list.get(0));
        return "/admin/notify/emailadd";
    }
}
