package com.codvision.base.controller.manager;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.codvision.authcore.annotation.RequiresPermissions;
import com.codvision.authcore.bean.SysUserBean;
import com.codvision.authcore.util.AuthUtil;
import com.codvision.base.entity.SysNotice;
import com.codvision.base.entity.SysNoticeUserMapper;
import com.codvision.base.entity.dto.SysNoticeDTO;
import com.codvision.base.entity.vo.SysNoticeVO;
import com.codvision.base.enums.NoticeReadStatusEnum;
import com.codvision.base.service.ISysNoticeService;
import com.codvision.base.service.ISysNoticeUserMapperService;
import com.codvision.commoncore.common.ResponseEntity;
import com.codvision.webapi.api.SysUserApi;
import com.codvision.webapi.bean.RemoteSysUser;
import com.codvision.webcore.bean.QueryPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 系统通知 管理模块
 *
 * @author lingee
 * @date 2023-12-01
 */
@RestController
@RequestMapping("/v1/manager/sysNotice")
@Api(tags = "平台管理端-系统通知模块")
public class ManagerSysNoticeController {

    @Resource
    private ISysNoticeService sysNoticeService;

    @Resource
    private SysUserApi sysUserApi;

    @Resource
    private ISysNoticeUserMapperService sysNoticeUserMapperService;

    @ApiOperation(value = "获取系统通知详情", notes = "获取系统通知详情接口")
    @PostMapping("/detail")
    @RequiresPermissions("sys_notice_detail")
    public ResponseEntity<SysNoticeVO> getDetail(@ApiParam(value = "系统通知ID", required = true) @RequestParam(value = "id") Integer id) {
        SysNoticeVO vo = sysNoticeService.getDetail(id);
        return new ResponseEntity<SysNoticeVO>().ok().data(vo);
    }

    @ApiOperation(value = "获取系统通知分页列表", notes = "获取系统通知分页列表接口")
    @PostMapping("/findAll")
    @RequiresPermissions("sys_notice_list")
    public ResponseEntity<IPage<SysNoticeVO>> findAll(@RequestParam(required = false) String keyword,
                                                      @RequestParam(value = "type", required = false) Integer type,
                                                      @RequestParam(value = "page", required = false, defaultValue = "1") int page,
                                                      @RequestParam(value = "size", required = false, defaultValue = "10") int size) {
        SysNotice queryBean = new SysNotice();
        queryBean.setTitle(keyword);
        queryBean.setType(type);
        IPage<SysNoticeVO> pageResult = sysNoticeService.getPageResult(new QueryPage<>(queryBean, page, size));
        return new ResponseEntity<IPage<SysNoticeVO>>().ok().data(pageResult);
    }

    @ApiOperation(value = "新增系统通知", notes = "新增系统通知接口")
    @PostMapping("/add")
    @RequiresPermissions("sys_notice_add")
    public ResponseEntity<String> saveSysNotice(@Valid @RequestBody SysNoticeDTO sysNoticeDTO) {
        SysUserBean sysUserBean = AuthUtil.getCurrentUser();
        sysNoticeDTO.setCreateUid(Math.toIntExact(sysUserBean.getId()));
        sysNoticeDTO.setCreateBy(sysUserBean.getName());
        sysNoticeService.saveSysNotice(sysNoticeDTO);
        return new ResponseEntity<String>().ok().message("添加成功");
    }

    @ApiOperation(value = "删除系统通知", notes = "删除系统通知接口")
    @PostMapping("/delete")
    @RequiresPermissions("sys_notice_del")
    public ResponseEntity<String> deleteByIds(@RequestBody List<Integer> ids) {
        sysNoticeService.deleteSysNotices(ids);
        return new ResponseEntity<String>().ok().message("删除成功");
    }

    @ApiOperation(value = "编辑系统通知", notes = "编辑系统通知接口")
    @PostMapping("/edit")
    @RequiresPermissions("sys_notice_edit")
    public ResponseEntity<String> editSysNotice(@RequestBody SysNotice sysNotice) {
        sysNoticeService.updateById(sysNotice);
        return new ResponseEntity<String>().ok().message("编辑成功");
    }

    @ApiOperation(value = "通知发送")
    @PostMapping(value = "/send")
    @RequiresPermissions("sys_notice_send")
    public ResponseEntity<String> send(@RequestBody SysNoticeDTO sysNoticeDTO) {
        ResponseEntity<String> responseEntity = new ResponseEntity<>();
        sysNoticeService.send(sysNoticeDTO);
        return responseEntity.ok();
    }

