<?php
/**
 *
 * @author：llbjj
 * @DateTime：2022/5/5 20:27
 * @Description：
 *
 */

namespace Application\Common;
use Application\Exception\UserException;
use Application\Service\DB\Dictionary\FormField;
use Laminas\Db\Sql\Predicate\Like;
use Laminas\Stdlib\ArrayUtils;

class Com
{

    /**
     * Notes:获取两个日期差多少天
     * User: lltyy
     * DateTime: 2023/8/22 11:14
     *
     * @param $str //数值
     * @param $digit //小数位数
     * @return false|float|string
     */
    public static function diffDateDay($date1='',$date2='')
    {
        $diff_days = 0;
        if(!empty($date1) && !empty($date2)){
            $date1_str = substr($date1,0,4).'-'.substr($date1,4,2).'-'.substr($date1,6,2);
            $date2_str = substr($date2,0,4).'-'.substr($date2,4,2).'-'.substr($date2,6,2);
            $time1 = strtotime($date1_str);
            $time2 = strtotime($date2_str);
            $diff_seconds = abs($time1 - $time2);
            $diff_days = floor($diff_seconds / (24 * 60 * 60));
        }

        return $diff_days;
    }

    /**
     * Notes: 去除无用字符串
     * User: lltyy
     * DateTime: 2023/6/8 15:07
     *
     * @param string $str
     * @param int $type 类型【0 结果 1 时间 2 识别项 3 识别项 4 识别项拆分末尾数字】
     * @return string|string[]|null
     */
    public function replaceData($str='',$type=0){
        if($str != ''){
            if($type == 3){
                $str = preg_replace("/\\d+/",'', $str);
            }
            if($type == 0){
                $str = str_replace(',','.',$str);
                $str = str_replace(' 。','.',$str);
                $str = str_replace("'",'',$str);
                $str = str_replace('-','',$str);
                $str = str_replace('*','',$str);
                $str = str_replace(':','',$str);
                $str = str_replace('?','',$str);
            }
            $delete_result_arr = ["—","！","ㄧ","」","∠",":","·","/","；","‘","’","：","，","（","）","—","——","、","~","!","@","#","$","%","^","&","*","(",")","-","_","+","{","}",";","|",",","？","【","】","[","]","！","……"];
            $have_result_arr = ["—","！","ㄧ","」","∠",":","·","/","；","‘","’","：","，","（","）","—","——","、","~","!","@","#","$","%","^","&","*","(",")","-","_","+","=","{","}",";","|",",","<",">","《","》","？","【","】","[","]","！","……"];
            if(!in_array($type,[0,4])){
                $delete_result_arr[] = '=';
                $delete_result_arr[] = '.';
                $delete_result_arr[] = "<";
                $delete_result_arr[] = ">";
                $delete_result_arr[] = "《";
                $delete_result_arr[] = "》";
                $delete_result_arr[] = "↑";
                $delete_result_arr[] = "↓";
                $have_result_arr[] = '.';
                $have_result_arr[] = '↑';
                $have_result_arr[] = '↓';
            }
            $chinese_regular = '/([\x80-\xff]*)/i';//汉字正则
            $big_letter_regular = '/[A-Z]/';//大写字母正则
            $small_letter_regular = '/[a-z]/';//小写字母正则
            if($type == 4){
                $judge_str = '';
                if(strpos($str,'↑')){
                    $judge_str = '↑';
                }
                if(strpos($str,'↓')){
                    $judge_str = '↓';
                }
                $new_rawname_str = str_replace(['↑','↓'],'',$str);//替换字符串中的特殊字符
                $split_name_arr = mb_str_split($new_rawname_str);
                $end_chinese = '';//最后一个汉字
                $all_number = '';//最后一个汉字之后的数字
                $last_number = '';
                $chinese_regular = '/[\x7f-\xff]+/';//汉字正则
                $end_str_type = 0;
                if(!empty($split_name_arr)){
                    foreach($split_name_arr as $split_name){
                        //判断字符串类型
                        $str_type = 0;
                        if(is_numeric($split_name)){//是数字
                            $str_type = 1;
                        }else{
                            if($split_name == '.'){//是数字
                                $str_type = 1;
                            }else{
                                $new_split_name = str_replace($have_result_arr,'',$split_name);//替换字符串中的特殊字符
                                if($new_split_name == ''){
                                    $str_type = 3;
                                }else{
                                    $new_split_name = preg_replace($chinese_regular,'',$split_name);//去除字符串中的汉字
                                    $new_split_name = preg_replace($big_letter_regular,'',$new_split_name);//去除字符串中的大写字母
                                    $new_split_name = preg_replace($small_letter_regular,'',$new_split_name);//去除字符串中的小写字母
                                    if($new_split_name == ''){
                                        $str_type = 2;
                                    }
                                }
                            }
                        }
                        if($end_chinese != ''){
                            if($str_type == 1){
                                $all_number .= $split_name;
                            }elseif($str_type == 2){
                                $end_chinese = $split_name;
                                $all_number = '';
                            }elseif($str_type == 3){
                                if($end_str_type != 3 || $last_number == ''){
                                    $last_number = $all_number;
                                }
                                $end_chinese = $split_name;
                                $all_number = '';
                            }
                        }else{
                            if($str_type == 2){
                                $end_chinese = $split_name;
                                $all_number = '';
                            }elseif($str_type == 3){
                                if($end_str_type != 3 || $last_number == ''){
                                    $last_number = $all_number;
                                }
                                $end_chinese = $split_name;
                                $all_number = '';
                            }
                        }
                        $end_str_type = $str_type;
                    }
                }
                if($end_str_type == 3){
                    $all_number = $last_number;
                }
                if($all_number != ''){
                    $all_number .= $judge_str;
                }
                $str = $all_number;
            }else{
                if(!in_array($str,$have_result_arr)){
                    $str = str_replace($delete_result_arr,'',$str);//替换字符串中的特殊字符
                    if($type != 3){
                        $str = preg_replace($chinese_regular,'',$str);//去除字符串中的汉字
                    }
                    $str = preg_replace($big_letter_regular,'',$str);//去除字符串中的大写字母
                    $str = preg_replace($small_letter_regular,'',$str);//去除字符串中的小写字母
                }else{
                    $str = '';
                }
            }
        }
        $str = $str != '' ? $str : '';
        if($str != '' && $type == 1){
            if(in_array(substr($str,0,2),['21','22','23'])){
                $str = '20'.$str;
            }
            if(in_array(substr($str,0,3),['020','021','022','023'])){
                $str = '2'.$str;
            }
            if(in_array(substr($str,0,5),['22020','22021','22022','22023'])){
                $str = substr_replace($str,'2',0,2);
            }
            if(in_array(substr($str,0,6),['222020','222021','222022','222023'])){
                $str = substr_replace($str,'2',0,3);
            }
            if(in_array(substr($str,0,7),['2222020','2222021','2222022','2222023'])){
                $str = substr_replace($str,'2',0,4);
            }
        }
        unset($delete_result_arr);
        unset($have_result_arr);
        unset($chinese_regular);
        unset($big_letter_regular);
        unset($small_letter_regular);
        return $str;
    }



