/*
 * Author: wangjian
 * 生成controller
 */
package com.tofly.base.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tofly.api.CodeClient;
import com.tofly.base.em.Constant;
import com.tofly.base.entity.Log;
import com.tofly.base.entity.User;
import com.tofly.base.service.LogService;
import com.tofly.base.service.UserService;
import com.tofly.base.util.DateTimeUtil;
import com.tofly.base.vo.CountLogVo;
import com.tofly.base.vo.OperationRecordsVo;
import com.tofly.common.core.constant.CommonConstants;
import com.tofly.common.core.entity.ResultRespone;
import com.tofly.common.core.util.StringUtil;
import com.tofly.common.log.annotation.ToFlyAppLog;
import com.tofly.common.oauth.auth.innerCall;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 日志信息表
 *
 * @author admin
 * @date Thu Oct 10 00:00:00 CST 2019
 */
@RestController
@RequestMapping("/log")
@Api(tags = "日志管理")
@Slf4j
public class LogController {
    private static final Logger logs = org.slf4j.LoggerFactory.getLogger(LogController.class);

    @Autowired
    private LogService logService;
    @Autowired
    private CodeClient codeClient;

    @Autowired
    private UserService userService;
//    @Autowired
//    private BaseEsLogService baseEsLogService;

    @Value("${isUseEs:false}")
    private boolean isUseEs;

    /**
     * 分页查询
     *
     * @param page 分页对象
     * @param log  日志信息表
     * @return
     */
    @GetMapping("/page")
    @ApiOperation(value = "分页查询")
    public ResultRespone getLogPage(Page page, @ModelAttribute Log log) {

        return ResultRespone.success(logService.page(page, Wrappers.query(log)));
    }

    /**
     * 分页查询
     *
     * @param page 分页对象
     * @return
     */
    @GetMapping("/pageNew")
    @ApiOperation(value = "分页查询-新")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deptId", value = "部门id", required = false, dataType = "String"),
            @ApiImplicitParam(name = "userIds", value = "用户id多个以,分隔", required = false, dataType = "String"),
            @ApiImplicitParam(name = "type", value = "类型", required = false, dataType = "String"),
            @ApiImplicitParam(name = "startDate", value = "开始日期", required = false, dataType = "String"),
            @ApiImplicitParam(name = "endDate", value = "结束日期", required = false, dataType = "String")
    })
    @ToFlyAppLog(title = "通过分页查询日志信息")
    public ResultRespone getLogPageNew(Page page, String deptId, String userIds, String type, String startDate, String endDate) {

        System.out.println(isUseEs);
        // 部门id不为空获取当前部门下所有用户登录名列表
        Map map = new HashMap(12);

        if (!StringUtils.isEmpty(deptId)) {
            List<String> collect = userService.getDepartmentUsersByIds(Long.valueOf(deptId)).stream().map(User::getUsername).collect(Collectors.toList());
                map.put("users",collect );

        }
        if (!StringUtils.isEmpty(userIds)) {
            List<Long> ids = Arrays.stream(userIds.split(Constant.CSV)).map(s -> Long.parseLong(s.trim()))
                    .collect(Collectors.toList());
            List<String> collect = userService.list(new QueryWrapper<User>().lambda().in(User::getId, ids)).stream().map(User::getUsername).collect(Collectors.toList());
            map.put("users",collect);
        }
        if (!StringUtils.isEmpty(type)) {
            map.put("type", type);
        }


        map.put("startDate", StringUtil.isEmpty(startDate) ? null : startDate + " 00:00:00");
        map.put("endDate", StringUtil.isEmpty(endDate) ? null : endDate + " 23:59:59");
//        if(isUseEs){
//            log.info("开启了es，日志查询从es");
//            Log log=new Log();
//            log.setType(type);
////            Map map1=new HashMap();
////            map1.put("page",page);
////            map1.put("logMap",map);
//            map.put("size",page.getSize());
//            map.put("page",page.getCurrent());
//            List list=baseEsLogService.queryLog(map);
//            page.setRecords(list);
//            return ResultRespone.success(page);
//        }
        return ResultRespone.success(logService.listLogPage(page, map));
//        return ResultRespone.success(logService.page(page, Wrappers.<Log>lambdaQuery()
//                .eq(!StringUtil.isEmpty(type),Log::getType, type)
//                //.ge(!StringUtil.isEmpty(startDate),Log::getCreateTime, Timestamp.valueOf(startDate+" 00:00:00"))
//                .ge(!StringUtil.isEmpty(startDate),Log::getCreateTime, !StringUtil.isEmpty(startDate)?DateUtil.getDateFormat(startDate):null)
//                .le(!StringUtil.isEmpty(endDate),Log::getCreateTime, !StringUtil.isEmpty(endDate)?Timestamp.valueOf(endDate+" 23:59:59"):null)
//        ));
    }


    /**
     * 通过id查询日志信息表
     *
     * @param id id
     * @return ResultRespone
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "通过ID查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Long")
    })
    @ToFlyAppLog(title = "通过id查询日志信息表")
    public ResultRespone getById(@PathVariable("id") Long id) {
        return ResultRespone.success(logService.getById(id));
    }

    /**
     * 新增日志信息表
     *
     * @param log 日志信息表
     * @return ResultRespone
     */
    //@ToFlyAppLog(title="新增日志信息表"
    //@ApiOperation(value = "新增日志信息表")
    @innerCall
    @PostMapping("/add")
    public ResultRespone save(@RequestBody Log log) {
//        if(isUseEs){
//            System.out.println("开启了es，日志存储到es");
//            return ResultRespone.success(baseEsLogService.saveLog(log));
//        }
        // 判断当前异常字段是否有值,若有值修改日志类型为0
        if(!StringUtils.isEmpty(log.getException())){
            log.setType(CommonConstants.LOG_EXCEPTION);
        }
        // 判断title是否为 content:注销登出 则修改日志类型为2
        if("content:注销登出".equals(log.getTitle())){
            log.setType(CommonConstants.LOG_LOGIN);
        }
        return ResultRespone.success(logService.save(log));
    }

    /**
     * 新增日志信息表
     *
     * @param log 日志信息表
     * @return ResultRespone
     */
    //@ToFlyAppLog(title="新增日志信息表"
    //@ApiOperation(value = "新增日志信息表")
    @PostMapping
    public ResultRespone savethis(@RequestBody Log log) {

        logService.save(log);

        return ResultRespone.success(true);
    }

    /**
     * 修改日志信息表
     *
     * @param log 日志信息表
     * @return ResultRespone
     */
    //@ToFlyAppLog(title="修改日志信息表" )
    //@ApiOperation(value = "修改日志信息表")
    @PutMapping
    public ResultRespone updateById(@RequestBody Log log) {
        return ResultRespone.success(logService.updateById(log));
    }

    /**
     * 通过id删除日志信息表
     *
     * @param id id
     * @return ResultRespone
     */
    //@ToFlyAppLog(title="通过id删除日志信息表" )
    //@ApiOperation(value = "通过ID删除日志信息表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Long")
    })
    @DeleteMapping("/{id}")
    public ResultRespone removeById(@PathVariable Long id) {
        return ResultRespone.success(logService.removeById(id));
    }

