<?php

// 应用公共文件

/**
 * 
 * @param type $algo
 * @param type $password
 * @param type $salt
 * @param type $hash_iterations
 * @return type
 */
function simple_hash($algo = 'md5', $password = '', $salt = '', $hash_iterations = 2) {
    $res = '';
    $pass = $salt . $password;
    $encoded = hash($algo, $pass, true);
    $iteration = $hash_iterations - 1;
    if ($iteration > 0) {
        for ($i = 0; $i < $iteration; $i++) {
            $encoded = hash($algo, $encoded, true);
        }
    }
    $tmp = unpack('H*', $encoded);
    if (!empty($tmp) && !empty($tmp[1])) {
        $res = $tmp[1];
    }
    return $res;
}

/**
 * 检查权限
 * @param type $url
 * @param type $old_url
 * @return type
 */
function chkCommission($url, $old_url) {
    return app\common\api\MenuApi::chkPermission($url, $old_url);
}

/**
 * 随机字符ID
 * @return type
 */
function getStringId() {
    $day = random_int(10, 30);
    $time = strtotime("-4 years -6 months -" . $day . " days");
    $randnum = random_int(100000000, 999999999);
    $randnum = str_shuffle($randnum);
    return $time . $randnum;
}

function isNullOrEmpty($obj) {
    if (!$obj || $obj == "" || !isset($obj))
        return "";
    return $obj;
}

function getTreeList($array, $id_field = "id", $pid_field = "pid", $value = "0") {
    static $result = [];
    foreach ($array as $key => $item) {
        if ($value == $item[$pid_field]) {
            $result[] = $item;
            unset($array[$key]);
            getTreeList($array, $id_field, $pid_field, $item[$id_field]);
        }
    }
    return $result;
}

/**
 * 读取excel
 * @param type $filepath
 * @param type $sheetIndex
 * @return type
 */
function getExcelDatas($filepath, $sheetIndex = 0) {
    $reader_type = \PHPExcel_IOFactory::identify($filepath);
    $reader = \PHPExcel_IOFactory::createReader($reader_type);
    $phpexcel = $reader->load($filepath);
    $sheet = $phpexcel->getSheet($sheetIndex);
    return $sheet->toArray();
}

/**
 * 检查是不是excel格式，不确定是否都是可用文件，主要还是第一和最后一个比较常见
 * @param type $mime
 * @return type
 */
function isExcelFile($mime) {
    return in_array($mime, [
        "application/vnd.ms-excel",
        "application/msexcel",
        "application/x-msexcel",
        "application/x-ms-excel",
        "application/x-excel",
        "application/x-dos_ms_excel",
        "application/xls",
        "application/x-xls",
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    ]);
}