    /**
     * Notes: 验证日期
     * User: lltyy
     * DateTime: 2023/6/25 9:31
     *
     * @param string $annex_date
     * @return array
     */
    public static function validAnnexDate($annex_date=''){
        $code = 200;
        $msg = '';
        //截取日期前8位数字
        $annex_date = self::replaceData($annex_date,2);
        $annex_date = !empty($annex_date) ? substr($annex_date,0,8) : '';

        //判断报告时间是否符合要求
        if(empty($annex_date)){
            $code = 60010;
            $msg = '采集时间不能为空！';
        }else{
            $annex_date_year = substr($annex_date,0,4);
            $annex_date_month = substr($annex_date,4,2);
            $annex_date_day = substr($annex_date,6,2);
            $annex_date_str = $annex_date_year.'-'.$annex_date_month.'-'.$annex_date_day;
            $date_reg = "/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/";
            //匹配日期格式
            if (preg_match ($date_reg, $annex_date_str, $parts)) {
                //检测是否为日期,checkdate为月日年
                if (checkdate($parts[2], $parts[3], $parts[1])) {
                    $code = 200;
                }else{
                    $code = 60011;
                    $msg = '采集时间格式不正确，【正确格式如：20210607】！';
                }
            }else{
                $code = 60011;
                $msg = '采集时间格式不正确，【正确格式如：20210607】！';
            }
            if($code == 200){
                $nowYear = date('Y');
                if(intval($annex_date_year) > $nowYear){
                    $code = 60011;
                    $msg = '采集时间所属年份【'.$annex_date_year.'】不能超过当前年份【'.$nowYear.'】！';
                }else{
                    if(intval($annex_date_year) < 2020){
                        $code = 60012;
                        $msg = '采集时间所属年份【'.$annex_date_year.'】不在【2020~~'.$nowYear.'】之间！';
                    }
                }
            }
        }
        return ['code'=>$code,'msg'=>$msg,'date'=>$annex_date];
    }


