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

import cn.reghao.devops.mgr.admin.db.repository.WebhookRepository;
import cn.reghao.devops.mgr.admin.model.po.Webhook;
import cn.reghao.devops.mgr.admin.model.po.SysMessage;
import cn.reghao.devops.mgr.admin.model.vo.SysMsg;
import cn.reghao.devops.mgr.admin.service.SysMessageService;
import cn.reghao.jutil.web.WebResult;
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.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author reghao
 * @date 2021-04-04 21:24:18
 */
@Api(tags = "系统页面和接口")
@Controller
@RequestMapping("/sys")
public class SysPageController {
    private final WebhookRepository webhookRepository;
    private final SysMessageService sysMessageService;

    public SysPageController(WebhookRepository webhookRepository, SysMessageService sysMessageService) {
        this.webhookRepository = webhookRepository;
        this.sysMessageService = sysMessageService;
    }

    @ApiOperation(value = "系统运行日志页面", notes = "N")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @GetMapping("/log")
    public String runtimeLogPage() {
        return "/admin/log/rtlog";
    }

    @ApiOperation(value = "系统消息页面", notes = "N")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @GetMapping("/message")
    public String messagePage(Model model) {
        Page<SysMsg> page = sysMessageService.getSysMessages();
        model.addAttribute("list", page.getContent());
        return "/admin/msg/sysmsg";
    }

    @ApiOperation(value = "系统消息内容", notes = "N")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @GetMapping("/message/detail/{id}")
    public String messageDetail(@PathVariable("id") int id, Model model) {
        String content = "";
        SysMessage sysMessage = sysMessageService.getSysMessage(id);
        if (sysMessage != null) {
            content = sysMessage.getContent();
        }

        model.addAttribute("content", content);
        return "/admin/msg/sysmsgdetail";
    }

    @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')")
    @GetMapping("/notify")
    public String receiverIndex(Model model) {
        PageRequest pageRequest = PageRequest.of(0, 100);
        Page<Webhook> page = webhookRepository.findAll(pageRequest);
        model.addAttribute("page", page);
        model.addAttribute("list", page.getContent());
        return "/admin/notify/receiver";
    }

    @ApiOperation(value = "添加 webhook 页面", notes = "N")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @GetMapping("/notify/add")
    public String receiverAdd() {
        return "/admin/notify/receiveradd";
    }

    @ApiOperation(value = "添加 webhook", notes = "N")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @PostMapping(value = "/notify/save", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public String saveReceiver(@Validated Webhook webhook) {
        String name = webhook.getName();
        Webhook webhook1 = webhookRepository.findByName(name);
        if (webhook1 != null) {
            String errMsg = String.format("Webhook %s exist", name);
            return WebResult.failWithMsg(errMsg);
        }

        webhookRepository.save(webhook);
        return WebResult.success();
    }

    @ApiOperation(value = "设置默认 webhook", notes = "N")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @PostMapping(value = "/notify/default/{name}", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public String updateDefaultReceiver(@PathVariable("name") String name) {
        Webhook webhook1 = webhookRepository.findByName(name);
        if (webhook1 == null || webhook1.getSetdefault()) {
            String errMsg = String.format("Webhook %s not exist or it is default receiver", name);
            return WebResult.failWithMsg(errMsg);
        }

        Webhook webhook2 = webhookRepository.findByTypeAndSetdefaultIsTrue(webhook1.getType());
        webhook1.setSetdefault(true);
        webhook2.setSetdefault(false);
        webhookRepository.saveAll(List.of(webhook1, webhook2));
        return WebResult.success();
    }
}
