<?php

namespace Application\Common;

use \baidu\AipOcr;
use Laminas\Config\Config;
use Application\Service\Extension\Laminas;

class Ocr
{
    public static function ocr_result($imgPath = '', $templateSign = '', $delimit = '', &$setocrfield_data = [])
    {
        $_result = [];
        $baidu_config = new Config(include realpath(__DIR__).'/../../../../config/autoload/zend-baidu.global.php');

        $client = new \AipOcr($baidu_config['baidu']['app_id'], $baidu_config['baidu']['api_key'], $baidu_config['baidu']['aecret_key']);
        $image = file_get_contents($imgPath);
        if ($templateSign == '-1') {
            //通用文字识别接口
            $text = $options = array();

            $options['probability'] = "true";
            $result = $client->basicGeneralUrl($imgPath,$options);
            if($result['error_code'] != 0){
                return $result;
            }
            foreach ($result['words_result'] as $item) {
                array_push($text, $item['words']);
            }
            $_result['item_name'] = 'text';
            $_result['user']['result'] = implode(',', $text);
            $_result['user']['result_type'] = 1;
        }else if($templateSign == '-2'){
            //通用医疗检查单
            $result = $client->medicalReportDetection($image);
            if($result['error_code'] != 0){
                return $result;
            }
            if($result['Item_row_num'] && !empty($setocrfield_data)){
                foreach($result['words_result'] as $itemKey => &$itemVal){
                    switch ($itemKey){
                        case 'Item':
                            foreach($itemVal as $fieldKey => &$fieldData){
                                foreach($fieldData as &$item){
                                    if(!empty($setocrfield_data[1][$item['word_name']])){
                                        $_result['user']['info'][$fieldKey][$setocrfield_data[1][$item['word_name']]] = $item['word'];
                                        if($setocrfield_data[1][$item['word_name']] == 'reference_range'){
                                            $item['word'] = str_ireplace(['~', '--'], '-', $item['word']);

                                            $word_value_arr = explode('-', $item['word']);
                                            if (count($word_value_arr) > 1) {
                                                $word_value_arr = array_filter($word_value_arr);
                                                $reference_range_max = floatval(array_pop($word_value_arr));
                                                $reference_range_min = floatval(array_pop($word_value_arr));
                                            } else {
                                                $reference_range_max = '';
                                                $reference_range_min = '';
                                            }
                                            $_result['user']['info'][$fieldKey]['reference_range_min'] = $reference_range_min;
                                            $_result['user']['info'][$fieldKey]['reference_range_max'] = $reference_range_max;
                                        }
                                    }
                                }
                            }
                            break;
                        case 'CommonData':
                            foreach($itemVal as &$item){
                                if(!empty($setocrfield_data[0][$item['word_name']])) {
                                    $_result['user'][$setocrfield_data[0][$item['word_name']]] = $item['word'];
                                }
                            }
                            break;
                    }
                }
            }

        } else {
            if ($delimit == 1) {
                $delimiter = '-';
            }elseif($delimit == 2) {
                $delimiter = '~';
            }elseif($delimit == 3) {
                $delimiter = '--';
            }
            $result = $client->custom($image, array('templateSign' => $templateSign));
            if($result['error_code'] != 0){
                return $result;
            }
            foreach ($result['data']['ret'] as $key => &$val) {
                $word_name_arr = explode('#', $val['word_name']);
                if (count($word_name_arr) == 3) {
                    $_result['user']['info'][$word_name_arr[1]][$word_name_arr[2]] = $val['word'];
                    if (in_array($word_name_arr[2], array('reference_range', 'reference_range-1'))) {
                        $word_value_arr = explode($delimiter, $val['word']);
                        if (count($word_value_arr) > 1) {
                            $word_value_arr = array_filter($word_value_arr);
                            $reference_range_max = floatval(array_pop($word_value_arr));
                            $reference_range_min = floatval(array_pop($word_value_arr));
                        } else {
                            $reference_range_max = '';
                            $reference_range_min = '';
                        }
                        $_result['user']['info'][$word_name_arr[1]][$word_name_arr[2] . '_min'] = $reference_range_min;
                        $_result['user']['info'][$word_name_arr[1]][$word_name_arr[2] . '_max'] = $reference_range_max;
                    }
                } else {
                    $word_value_arr = explode(':', $val['word']);
                    if (count($word_value_arr) == 2) {
                        $_result['user'][$val['word_name']] = $word_value_arr[1];
                    } else {
                        $_result['user'][$val['word_name']] = $val['word'];
                    }
                }
            }
        }
        foreach ($_result['user']['info'] as $k => $v) {
            $two_col_data = [];
            foreach ($v as $k1 => $v1) {
                if (strpos($k1, "-1")) {
                    unset($_result['user']['info'][$k][$k1]);
                    if($v1 !== ''){
                        $two_col_data[str_ireplace('-1', '', $k1)] = $v1;
                    }
                }
            }
            if(count($two_col_data)){
                $_result['user']['info'][] = $two_col_data;
            }
        }

        $collect_date = '';
        if($_result['user']['collect_date']){
            $collect_date = strtotime($_result['user']['collect_date']);

            if ($collect_date > time() || $collect_date < 0) {
                $collect_date = '';
            }
        }
        $_result['user']['collect_date'] = $collect_date;
        if(isset($_result['user']['result'])){
            $_result['user']['result_type'] = 1;
        }
        return $_result;
    }