    /**
     * Notes:验证时间
     * User: lltyy
     * DateTime: 2024/3/27 11:21
     *
     * @param string $annex_date
     * @param int $type 【0 时分 1 小时】
     * @return array
     */
    public static function validAnnexDatetime($annex_date='',$type = 0){
        $code = 200;
        $msg = '';
        //截取日期前4位数字
        $new_annex_date = !empty($annex_date) ? substr($annex_date,0,4) : '';
        if($type == 1){
            $new_annex_date = !empty($annex_date) ? substr($annex_date,0,2) : '';
        }
        //判断报告时间是否符合要求
        if(empty($annex_date)){
            $code = 60010;
            $msg = '不能为空！';
        }else{
            if($type == 1){
                $new_annex_date = !empty($annex_date) ? substr($annex_date,0,2) : '';
                $time_hour = substr($new_annex_date,0,2);
                $time_str = $time_hour;
                $time_reg = "/^([01]?[0-9]|2[0-3])$/";
                //匹配日期格式
                if (preg_match ($time_reg, $time_str)) {
                    $code = 200;
                }else{
                    $code = 60011;
                    $msg = '格式不正确，【正确格式如：09】！';
                }
            }else{
                $time_hour = substr($new_annex_date,0,2);
                $time_sceond = substr($new_annex_date,2,2);
                $time_str = $time_hour.':'.$time_sceond;
                $time_reg = "/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/";
                //匹配日期格式
                if (preg_match ($time_reg, $time_str)) {
                    $code = 200;
                }else{
                    $code = 60011;
                    $msg = '格式不正确，【正确格式如：0909】！';
                }
            }
        }
        return ['code'=>$code,'msg'=>$msg,'date'=>$new_annex_date];
    }


    /**
     * Notes:Notes:识别结果去除首尾多余的1
     * User: lltyy
     * DateTime: 2024/2/18 9:06
     * 
     * 1》上下箭头 在前面，且结果大于最大值2倍，首位是1，去掉1后依然大于最大值，则首位1直接去掉
     * 2》上下箭头 在后面，如果尾数为1，且结果大于2两倍最大值，去掉尾数1后，小于最小值，则直接去掉尾数1，如果去掉尾数1，大于最大值，则去掉尾数1
     *
     * @param string $result
     * @param string $min
     * @param string $max
     * @return string|string[]
     */
    public static function cutResultOne($result='',$min='',$max='')
    {
        $new_result = $result;
        if($result != '' && is_numeric($result)){
            //首位是1
            $firstDigit = substr(strval($new_result), 0, 1);
            if($firstDigit == 1){
                $first_set_judge = self::getResultSetJudge($new_result,$min,$max);
                if(in_array($first_set_judge,[4])){
                    $firstCheckResult = substr_replace($new_result,'',0,1);
                    $first_check_set_judge = self::getResultSetJudge($firstCheckResult,$min,$max);
                    if(in_array($first_check_set_judge,[2,4])){
                        $new_result = $firstCheckResult;
                    }
                }
            }

            //尾数为1
            $endDigit = substr(strval($new_result), -1);
            if($endDigit == 1){
                $end_set_judge = self::getResultSetJudge($new_result,$min,$max);
                if(in_array($end_set_judge,[4])){
                    $endCheckResult = substr_replace($new_result,'',-1);
                    $end_check_set_judge = self::getResultSetJudge($endCheckResult,$min,$max);
                    if(in_array($end_check_set_judge,[1,3,2,4])){
                        $new_result = $endCheckResult;
                    }
                }
            }
        }

        return $new_result;
    }

