package com.ibiz.mybatis.util.helper;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ibiz.util.SearchContext;
import com.ibiz.util.helper.QueryBuilderHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Component;
import org.springframework.data.domain.Pageable;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Component
public class QueryBuilder {

    @Autowired
    QueryBuilderHelper queryBuilderHelper;

    /**
     * 条件构造器
     * @param context
     * @return
     */
    public QueryWrapper buildQueryWrapper(SearchContext context){
        QueryWrapper qw=new QueryWrapper();
        String sql=queryBuilderHelper.buildSQL(context);//获取sql
        if(!StringUtils.isEmpty(sql)) //拼接sql
            qw.apply(sql);
        return qw;
    }

    /**
     * 分页参数
     * @param context
     * @return
     */
    public Page  buildPage(SearchContext context){

        Page page;
        List<String> asc_fieldList = new ArrayList<>();
        List<String> desc_fieldList = new ArrayList<>();

        Pageable pageable=context.getPageable();
        int currentPage=pageable.getPageNumber();
        int pageSize=pageable.getPageSize();

        //构造mybatis-plus分页
        if(StringUtils.isEmpty(currentPage) || StringUtils.isEmpty(pageSize))
            page=new Page(1,Short.MAX_VALUE);
        else
            page=new Page(currentPage+1,pageSize);

        //构造mybatis-plus排序
        Sort sort = pageable.getSort();
        Iterator<Sort.Order> it_sort = sort.iterator();

        if(ObjectUtils.isEmpty(it_sort))
            return page;

        while (it_sort.hasNext()) {
            Sort.Order sort_order = it_sort.next();
            if(sort_order.getDirection()== Sort.Direction.ASC){
                asc_fieldList.add(sort_order.getProperty());
            }
            else if(sort_order.getDirection()== Sort.Direction.DESC){
                desc_fieldList.add(sort_order.getProperty());
            }
        }

        if(asc_fieldList.size()>0){
            page.setAscs(asc_fieldList);
        }
        if(desc_fieldList.size()>0){
            page.setDescs(desc_fieldList);
        }

        return page;
    }

    /**
     * page转list
     * @param page_datas
     * @return
     */
    public List page2List(Page page_datas){

        List list_datas=new ArrayList();
        if(page_datas.getRecords().size()==0)
            return list_datas;

        list_datas.addAll(page_datas.getRecords());

        return list_datas;
    }

}