    @ApiOperation(value = "通知撤回")
    @PostMapping(value = "/revoke")
    @RequiresPermissions("sys_notice_revoke")
    public ResponseEntity<String> revoke(@RequestBody SysNoticeDTO sysNoticeDTO) {
        ResponseEntity<String> responseEntity = new ResponseEntity<>();
        sysNoticeService.revoke(sysNoticeDTO);
        return responseEntity.ok();
    }

    @ApiOperation(value = "根据通知id，查询已发送人员列表")
    @PostMapping(value = "/userList")
    @RequiresPermissions("sys_notice_user_list")
    public ResponseEntity<IPage<RemoteSysUser>> getNoticeUserList(@ApiParam(value = "主键id") @RequestParam(value = "id") Integer id,
                                                                  @ApiParam(value = "关键字") @RequestParam(required = false) String keyword,
                                                                  @RequestParam(value = "page", required = false, defaultValue = "1") int page,
                                                                  @RequestParam(value = "size", required = false, defaultValue = "10") int size) {
        ResponseEntity<IPage<RemoteSysUser>> response = new ResponseEntity<>();
        List<SysNoticeUserMapper> list = sysNoticeUserMapperService.list(Wrappers.<SysNoticeUserMapper>lambdaQuery()
                .eq(SysNoticeUserMapper::getNoticeId, id));
        if (CollectionUtil.isNotEmpty(list)) {
            IPage<RemoteSysUser> pageResult = sysUserApi.pageUserList(keyword, null, null,
                    list.stream().map(SysNoticeUserMapper::getUserId).collect(Collectors.toList()), page, size);
            response.data(pageResult);
        }

        return response.ok();
    }

    @ApiOperation(value = "已读通知调用")
    @PostMapping(value = "/updateNoticeUserStatus")
    @RequiresPermissions("sys_notice_read")
    public ResponseEntity<String> updateNoticeUserStatus(@ApiParam(value = "通知id") @RequestParam(value = "noticeId") Integer noticeId) {
        ResponseEntity<String> responseEntity = new ResponseEntity<>();
        SysUserBean sysUser = AuthUtil.getCurrentUser();
        sysNoticeUserMapperService.update(Wrappers.<SysNoticeUserMapper>lambdaUpdate()
                .eq(SysNoticeUserMapper::getNoticeId, noticeId).
                eq(SysNoticeUserMapper::getUserId, sysUser.getId())
                .set(SysNoticeUserMapper::getStatus, NoticeReadStatusEnum.READ.getStatus()));
        return responseEntity.ok();
    }

    @ApiOperation("全部标记已读")
    @PostMapping(value = "/markAllRead")
    public ResponseEntity<String> markAllRead(@RequestParam(value = "type") Integer type) {
        ResponseEntity<String> responseEntity = new ResponseEntity<>();
        SysUserBean sysUser = AuthUtil.getCurrentUser();
        sysNoticeUserMapperService.markAllRead(Math.toIntExact(sysUser.getId()), type);
        return responseEntity.ok();
    }


    @PostMapping("/getListByUid")
    @ApiOperation("获取当前登录用户的通知消息列表")
    @RequiresPermissions("sys_notice_list_uid")
    public ResponseEntity<IPage<SysNoticeVO>> getListByUid(@RequestParam(value = "type") Integer type,
                                                           @RequestParam(value = "page", required = false, defaultValue = "1") int page,
                                                           @RequestParam(value = "size", required = false, defaultValue = "10") int size) {
        ResponseEntity<IPage<SysNoticeVO>> responseEntity = new ResponseEntity<>();

        SysUserBean sysUser = AuthUtil.getCurrentUser();
        QueryPage<SysNotice> queryPage = new QueryPage<>(page, size);
        IPage<SysNoticeVO> pageResult = sysNoticeService.getListByUidAndType(queryPage.getPage(), Math.toIntExact(sysUser.getId()), type);
        return responseEntity.data(pageResult).ok();
    }

    @PostMapping("/flagUnReadNotice")
    @ApiOperation("未读消息列表（登陆触发）")
    public ResponseEntity<Boolean> flagUnReadNotice() {
        ResponseEntity<Boolean> responseEntity = new ResponseEntity<>();
        SysUserBean sysUser = AuthUtil.getCurrentUser();
        return responseEntity.ok().data(sysNoticeService.flagUnReadNotice(Math.toIntExact(sysUser.getId())));
    }
}
