/**
 * @since Last modified: 2024-07-09 15:30:45
 * @function arrSort
 * @description Sort an array multiple times using multiple keys.
 * @param  {object|object[]} basis - criteria for array sorting.
 * @param  {object[]} source - Data to sort for.
 * @see {@link https://codepen.io/axui/pen/VwJwjwP|demo @ codepen}
 * @example
 * ax.arrSort({key:'a',dir:1},[{x:'abca',y:''},{x:'are',y:''}...]);
 * <!--return [{x:'abca',y:''},{x:'are',y:''}...]-->
 */
'use strict';
import { T_obj } from "../../../types/ax";
import ax from "../ax";
import config from "../global/config";
import getDataType from "./getDataType";
import getNestProp from "./getNestProp";
import isEmpty from "./isEmpty";
import valToArr from "./valToArr";
const arrSort = (source: T_obj[], basis?: T_obj | T_obj[]) => {
    if (isEmpty(source)) return;
    let basisType = getDataType(basis),
        _basis: T_obj[] = [],
        basisFn = (keys: T_obj[]) => {
            if (keys.length === 0) return (a: any, b: any) =>  (a + '').localeCompare(b + '',ax.lang.name);
            return (a: any, b: any) => {
                for (let k of keys) {
                    let key = '',
                        dir = 0,
                        result = 0;
                    if (k.hasOwnProperty('key')) {
                        key = k.key;
                    } else {
                        key = 'label';
                    }
                    if (k.hasOwnProperty('dir')) {
                        dir = k.dir === 'asc' ? 1 : k.dir === 'desc' ? -1 : 0;
                    } else {
                        dir = 1;
                    }
                    result = (getNestProp(a,key) + '').localeCompare(getNestProp(b,key) + '', k.locale || ax.lang.name, k.opt || {});
                    if (result !== 0) return result * dir;
                }
                return 0;
            };
        };
    if (basisType === 'Object') {
        _basis = [basis as T_obj];
    } else if (basisType === 'Array') {
        _basis = basis as T_obj[];
    }
    source.sort(basisFn(_basis));
};
export default arrSort;