//    /**
//     * 获取码表信息
//     */
//    @GetMapping("/getClock" )
//    @ApiOperation(value = "获取码表得接口")
//    public ResultRespone getClock(@RequestParam(value = "pCid") String pCid) {
//        return ResultRespone.success(codeClient.updateCarInfo(pCid));
//    }

    /**
     * 手动添加日志的相关类容
     */
    @PostMapping("/manuallyAdd")
    @ApiOperation(value = "手动添加日志的相关类容")
    public ResultRespone manuallyAdd(List<MultipartFile> fileList, HttpServletRequest request) {
        return logService.manuallyAdd(fileList, request);
    }


    @GetMapping("/countLogType")
    @ApiOperation(value = "获取日志统计分类(部门-类型-数量)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "startDate", value = "开始日期", required = false, dataType = "String"),
            @ApiImplicitParam(name = "endDate", value = "结束日期", required = false, dataType = "String")
    })
    @ToFlyAppLog(title = "获取日志统计分类(部门-类型-数量)")
    public ResultRespone<List<CountLogVo>> countLogType(String startDate, String endDate) {
        Map map = new HashMap(12);
        map.put("startDate", StringUtil.isEmpty(startDate) ? null : startDate + " 00:00:00");
        map.put("endDate", StringUtil.isEmpty(endDate) ? null : endDate + " 23:59:59");
        return ResultRespone.success(logService.countLogType(map));
    }

    @PutMapping("/updateUserOperationTime")
    @ApiOperation(value = "更新用户操作时长")
    public ResultRespone<Boolean> updateUserOperationTime(@RequestParam(value = "username") String username) {
        Map map = new HashMap(12);
        map.put("username",username);
        List<Log> post = logService.list(new QueryWrapper<Log>().lambda().eq(Log::getCreateBy, username).eq(Log::getServiceId, "tofly-auth").eq(Log::getMethod, "POST").isNull(Log::getException).orderByDesc(Log::getCreateTime));

        if(null!=post && post.size()>0){
            Log oneLogInfo = post.get(0);
            // 获取当前时间
            Date createTime = oneLogInfo.getCreateTime();
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime localDateTime = DateTimeUtil.fromLong2LocalDateTime(createTime.getTime());
            Duration duration = Duration.between(localDateTime,now);
            //相差的秒数
            long seconds = duration.getSeconds();
            oneLogInfo.setOperatingTime(BigDecimal.valueOf(seconds));

            return ResultRespone.success(logService.updateById(oneLogInfo));
        }


        return ResultRespone.failed();
    }

    @GetMapping("/getOperationRecords")
    @ApiOperation(value = "获取操作记录分类(部门-人员)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "flag", value = "flag为空按照部门统计,flag为1按照部门人员统计", required = false, dataType = "String"),
            @ApiImplicitParam(name = "startTime", value = "统计操作起始时间 yyyy-MM-dd HH:mm:ss", required = true, dataType = "String"),
            @ApiImplicitParam(name = "endTime", value = "统计操作结束日期 yyyy-MM-dd HH:mm:ss", required = true, dataType = "String")
    })
    @ToFlyAppLog(title = "获取操作记录分类(部门-人员)")
    public ResultRespone<List<OperationRecordsVo>> operationRecords(String flag,String startTime, String endTime) {
        List<OperationRecordsVo> operationRecords = logService.getOperationRecords(flag, startTime, endTime);
        return ResultRespone.success(operationRecords);
    }
}
