package com.dtok.api.controller;

import com.dtok.entity.Account;
import com.dtok.entity.AccountRole;
import com.dtok.entity.LoginHistory;
import com.dtok.framework.response.ResponseData;
import com.dtok.framework.util.ToolUtil;
import com.dtok.repository.LoginHistoryRepository;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.query.internal.NativeQueryImpl;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.criteria.Predicate;
import java.util.List;

@RestController
@RequestMapping("/loginHistory")
@Slf4j
public class LoginHistoryController {

    @Autowired
    EntityManager entityManager;

    @Autowired
    LoginHistoryRepository loginHistoryRepository;
    @GetMapping("/search")
    public ResponseData search(@RequestParam("loginSys")String loginSys,@RequestParam("ip") String ip, @RequestParam("username") String username,
                               @RequestParam("actionType") String actionType,@RequestParam("startTime") String startTime,@RequestParam("endTime") String endTime) {
        Specification<LoginHistory> query = (root, query1, criteriaBuilder) -> {
            Predicate predicate = criteriaBuilder.conjunction();
            if (ToolUtil.isNotEmpty(ip)) {
                predicate.getExpressions().add(criteriaBuilder.or(criteriaBuilder.like(root.get("code"), "%" + ip + "%")));
            }
            if (ToolUtil.isNotEmpty(username)) {
                predicate.getExpressions().add(criteriaBuilder.or(criteriaBuilder.like(root.get("name"), "%" + username + "%")));
            }
            if (ToolUtil.isNotEmpty(actionType)) {
                predicate.getExpressions().add(criteriaBuilder.or(criteriaBuilder.equal(root.get("actionType"), actionType)));
            }
            if (ToolUtil.isNotEmpty(loginSys)) {
                predicate.getExpressions().add(criteriaBuilder.or(criteriaBuilder.equal(root.get("loginSys"), loginSys)));
            }
            if (ToolUtil.isNotEmpty(startTime)) {
                predicate.getExpressions().add(criteriaBuilder.greaterThanOrEqualTo(root.get("happenTime").as(String.class), startTime));
            }
            if (ToolUtil.isNotEmpty(endTime)) {
                predicate.getExpressions().add(criteriaBuilder.lessThanOrEqualTo(root.get("happenTime").as(String.class), endTime));
            }
            return predicate;
        };
        List<LoginHistory> result = loginHistoryRepository.findAll(query);
        return ResponseData.success(result);
    }
}
