package com.zcxk.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zcxk.common.EasyExcelUtil;
import com.zcxk.dto.LoginLogDto;
import com.zcxk.entity.LoginLogEntity;
import com.zcxk.model.AjaxMessage;
import com.zcxk.model.LoginUser;
import com.zcxk.model.Pagination;
import com.zcxk.model.ResultStatus;
import com.zcxk.service.LoginLogService;
import com.zcxk.util.UserUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description 登录日志管理控制层
 * @auto wangli
 * @data 2020-10-27 9:19
 */
@RestController
@RequestMapping("/loginLog")
@Api(tags = "登录日志管理")
@Slf4j
public class LoginLogController {

    @Autowired
    private LoginLogService loginLogService;
    @Value("${UMIS.sys_excel_path}")
    private String baseDir;

    /**
     * 通过主键查询单条数据
     *
     * @param id
     * @return 单条数据
     */
    @RequestMapping(value = "get", method = RequestMethod.POST)
    @ApiOperation(value = "根据id查询登录日志")
    public AjaxMessage<LoginLogDto> selectOne(
            @ApiParam(value = "登录日志信息", required = true) @RequestParam Long id) {
        LoginLogDto result = loginLogService.selectById(id);

        return new AjaxMessage<>(ResultStatus.OK, result);
    }

    /**
     * 查询登录日志信息
     *
     * @param loginLogDto 参数对象
     * @return 多条数据
     */
    @RequestMapping(value = "selectList", method = RequestMethod.POST)
    @ApiOperation(value = "查询登录日志信息")
    public AjaxMessage<List<LoginLogDto>> selectList(
            @ApiParam(value = "登录日志信息", required = true) @RequestBody LoginLogDto loginLogDto) {
        List<LoginLogDto> result = loginLogService.selectList(loginLogDto);

        return new AjaxMessage<>(ResultStatus.OK, result);
    }


    /**
     * 新增一条数据
     *
     * @param loginLogEntity 实体类
     * @return Response对象
     */
    @RequestMapping(value = "insert", method = RequestMethod.POST)
    @ApiOperation(value = "插入登录日志信息")
    public AjaxMessage<Integer> insert(@ApiParam(value = "登录日志信息", required = true) @RequestBody LoginLogEntity loginLogEntity) {
        int result = loginLogService.insert(loginLogEntity);

        return new AjaxMessage<>(ResultStatus.OK, result);
    }

    /**
     * 修改一条数据
     *
     * @param loginLogEntity 实体类
     * @return Response对象
     */
    @RequestMapping(value = "update", method = RequestMethod.POST)
    @ApiOperation(value = "修改登录日志信息")
    public AjaxMessage<Integer> update(@ApiParam(value = "登录日志信息", required = true) @RequestBody LoginLogEntity loginLogEntity) {
        int result = loginLogService.update(loginLogEntity);
        return new AjaxMessage<>(ResultStatus.OK, result);

    }

    /**
     * 单条删除数据
     *
     * @param id
     * @return Response对象
     */
    @RequestMapping(value = "delete", method = RequestMethod.POST)
    @ApiOperation(value = "删除登录日志信息")
    public AjaxMessage<Integer> delete(@ApiParam(value = "登录日志信息", required = true) @RequestParam Long id) {
        int result = loginLogService.deleteById(id);
        return new AjaxMessage<>(ResultStatus.OK, result);
    }


    /**
     * 分页查询
     *
     * @return Response对象
     */
    @RequestMapping(value = "selectPage", method = RequestMethod.POST)
    @ApiOperation(value = "查询登录日志信息列表")
    public AjaxMessage<Pagination<LoginLogDto>> selectPage(

            @ApiParam(value = "查询条件（用户名/手机号）") @RequestParam(required = false) String condition,
            @ApiParam(value = "部门id") @RequestParam(required = false) Long departmentId,
            @ApiParam(value = "开始时间yyyy-MM-dd") @RequestParam(required = false) String beginTime,
            @ApiParam(value = "结束时间yyyy-MM-dd") @RequestParam(required = false) String endTime,
            @ApiParam(value = "页数,非必传，默认第一页",  defaultValue = "1") @RequestParam(required = false, defaultValue = "1") Integer pageNum,
            @ApiParam(value = "条数，非必传，默认10条",  defaultValue = "10") @RequestParam(required = false, defaultValue = "10") Integer pageSize



    ) {
        LoginUser loginUser = UserUtil.getCurrentUser();
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        LoginLogDto loginLogDto = new LoginLogDto();
        loginLogDto.setTenantId(loginUser.getTenantId());
        loginLogDto.setCondition(condition);
        loginLogDto.setDepartmentId(departmentId);
        loginLogDto.setPermissonType(loginUser.getPermissonType());
        //系统管理员不过滤权限，机构信息为null的去掉
        if((!loginUser.getType().equals("-9999")) && !loginUser.getType().equals("-999")   ){
            loginLogDto.setProgramItems(loginUser.getProgramItemList().stream().filter(p -> p.getOrgId() != null).collect(Collectors.toList()));
        }

        try {
            if(StringUtils.isNotBlank(beginTime)){
                loginLogDto.setBeginTime(f.parse(beginTime));
            }
            if(StringUtils.isNotBlank(endTime)){
                loginLogDto.setEndTime(f.parse(endTime));
            }
        }catch (ParseException e){
            log.error("登录日志查询时间转换错误，原数据：beginTime：{}，endTime：{}，异常信息：{}",beginTime,endTime,e.getMessage());
            loginLogDto.setBeginTime(new Date());
            loginLogDto.setEndTime(new Date());
        }

        IPage<LoginLogDto> iPage = new Page<>(pageNum, pageSize);
        if(iPage.orders().size() == 0){
            OrderItem orderItem =new OrderItem();
            orderItem.setAsc(false);
            orderItem.setColumn("a.create_time");
            iPage.orders().add(orderItem);
        }

        iPage = loginLogService.selectPage(iPage, loginLogDto);

        Pagination<LoginLogDto> pages = new Pagination<>(iPage);

        return new AjaxMessage<>(ResultStatus.OK, pages);
    }

    @RequestMapping(value = "/exportExcel", method = RequestMethod.POST)
    @ApiOperation(value = "登录日志导出")
    public AjaxMessage<String> exportExcel(@ApiParam(value = "日志IDS", required = true) @RequestParam Long[] ids) {
        List<LoginLogDto> result = loginLogService.selectListByIds(ids);
        String filePath = EasyExcelUtil.excelWrite(baseDir, LoginLogDto.class, "登录日志", result);
        return new AjaxMessage<>(ResultStatus.OK, filePath);
    }
}