    /**
     * Notes:结果判断异常
     * User: lltyy
     * DateTime: 2024/2/18 9:06
     *
     * @param string $result
     * @param string $set_min
     * @param string $set_max
     * @return int
     * $set_judge
     *      0：正常
     *      1：低
     *      2：高
     *      3：超低【低于最小值的二分之一】
     *      4：超高【高于最大值的2倍】
     */
    public static function getResultSetJudge($result='',$set_min='',$set_max=''){
        $result = is_null($result) || $result == '' ? '' : trim($result);
        $set_min = is_null($set_min) || $set_min == '' ? '' : trim($set_min);
        $set_max = is_null($set_max) || $set_max == '' ? '' : trim($set_max);
        $set_judge = 0;

        if($result != '' && is_numeric($result)){
            if($set_min != ''){
                if($result < $set_min){
                    $set_judge = 1;
                    //判断是否低于最小值2倍
                    $set_min_two = $set_min/2;
                    if($result <= $set_min_two){//超低
                        $set_judge = 3;
                    }
                }else{
                    if($set_max != ''){
                        if(strpos($set_max,'<') !== false){
                            $set_max_number = str_replace('<','',$set_max);
                            if($result >= $set_max_number){
                                $set_judge = 2;
                                //判断是否高于最大值2倍
                                $set_max_two = $set_max_number*2;
                                if($result >= $set_max_two){//超高
                                    $set_judge = 4;
                                }
                            }
                        }else{
                            if($result >= $set_max){
                                $set_judge = 2;
                                //判断是否高于最大值2倍
                                $set_max_two = $set_max*2;
                                if($result >= $set_max_two){//超高
                                    $set_judge = 4;
                                }
                            }
                        }
                    }
                }
            }else{
                if($set_max != ''){
                    if(strpos($set_max,'<') !== false){
                        $set_max_number = str_replace('<','',$set_max);
                        if($result >= $set_max_number){
                            $set_judge = 2;
                            //判断是否高于最大值2倍
                            $set_max_two = $set_max_number*2;
                            if($result >= $set_max_two){//超高
                                $set_judge = 4;
                            }
                        }
                    }else{
                        if($result >= $set_max){
                            $set_judge = 2;
                            //判断是否高于最大值2倍
                            $set_max_two = $set_max*2;
                            if($result >= $set_max_two){//超高
                                $set_judge = 4;
                            }
                        }
                    }
                }
            }
        }

        return $set_judge;
    }


    /**
     * Notes:保留小数位数【多余直接舍弃】
     * User: lltyy
     * DateTime: 2023/8/22 11:14
     *
     * @param $str //数值
     * @param $digit //小数位数
     * @return false|float|string
     */
    public static function numberDigit($str,$digit)
    {
        $new_str = $str;
        if(is_numeric($str)) {
            $last_digit = $digit+1;
            switch ($digit) {
                case 0:
                    $new_str = floor($str);
                    break;
                default:
                    $new_str = sprintf("%.".$digit."f",substr(sprintf('%.'.$last_digit.'f',$str),0,-1));
                    break;
            }
        }

        return $new_str;
    }

    /**
     * Notes: 字符串切片
     * User: llbjj
     * DateTime: 2023/4/26 10:14
     *
     * @param string $str
     * @return array
     */
    public static function cutIntoSlices(string $str)
    {
        $result = [];
        if($str != '') {
            $strLen = mb_strlen($str);
            for ($i = 0; $i < $strLen; $i++) {
                $splitStr = $i ? mb_substr($str, $i) : $str;

                for($len = $i ? 2 : 1; $len <= mb_strlen($splitStr); $len++) {
                    $splitArr = mb_str_split($splitStr, $len);
                    $result = ArrayUtils::merge($result, $splitArr);
                }
            }
        }

        return array_unique($result);
    }


    public function getTree($data, $pid = 0,$type = 0,$level = 2,$field = 'fid'){
        $tree = [];
        foreach($data as $k => $v){
            $v['icon'] = $v['icon'] ?: 'formOcr';
            if (isset($v['parent_id'])){
                if(($v['parent_id'] == $pid)){
                    if (!empty($type) && $v['level'] > $level){
                        continue;
                    }
                    $v['children'] = $this->getTree($data, $v['id'],$type,$level);
                    $tree[] = $v;
                    unset($data[$k]);
                }
            }else{
                if(($v[$field] == $pid)){
                    $v['children'] = $this->getTree($data, $v['id'],$type,$level,$field);
                    $tree[] = $v;
//                    unset($data[$k]);
                }
            }

        }
        return $tree;
    }

