package com.ruoyi.common.core.domain;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import java.util.ArrayList;
import java.util.List;

/**
 * 扩展分页条件orderBy
 * @param <T>
 */
public class Page<T> extends com.baomidou.mybatisplus.extension.plugins.pagination.Page<T> {

  private final static String REGEX = "^\\w+( (asc|desc|ASC|DESC)?)?(,\\w+( (asc|desc|ASC|DESC)?)?)*$";

  /**
   * 分词后的关键字
   */
  @Getter
  @Setter
  private String keys;

  public Page() {
  }

  public Page(long current, long size) {
    super(current, size);
  }

  public Page(long current, long size, long total) {
    super(current, size, total);
  }

  public Page(long current, long size, boolean searchCount) {
    super(current, size, searchCount);
  }

  public Page(long current, long size, long total, boolean searchCount) {
    super(current, size, total, searchCount);
  }

  public void setOrderBy(String orderBy) {
    if (StrUtil.isBlank(orderBy)) {
      return;
    }
    if (!orderBy.matches(REGEX)) {
      throw new RuntimeException("排序格式不正确");
    }
    String[] os = orderBy.split(",");
    super.setOrders(new ArrayList<>());
    for (String o : os) {
      int index = o.indexOf(" ");
      if (index == -1) {
        super.addOrder(OrderItem.asc(o));
      } else if(o.endsWith(" desc") || o.endsWith(" DESC")) {
        super.addOrder(OrderItem.desc(o.substring(0,index)));
      }else{
        super.addOrder(OrderItem.asc(o.substring(0,index)));
      }
    }
  }

  /**
   * 转化为Spring-data模块的排序
   * @return
   */
  public Sort sort(){
    if(CollUtil.isNotEmpty(orders())){
      List<Sort.Order> orders = ListUtil.list(true);
      orders().forEach(o->{
        orders.add(o.isAsc()?Sort.Order.asc(o.getColumn()):Sort.Order.desc(o.getColumn()));
      });
      return Sort.by(orders);
    }
    return Sort.unsorted();
  }

  /**
   * 转换为Spring-data模块的分页，含排序
   * @return
   */
  public Pageable pageable(){
    return PageRequest.of((int)getCurrent()-1,(int)getSize(),sort());
  }

  private static void main(String[] args) {
    System.out.println("asdf".matches(REGEX));
    System.out.println("asdf'".matches(REGEX));
    System.out.println("asdf asc".matches(REGEX));
    System.out.println("asdf desc".matches(REGEX));
    System.out.println("asdf abc".matches(REGEX));
    System.out.println("asdf,abc".matches(REGEX));
    System.out.println("asdf desc,abc".matches(REGEX));
    System.out.println("asdf desc,abc  asc".matches(REGEX));
    System.out.println("asdf desc,abc asc".matches(REGEX));
  }
}
