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

import cn.reghao.devops.mgr.admin.db.repository.EmailAccountRepository;
import cn.reghao.devops.mgr.admin.db.repository.NotifyReceiverRepository;
import cn.reghao.devops.mgr.admin.model.po.EmailAccount;
import cn.reghao.devops.mgr.admin.model.po.NotifyReceiver;
import cn.reghao.devops.mgr.admin.model.vo.NotifyType;
import cn.reghao.devops.mgr.admin.service.SysMessageService;
import cn.reghao.jutil.jdk.result.WebResult;
import cn.reghao.jutil.jdk.string.StringRegexp;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author reghao
 * @date 2024-07-30 10:03:22
 */
@Api(tags = "系统消息接口")
@RestController
@RequestMapping("/api/sys")
public class SysMessageController {
    private final SysMessageService sysMessageService;
    private final EmailAccountRepository emailAccountRepository;
    private final NotifyReceiverRepository notifyReceiverRepository;

    public SysMessageController(SysMessageService sysMessageService, EmailAccountRepository emailAccountRepository,
                                NotifyReceiverRepository notifyReceiverRepository) {
        this.sysMessageService = sysMessageService;
        this.emailAccountRepository = emailAccountRepository;
        this.notifyReceiverRepository = notifyReceiverRepository;
    }

    @ApiOperation(value = "清空系统消息", notes = "N")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @PostMapping(value = "/message/clear", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public String clearMessage() {
        sysMessageService.clearUnread();
        return WebResult.success();
    }

    @ApiOperation(value = "添加邮箱帐号", notes = "N")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @PostMapping(value = "/notify/email/save", produces = MediaType.APPLICATION_JSON_VALUE)
    public String saveReceiver(@Validated EmailAccount emailAccount) {
        String email = emailAccount.getUsername();
        boolean matched = StringRegexp.matchEmail(email);
        if (!matched) {
            return WebResult.failWithMsg("邮箱地址格式不正确, 请检查");
        }

        List<EmailAccount> list = emailAccountRepository.findAll();
        if (!list.isEmpty()) {
            EmailAccount emailAccount1 = list.get(0);
            emailAccount1.setSmtp(emailAccount.getSmtp());
            emailAccount1.setUsername(emailAccount.getUsername());
            emailAccount1.setPassword(emailAccount.getPassword());
            emailAccount1.setPersonal(emailAccount.getPersonal());
            emailAccountRepository.save(emailAccount1);
        } else {
            emailAccountRepository.save(emailAccount);
        }

        return WebResult.success();
    }

    @ApiOperation(value = "删除邮箱帐号", notes = "N")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @DeleteMapping(value = "/notify/email/delete/{username}", produces = MediaType.APPLICATION_JSON_VALUE)
    public String deleteEmail(@PathVariable("username") String username) {
        /*NotifyReceiver notifyReceiver = notifyReceiverRepository.findByType(NotifyType.email.name());
        if (notifyReceiver != null) {
            return WebResult.failWithMsg("系统中存在接收通知的邮箱地址, 不能删除发送通知的邮箱");
        }

        List<EmailAccount> list = emailAccountRepository.findAll();
        emailAccountRepository.delete(list.get(0));*/
        return WebResult.failWithMsg("接口未实现");
    }

    @ApiOperation(value = "添加通知接收", notes = "N")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @PostMapping(value = "/notify/receiver/save", produces = MediaType.APPLICATION_JSON_VALUE)
    public String saveReceiver(@Validated NotifyReceiver notifyReceiver) {
        String name = notifyReceiver.getName();
        NotifyReceiver notifyReceiver1 = notifyReceiverRepository.findByName(name);
        if (notifyReceiver1 != null) {
            String errMsg = String.format("NotifyReceiver %s exist", name);
            return WebResult.failWithMsg(errMsg);
        }

        /*String type = notifyReceiver.getType();
        NotifyReceiver notifyReceiver1 = notifyReceiverRepository.findByType(type);
        if (notifyReceiver1 != null) {
            String errMsg = String.format("NotifyType %s already exist", type);
            return WebResult.failWithMsg(errMsg);
        }*/
        String type = notifyReceiver.getType();
        if (type.equals(NotifyType.email.name())) {
            List<EmailAccount> list = emailAccountRepository.findAll();
            if (list.isEmpty()) {
                return WebResult.failWithMsg("没有可以发送通知的邮箱, 请先配置");
            }

            String email = notifyReceiver.getUrl();
            boolean matched = StringRegexp.matchEmail(email);
            if (!matched) {
                return WebResult.failWithMsg("邮箱地址格式不正确, 请检查");
            }
        }

        notifyReceiverRepository.save(notifyReceiver);
        return WebResult.success();
    }

    @ApiOperation(value = "更新通知接收", notes = "N")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @PostMapping(value = "/notify/receiver/edit", produces = MediaType.APPLICATION_JSON_VALUE)
    public String editReceiver(@Validated NotifyReceiver notifyReceiver) {
        String name = notifyReceiver.getName();
        NotifyReceiver notifyReceiver1 = notifyReceiverRepository.findByName(name);
        if (notifyReceiver1 == null) {
            String errMsg = String.format("NotifyReceiver %s not exist", name);
            return WebResult.failWithMsg(errMsg);
        }

        notifyReceiver1.setUrl(notifyReceiver.getUrl());
        notifyReceiverRepository.save(notifyReceiver1);
        return WebResult.success();
    }

    @ApiOperation(value = "更新通知接收", notes = "N")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @PostMapping(value = "/notify/receiver/default/{name}", produces = MediaType.APPLICATION_JSON_VALUE)
    public String updateDefaultReceiver(@PathVariable("name") String name) {
        NotifyReceiver notifyReceiver1 = notifyReceiverRepository.findByName(name);
        if (notifyReceiver1 == null || notifyReceiver1.getSetdefault()) {
            String errMsg = String.format("NotifyReceiver %s not exist or it is default receiver", name);
            return WebResult.failWithMsg(errMsg);
        }

        NotifyReceiver notifyReceiver2 = notifyReceiverRepository.findByTypeAndSetdefaultIsTrue(notifyReceiver1.getType());
        notifyReceiver1.setSetdefault(true);
        notifyReceiver2.setSetdefault(false);
        notifyReceiverRepository.saveAll(List.of(notifyReceiver1, notifyReceiver2));
        return WebResult.success();
    }

    @ApiOperation(value = "删除通知接收", notes = "N")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @DeleteMapping(value = "/notify/receiver/delete/{name}", produces = MediaType.APPLICATION_JSON_VALUE)
    public String deleteReceiver(@PathVariable("name") String name) {
        NotifyReceiver notifyReceiver = notifyReceiverRepository.findByName(name);
        if (notifyReceiver != null) {
            notifyReceiverRepository.delete(notifyReceiver);
        }

        return WebResult.success();
    }
}
