/**
 * Copyright 2018-2020 stylefeng & fengshuonan (sn93@qq.com)
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.inkasso.adapter.page;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.util.CollectionUtils;

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


/**
 * 默认分页参数构建
 *
 * @author zc
 * @date 2021-09-23
 */
public class PageFactory {

    /**
     * 自定义参数的分页
     *
     * @author zc
     * @Date 2021-03-23
     */
    public static <T> Page<T> createPage(PageQuery pageQuery) {

        int pageSize = 20;
        int pageNo = 1;

        if (pageQuery != null && pageQuery.getPageSize()!=null) {
            pageSize = pageQuery.getPageSize();
        }

        if (pageQuery != null && pageQuery.getPageNum()!=null) {
            pageNo = pageQuery.getPageNum();
        }

    if (pageQuery == null) {
      return new Page<>(pageNo, pageSize);
    }
    Page<T> page = new Page<>(pageNo, pageSize);
    setSort(page, pageQuery);

    return page;
  }


  private static void setSort(Page page, PageQuery pageQuery) {
    List<OrderItem> orderItems = new ArrayList<>();
    if (!CollectionUtils.isEmpty(pageQuery.getSortList())) {
      //多个字段排序
      for (Sort s : pageQuery.getSortList()) {
        Boolean ascFlag = s.getAsc();
        String orderByField = s.getFiledName();
        if (ascFlag == null) {
          continue;
        }
        OrderItem orderItem = new OrderItem();
        orderItem.setColumn(orderByField);
        //ASC.equalsIgnoreCase(sort)
        orderItem.setAsc(ascFlag);
        orderItems.add(orderItem);
      }
    } else {
      //单个字段
      Boolean ascFlag = pageQuery.getAsc();
      String orderByField = pageQuery.getFiledName();
      if (ascFlag != null) {
        OrderItem orderItem = new OrderItem();
        orderItem.setColumn(orderByField);
        orderItem.setAsc(ascFlag);
        orderItems.add(orderItem);
      }
    }
    if (!CollectionUtils.isEmpty(orderItems)) {
      page.setOrders(orderItems);
    }
  }
}