    /**
     * 无限分类
     * **/
    public function getTreed($arr){
        $items = array();
        foreach($arr as $v){
            $items[$v['id']] = $v;
        }
        $tree = array();
        foreach($items as $k => $item){
            if(isset($items[$item['pid']])){
                $items[$item['pid']]['children'][] = &$items[$k];
            }else{
                $tree[] = &$items[$k];
            }
        }
        return $tree;
    }

    /**
     * 无限分类
     * **/
    public function getTreeall($arr,$pid=0,$step=0,$name='',$pidname=''){
        global $tree;
        foreach($arr as $key=>$val) {
            if($val[$pidname] == $pid) {
                $flg = str_repeat("&nbsp;&nbsp;&nbsp;",$step);
                $val[$name] = $flg.$val[$name];
                $tree[] = $val;
                $this->getTreeallAction($arr , $val['id'] ,$step+1);
            }
        }
        return $tree;
    }

    /**
     * Notes: 组合sql WHERE条件
     *
     * @param array $searchArr
     * @param array $formFieldData
     * @param int $returnType 0/字符串 1、数组
     * @return string
     */
    public static function CreateSearchWhere(array $searchArr, array $formFieldData, $returnType = 0){
        $popData = ['limit', 'page'];
        $search_where_data = ['1'];
        foreach($searchArr as $field => $searchVal){
            if(!empty($formFieldData[$field]) && $searchVal !== ''){
                switch($formFieldData[$field]['type']){
                    case 'Input':
                        array_push($search_where_data, new Like($field, "%{$searchVal}%"));
                        break;
                    default:
                        $search_where_data[$field] = $searchVal;
                }
            }
        }

        return $returnType ? $search_where_data : implode(' and ', $search_where_data);
    }

    /**
     * Notes: 获取每个表单模块的说明数组（select的options数组格式）
     *
     * @return array
     */
    public static function getSearchFormEventData(){
        $result = [];
        $eventFormData = include APP_PATH.'/formData/formMap.php';
        if(!empty($eventFormData)){
            foreach($eventFormData as $eventCode => $eventLabel){
                $result[] = ['label' => $eventLabel, 'value' => $eventCode];
            }
        }
        return $result;
    }

    /**
     * @Description: 获取两个不同时间的相差的毫秒数(暂时不支持结束时间小于开始时间)
     * @Author: llbjj
     * @Date: 2022-07-11 14:17:11
     * @param {string} $startDate   开始时间
     * @param {string} $endDate     结束时间
     * @return int
     */    
    public static function getDiffMs(string $startDate, string $endDate):int
    {
        // 开始时间 大于 结束时间，直接返回 0
        if($startDate > $endDate) return 0;

        $isMoreThan = false;
        $oneDayMs = 86400000;
        $diffMs = 0;
        $start_time = date_create($startDate);
        $end_time = date_create($endDate);

        $dateDiffObj = date_diff($end_time, $start_time);

        $date_params_arr = ['y', 'm', 'd', 'h', 'i', 's'];

        foreach($date_params_arr as $date_param){
            $diffVal = $dateDiffObj->{$date_param};
            if($diffVal){
                switch($date_param) {
                    case 'h': $diffMs += $diffVal * 60 * 60 * 1000; break;
                    case 'i': $diffMs += $diffVal * 60 * 1000; break;
                    case 's': $diffMs += $diffVal * 1000; break;
                    default: $isMoreThan = true;break;
                }
            }
        }
        // 如果日期差超出一天，直接获取相差的天数
        if($isMoreThan) $diffMs += floor((strtotime($endDate) - strtotime($startDate)) / 86400) * $oneDayMs;

        return $diffMs;
    }

    /**
     * @Description: 将内容写入文件中
     * @Author: llbjj
     * @Date: 2022-07-12 17:17:11
     * @param {string} $fileName   开始时间
     * @param {string} $filePath     结束时间
     * @param {string} $fileContent 文件内容
     */ 
    public static function writeFile(string $fileName, string $filePath, string $fileContent)
    {
        try{
            if($fileContent !== ''){
                if(!file_exists($filePath)) {
                    mkdir($filePath, 0777, true);
                }
                if(substr($filePath, -1, 1) != '/') $filePath .= '/';
                file_put_contents($filePath.$fileName, $fileContent, FILE_APPEND);
            }
        }catch(\Exception $e){
            return false;
        }
    }

