package com.sw.mes.auth.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sw.mes.auth.domain.SysLoginLog;
import com.sw.mes.auth.service.SysLoginLogService;
import com.sw.mes.core.dto.auth.LoginLogDto;
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.*;
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.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

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


/**
 * @Author
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@RestController
@RequestMapping("/LoginLog")
@Slf4j
@Api(description = "登录日志接口")
public class LoginLogController {
    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private SysLoginLogService sysLoginLogService;

    @ApiOperation(value = "分页查询登录日志列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_deviceCode", value = "设备编号", dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "search_GTE_createTime", value = "开始时间", dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "search_LTE_createTime", value = "结束时间", dataType = "String", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<LoginLogDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        LambdaQueryWrapper<SysLoginLog> queryWrapper = new LambdaQueryWrapper<>();
        if (request.getParameter("search_EQ_deviceCode")!=null){
            queryWrapper.eq(SysLoginLog::getDeviceCode,request.getParameter("search_EQ_deviceCode"));
        }
        if (request.getParameter("search_GTE_createTime")!=null){
            queryWrapper.gt(SysLoginLog::getCreateTime,request.getParameter("search_GTE_createTime"));
        }
        if (request.getParameter("search_LTE_createTime")!=null){
            queryWrapper.lt(SysLoginLog::getCreateTime,request.getParameter("search_LTE_createTime"));
        }
       Page<SysLoginLog> listPage = sysLoginLogService.page(new Page<>(requestPage.getPage(), requestPage.getRows()), queryWrapper);

        List<LoginLogDto> dtos = listPage.getRecords().stream()
                .map(entity -> toLazyDto(entity))
                .collect(Collectors.toList());
        ResponsePage responsePage = new ResponsePage(dtos,listPage.getTotal());
        return ResultGenerator.success(responsePage);
    }

    @ApiOperation(value = "获取所有登录日志")
    @GetMapping("/listAll")
    public Result<List<LoginLogDto>> listAll(ServletRequest request) {
        List<SysLoginLog> list = sysLoginLogService.list();
        List<LoginLogDto> loginLogDtos = list.stream()
                .map(loginLog -> toLazyDto(loginLog))
                .collect(Collectors.toList());
        return ResultGenerator.success(loginLogDtos);
    }

    @ApiOperation(value = "登录日志详细信息")
    @GetMapping("/{id}")
    public Result<LoginLogDto> get(@PathVariable @ApiParam(value = "登录日志id") Integer id) {
        SysLoginLog loginLog = sysLoginLogService.getById(id);
        if (null == loginLog) {
            return ResultGenerator.fail("该登录日志不存在");
        }
        return ResultGenerator.success(toEagerDto(loginLog));
    }

    @ApiOperation(value = "创建登录日志")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "登录日志对象") LoginLogDto loginLogDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        SysLoginLog loginLog = fromDto(loginLogDto);
        sysLoginLogService.saveOrUpdate(loginLog);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "更新登录日志")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "登录日志") LoginLogDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        if (dto.getId() == null)
            return ResultGenerator.fail("id不能为空");
        SysLoginLog entity = sysLoginLogService.getById(dto.getId());
        if (entity == null) {
            return ResultGenerator.fail("原信息不存在");
        }
        try {
            SysLoginLog entityfromFto = fromDto(dto);
            BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
            sysLoginLogService.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 Integer[] ids) {
        for (Integer id : ids) {
            sysLoginLogService.removeById(id);
        }
        return ResultGenerator.success();
    }

    public LoginLogDto toLazyDto(SysLoginLog entity) {
        return modelMapper.map(entity, LoginLogDto.class);
    }

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

    public SysLoginLog fromDto(LoginLogDto dto) {
        return modelMapper.map(dto, SysLoginLog.class);
    }


}
