package com.sw.mes.auth.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sw.mes.auth.domain.SysNotice;
import com.sw.mes.auth.service.SysNoticeService;
import com.sw.mes.core.context.BaseContextHandler;
import com.sw.mes.core.dto.auth.SysNoticeDto;
import com.sw.mes.core.entity.SearchFilter;
import com.sw.mes.core.response.ResponsePage;
import com.sw.mes.core.response.Result;
import com.sw.mes.core.response.ResultGenerator;
import com.sw.mes.core.utils.BeanUtil;

import com.sw.mes.core.utils.DynmaicQueryWrapper;
import com.sw.mes.core.utils.RequestPage;
import com.sw.mes.core.utils.StringUtils;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletRequest;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @Author
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@RestController
@RequestMapping("/notice")
@Slf4j
@Api(description = "系统公告接口")
public class NoticeController {
    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private SysNoticeService sysNoticeService;



    @ApiOperation(value = "分页查询系统公告列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "type", value = "类型（0：查询所有，1：查询自己发布的）", dataType = "integer", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<SysNoticeDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        String type = request.getParameter("type");
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<SysNotice> listPage = new Page<>();
        if (StringUtils.isBlank(type) || "0".equals(type)) {
            LambdaQueryWrapper<SysNotice> queryWrapper = new LambdaQueryWrapper<>();
            listPage = sysNoticeService.page(new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(requestPage.getPage(), requestPage.getRows()), queryWrapper);
        } else {
            QueryWrapper<SysNotice> sysNoticeQueryWrapper = DynmaicQueryWrapper.searchFilter(request, SysNotice.class);
            sysNoticeQueryWrapper.eq("user_id_create", BaseContextHandler.getUserID());
            listPage = sysNoticeService.page(new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(requestPage.getPage(), requestPage.getRows()), sysNoticeQueryWrapper);
        }
        List<SysNoticeDto> dtos = listPage.getRecords().stream()
                .map(this::toLazyDto)
                .collect(Collectors.toList());
        ResponsePage<SysNoticeDto> responsePage = new ResponsePage(dtos, listPage.getTotal());
        return ResultGenerator.success(responsePage);
    }

    @ApiOperation(value = "获取所有系统公告")
    @GetMapping("/listAll")
    public Result<List<SysNoticeDto>> listAll(ServletRequest request) {
        List<SysNotice> users = sysNoticeService.list();
        List<SysNoticeDto> userDtos = users.stream()
                .map(user -> toLazyDto(user))
                .collect(Collectors.toList());
        return ResultGenerator.success(userDtos);

    }

    @ApiOperation(value = "系统公告详细信息")
    @GetMapping("/{id}")
    public Result<SysNoticeDto> get(@PathVariable @ApiParam(value = "系统公告id") Long id) {
        SysNotice notice = sysNoticeService.getById(id);
        if (null == notice)
            return ResultGenerator.fail("该系统公告不存在");
        return ResultGenerator.success(toEagerDto(notice));
    }

    @ApiOperation(value = "创建系统公告")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "系统公告对象") SysNoticeDto noticeDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        SysNotice notice = fromDto(noticeDto);
        notice.setUserCreate(BaseContextHandler.getUsername());
        notice.setGmtCreate(new Date());
        notice.setUserIdCreate(BaseContextHandler.getUserID().longValue());
        sysNoticeService.saveOrUpdate(notice);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "更新系统公告")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "系统公告") SysNoticeDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        if (dto.getId() == null)
            return ResultGenerator.fail("id不能为空");
        SysNotice entity = sysNoticeService.getById(dto.getId());
        if (entity == null)
            return ResultGenerator.fail("原信息不存在");
        try {
            SysNotice entityfromFto = fromDto(dto);
            BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
            entity.setUserCreate(BaseContextHandler.getUsername());
            entity.setGmtCreate(new Date());
            entity.setUserIdCreate(BaseContextHandler.getUserID().longValue());
            sysNoticeService.saveOrUpdate(entity);
            return ResultGenerator.success();
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "删除系统公告")
    @PostMapping("/delete")
    public Result remove(@ApiParam(value = "id集合,逗号分隔,如2,4", type = "query") @RequestParam Long[] ids) {
        for (Long id : ids) {
            sysNoticeService.removeById(id);
        }
        return ResultGenerator.success();
    }

    public SysNoticeDto toLazyDto(SysNotice entity) {
        return modelMapper.map(entity, SysNoticeDto.class);
    }

    public SysNoticeDto toEagerDto(SysNotice entity) {
        SysNoticeDto dto = modelMapper.map(entity, SysNoticeDto.class);
        return dto;
    }

    public SysNotice fromDto(SysNoticeDto dto) {
        return modelMapper.map(dto, SysNotice.class);
    }


}