    /**
     * Notes: 识别身份证信息
     * User: lltyy
     * DateTime: 2021/8/2 10:00
     *
     * @param string $imgPath
     * @param string $templateSign
     * @return array
     */
    public static function ocr_card($imgPath = '', $templateSign = '')
    {
        $baidu_config = new Config(include realpath(__DIR__).'/../../../../config/autoload/zend-baidu.global.php');
        $client = new \AipOcr($baidu_config['baidu']['app_id'], $baidu_config['baidu']['api_key'], $baidu_config['baidu']['aecret_key']);
        $image = file_get_contents($imgPath);
        $front_result = $client->custom($image, array('templateSign'=>$templateSign));
        $field_arr = [
            '姓名' => 'form_name',
            '公民身份号码' => 'form_card',
            '年龄' => 'form_age',
            '出生' => 'form_birth',
            '性别' => 'form_sex',
            '民族' => 'form_nation',
            '住址' => 'form_address',
        ];

        $result = [
            'code' => $front_result['error_code'],
            'message' => $front_result['error_msg'],
            'data' => []
        ];
        if($front_result['error_code'] == 0){
            $ocrContent = $front_result['data']['ret'];
            foreach($ocrContent as $rowInfo){
                //$fieldName = iconv('utf-8', 'gbk', $rowInfo['word_name']);
                $fieldName = $rowInfo['word_name'];
                $fieldValue = $rowInfo['word'];
                $fieldId = $field_arr[$fieldName];
                $newValue = $fieldValue;
                if($fieldId == 'form_birth'){//年龄、出生
                    $date = strtotime($fieldValue); //获得出生年月日的时间戳
                    $newValue = date('Y-m-d',$date);
                    $today = strtotime('today'); //获得今日的时间戳
                    $diff = floor(($today - $date) / 86400 / 365); //得到两个日期相差的大体年数
                    //strtotime加上这个年数后得到那日的时间戳后与今日的时间戳相比
                    $ageValue = strtotime(substr($fieldValue, 6,8) . ' +' . $diff . 'years') > $today ? ($diff + 1) : $diff;
                    $result['data']['form_age'] = $ageValue;
                }elseif($fieldId == 'form_sex'){
                    //$newValue = iconv('utf-8', 'gbk', $fieldValue) == '男' ? '0' : '1';
                    $newValue = $fieldValue == '男' ? '0' : '1';
                }
                $result['data'][$fieldId] = $newValue;
            }
        }
        return $result;
    }
}


?>