    /**
     * 执行树型数据生成
     * @param array $data   要进行转化的数据
     * @param string $children 子节点下标名称，默认为‘children’
     * @param string $defaultID ID节点下标名称，默认为'id'
     * @param string $parentID 父节点下标名称，默认为‘pid’
     * @param string $defaultTitle title节点下标名称，默认为‘title’
     */
    public static function get_tree_data(array &$data, $children = 'children', $defaultID = 'id', $parentID = 'pid', $defaultTitle = 'title'){
        $collection_data = [];
        foreach ($data as $item) {
            foreach($item as $field_key=>$field_val){
                if($field_key == $defaultID){
                    $collection_data[$item[$defaultID]]['id'] = $field_val;
                }else if($field_key == $defaultTitle){
                    $collection_data[$item[$defaultID]]['title'] = $field_val;
                }else if($field_key == $parentID){
                    $collection_data[$item[$defaultID]][$parentID] = $field_val;
                }else{
                    $collection_data[$item[$defaultID]][$field_key] = $field_val;
                }
            }

            $collection_data[$item[$defaultID]][$children] = [];
        }

        foreach ($collection_data as $key => $item) {
            if(isset($item[$parentID]) and isset($collection_data[$item[$parentID]])){
                if (isset($item[$parentID]) and $item[$parentID] != 0 && count($collection_data[$item[$parentID]]) > 1) {
                    $collection_data[$item[$parentID]][$children][] = &$collection_data[$key];
                    if (empty($collection_data[$key][$children])) unset($collection_data[$key][$children]);
                }
            }
        }

        $tree = [];
        foreach($collection_data as $key => &$item) {
            if ($item[$parentID] != 0) unset($collection_data[$key]);
            if (empty($item[$children])) unset($item[$children]);

            if(isset($collection_data[$key]) and $collection_data[$key]){
                $tree[] = $collection_data[$key];
            }
        }

        return $tree;
    }

    /**
     * 执行树型数据生成
     * @param array $data   要进行转化的数据
     * @param string $children 子节点下标名称，默认为‘children’
     * @param string $defaultID ID节点下标名称，默认为'id'
     * @param string $parentID 父节点下标名称，默认为‘pid’
     * @param string $defaultTitle title节点下标名称，默认为‘title’
     */
    public static function get_treeoption_data(array &$data, $children = 'children', $defaultID = 'value', $parentID = 'pid', $defaultTitle = 'label'){
        $collection_data = [];
        foreach ($data as $item) {
            foreach($item as $field_key=>$field_val){
                if($field_key == $defaultID){
                    $collection_data[$item[$defaultID]][$defaultID] = $field_val;
                }else if($field_key == $defaultTitle){
                    $collection_data[$item[$defaultID]][$defaultTitle] = $field_val;
                }else if($field_key == $parentID){
                    $collection_data[$item[$defaultID]][$parentID] = $field_val;
                }else{
                    $collection_data[$item[$defaultID]][$field_key] = $field_val;
                }
            }

            $collection_data[$item[$defaultID]][$children] = [];
        }

        foreach ($collection_data as $key => $item) {
            if(isset($item[$parentID]) and isset($collection_data[$item[$parentID]])){
                if (isset($item[$parentID]) and $item[$parentID] != 0 && count($collection_data[$item[$parentID]]) > 1) {
                    $collection_data[$item[$parentID]][$children][] = &$collection_data[$key];
                    //if (empty($collection_data[$key][$children])) unset($collection_data[$key][$children]);
                }
            }
        }

        $tree = [];
        foreach($collection_data as $key => &$item) {
            if ($item[$parentID] != 0) unset($collection_data[$key]);
            //if (empty($item[$children])) unset($item[$children]);

            if(isset($collection_data[$key]) and $collection_data[$key]){
                $tree[] = $collection_data[$key];
            }
        }

        return $tree;
    }

    /**
     * 执行树型数据生成
     * @param array $data   要进行转化的数据
     * @param string $children 子节点下标名称，默认为‘children’
     * @param string $defaultID ID节点下标名称，默认为'id'
     * @param string $parentID 父节点下标名称，默认为‘pid’
     * @param string $defaultTitle title节点下标名称，默认为‘title’
     */
    public static function get_newtree_data(array &$data, $children = 'children', $defaultID = 'id', $parentID = 'pid', $defaultTitle = 'title'){
        $collection_data = [];
        foreach ($data as $item) {
            foreach($item as $field_key=>$field_val){
                if($field_key == $defaultID){
                    $collection_data[$item[$defaultID]]['id'] = $field_val;
                }else if($field_key == $defaultTitle){
                    $collection_data[$item[$defaultID]]['title'] = $field_val;
                }else if($field_key == $parentID){
                    $collection_data[$item[$defaultID]][$parentID] = $field_val;
                }else{
                    $collection_data[$item[$defaultID]][$field_key] = $field_val;
                }
            }

            $collection_data[$item[$defaultID]][$children] = [];
        }

        foreach ($collection_data as $key => $item) {
            if(isset($item[$parentID]) and isset($collection_data[$item[$parentID]])){
                if (isset($item[$parentID]) and $item[$parentID] != 0 && count($collection_data[$item[$parentID]]) > 1) {
                    $collection_data[$item[$parentID]][$children][] = &$collection_data[$key];
                    if (empty($collection_data[$key][$children])) unset($collection_data[$key][$children]);
                }
            }
        }

        $tree = [];
        foreach($collection_data as $key => &$item) {
            if ($item[$parentID] != 0) unset($collection_data[$key]);
            if (empty($item[$children])) unset($item[$children]);
            if (empty($item[$children])) unset($item['disabled']);

            if(isset($collection_data[$key]) and $collection_data[$key]){
                $tree[] = $collection_data[$key];
            }
        }

        return $tree;
    }


    /**
     * Notes:转换化验单识别结果
     * @param array $ocrResult
     */
    public static function changeOcrResult(array &$ocrResult) : array
    {
        $keyMap = [
            '项目名称/编码'  => 'item_name',
            '项目名称' => 'item_name',
            '结果'      => 'result',
            '单位'     => 'unit',
            '参考值'   => 'reference_range',
            '采样时间'  => 'collect_date',
            '参考范围' => 'reference_range',
            '检验结果' => 'result',
            '计量单位' => 'unit',
        ];
        $result = [];
        // 将结果存放到表中
        if(!empty($ocrResult)) {
            foreach($ocrResult as &$item) {
                $row = [];
                foreach($item as $key => &$val) {
                    if(!isset($keyMap[$key])) continue;
                    $row[$keyMap[$key]] = $val;
                    if($key === '参考值') {
                        $reference_range = str_ireplace(['--', '~'], '-', $val);
                        $rangeData = explode('-', $reference_range);
                        $row['reference_range_min'] = $rangeData[0] ?? '';
                        $row['reference_range_max'] = $rangeData[1] ?? '';
                    }
                }
                $result[] = $row;
            }
        }

        return $result;
    }

    /**
     * Notes: 获取图片的大小
     * User: llbjj
     * DateTime: 2024/5/28 17:02
     *
     * @param string $file
     * @return false|int|mixed
     */
    public static function customFilesize(string $file) {
        $isHttp = strpos($file, '://');

        if($isHttp) {
            $header = get_headers($file, 1);
            return $header['Content-Length'];
        }else return filesize($file);
    }

    /**
     * @note 字符串脱敏
     * @param string|null $str
     * @return string
     */
    public static function maskingPhoneNumber( ?string $str): string
    {
        $replacement = '****';
        $start = 3;
        $end = -2;

        $length = mb_strlen($str, 'UTF-8');
        if($length < 6) {
            return $replacement;
        }
        return mb_substr($str, 0, $start, 'UTF-8') . $replacement . mb_substr($str, $length + $end, $length, 'UTF-8');
    }

    /**
     * @note 验证表单字段类型是否是日期类型
     * @return bool
     */
    public static function isValidDateField($formFieldType): bool
    {
        return in_array ($formFieldType, [
            FormField::FORM_FIELD_TYPE_DATE_UK, // 日期(UK)
            FormField::FORM_FIELD_TYPE_DATE,    // 日期(年月日)
            FormField::FORM_FIELD_TYPE_DATETIME,    // 日期(年月日时分秒)
            FormField::FORM_FIELD_TYPE_DATE_SECOND, // 日期(年月日时分)
            FormField::FORM_FIELD_TYPE_DATETIME_UK, // 日期(年月日时分UK)
            FormField::FORM_FIELD_TYPE_DATETIME_SECOND_UK, // 日期(年月日时分秒UK)
            FormField::FORM_FIELD_TYPE_TIME_UK, // 日期(时分UK)
            FormField::FORM_FIELD_TYPE_TIME_SECOND_UK, // 日期(时分秒Uk)
        ]);
    }
}