<?php
/**
 *
 * @author：llbjj
 * @DateTime：2024/3/19 20:32
 * @Description：
 *
 */

namespace Application\Service\ToolSys;

use Application\Common\Com;
use Laminas\Cache\Exception\ExceptionInterface;
use Laminas\Json\Json;
use Zend\Stdlib\ArrayUtils;

class SyncOcrAnnex extends \Application\Service\BaseService
{
    /**
     * @throws ExceptionInterface
     */
    public function PushOcrAnnex() {
        $annexList = $this->LocalService()->ocrOcrannex->fetchAll([
            'where' => [ 'is_del' => 0, 'ocr_status' => 0],
            'columns' => [ 'annexId' => 'id', 'annexPath' => 'annex_path', 'itemsigId' => 'sig_id', 'patientId' => 'patient_id'],
            'limit' => 10
        ]);

        if(!empty($annexList)) {
            foreach($annexList as $annex) {
                $this->LocalService()->toolSys->pushTextOcr($annex);
                // 更新附件识别的状态
                $this->LocalService()->ocrOcrannex->updateField($annex['annexId'], 'ocr_status', 1);
            }
        }
    }

    /**
     * @throws ExceptionInterface
     */
    public function PushPatientWorkannex() {
        $annexList = $this->LocalService()->itemPatientworkannex->fetchAll([
            'where' => 'ocr_id != 0 and report_type = 0 and lock_state = 0 and ocr_state = 0 and confirm_state = 0 and change_type = 0 and annex_type in (1,4,5) and annex_path != "" and create_time >= "'.strtotime('-1 day').'" ',
            'columns' => [ 'annexId' => 'id', 'annexPath' => 'annex_path', 'itemsigId' => 'itemsig_id', 'patientId' => 'patient_id'],
            'limit' => 20
        ]);

        if(!empty($annexList)) {
            foreach($annexList as $annex) {
                $this->LocalService()->toolSys->pushCustomOcr(ArrayUtils::merge($annex, [
                    'aiKey' => 1
                ]));
                // 更新附件识别的状态
                $this->LocalService()->itemPatientworkannex->updateField($annex['annexId'], 'ocr_state', 2);
            }
        }
    }

    /**
     * Notes: 投放patientFormContentImg表中需要识别的图片
     * User: llbjj
     * DateTime: 2024/5/27 15:45
     *
     */
    public function PushFormAnnex() {
        $collectCategoryData = $this->LocalService()->collectCategory->fetchAll([
            'where' => "is_del = 0 and ocr_type > 0",
            'columns' => ['id', 'category_code', 'ocr_type', 'ai_key']
        ]);

        $itemSignatoryCollecttypeOcrData = $this->LocalService()->itemSignatoryCollecttypeocr->fetchAll([
            'where' => "is_del = 0 and ocr_type > 0",
            'columns' => ['id', 'itemsig_id', 'collect_category_id', 'ocr_type', 'ai_key']
        ]);

        $_signatoryCollectCategoryData = [];
        if(!empty($itemSignatoryCollecttypeOcrData)) {
            foreach($itemSignatoryCollecttypeOcrData as &$item) {
                $_signatoryCollectCategoryData[$item['itemsig_id']][$item['collect_category_id']] = &$item;
            }
        }

        if(!empty($collectCategoryData)) {
            $collectTypeData = [];  // 识别方式
            $_collectCategoryData = [];
            foreach($collectCategoryData as &$collectCategoryDatum) {
                $_collectCategoryData[$collectCategoryDatum['id']] = &$collectCategoryDatum;
                $collectTypeData[$collectCategoryDatum['id']] = &$collectCategoryDatum['ocr_type'];
            }

            $annexList = $this->LocalService()->patientFormContentImg->fetchAll([
                'where' => ' is_lock != 1 and is_form_ocr = 1 and is_del = 0 and ocr_state = 0 and info_collect_type in (' . implode(',', array_keys($collectTypeData)) . ')',
                'columns' => ['annexId' => 'id', 'annexPath' => 'img_src', 'itemsigId' => 'itemsig_id', 'patientId' => 'patient_id', 'itemId' => 'item_id', 'infoCollectType' => 'info_collect_type'],
                'limit' => 20
            ]);

            if(!empty($annexList)) {
                $pushMethodMapOcr = ['1' => 'pushTextOcr', '2' => 'pushTableOcr', '3' => 'pushCustomOcr'];

                foreach($annexList as $annex) {
                    $aiKey = $_collectCategoryData[$annex['infoCollectType']]['ai_key'] ?: 0;
                    $ocrMethodName = $pushMethodMapOcr[$collectTypeData[$annex['infoCollectType']]];

                    if(!empty($_signatoryCollectCategoryData[$annex['itemsigId']][$annex['infoCollectType']])) {
                        $aiKey = $_signatoryCollectCategoryData[$annex['itemsigId']][$annex['infoCollectType']]['ai_key'] ?: 0;
                        $ocrMethodName = $pushMethodMapOcr[$_signatoryCollectCategoryData[$annex['itemsigId']][$annex['infoCollectType']]['ocr_type']];
                    }
                    $this->LocalService()->toolSys->{$ocrMethodName}(ArrayUtils::merge($annex, [
                        'sourceType' => 1,
                        'isDrug' => $_collectCategoryData[$annex['infoCollectType']]['category_code'] == 'DischargeRecord' && $collectTypeData[$annex['infoCollectType']] == 1,
                        'aiKey' => $aiKey
                    ]));
                    // 更新附件识别的状态
                    $this->LocalService()->patientFormContentImg->updateField($annex['annexId'], 'ocr_state', 2);
                }
            }
        }
    }

    /**
     * @throws ExceptionInterface
     */
    public function PullPatientWorkannex() {
        $annexList = $this->LocalService()->itemPatientworkannex->fetchAll([
            'where' => 'ocr_id != 0 and report_type = 0 and lock_state = 0 and ocr_state = 2 and confirm_state = 0 and change_type = 0 and annex_type in (1,4,5) and annex_path != "" ',
            'columns' => [ 'annexId' => 'id', 'itemsigId' => 'itemsig_id', 'patientId' => 'patient_id'],
            'limit' => 50
        ]);

        if(!empty($annexList)) {
            foreach($annexList as $annex) {
                $ocrResult = $this->LocalService()->toolSys->pullCustomOcr($annex);

                if(!empty($ocrResult)) {
                    $this->_handleCheckImg($ocrResult, $annex, 'itemIdentificationresult', 'itemPatientworkannex');
                }
            }
        }
    }

    public function PullFormAnnex() {
        $collectCategoryData = $this->LocalService()->collectCategory->fetchAll([
            'where' => "is_del = 0 and ocr_type > 0",
            'columns' => ['id', 'category_code', 'ocr_type']
        ]);

        $itemSignatoryCollecttypeOcrData = $this->LocalService()->itemSignatoryCollecttypeocr->fetchAll([
            'where' => "is_del = 0 and ocr_type > 0",
            'columns' => ['id', 'itemsig_id', 'collect_category_id', 'ocr_type', 'ai_key']
        ]);

        $_signatoryCollectCategoryData = [];
        if(!empty($itemSignatoryCollecttypeOcrData)) {
            foreach($itemSignatoryCollecttypeOcrData as &$item) {
                $_signatoryCollectCategoryData[$item['itemsig_id']][$item['collect_category_id']] = &$item;
            }
        }


        if(!empty($collectCategoryData)) {
            $collectTypeData = [];
            $_collectCategoryData = [];
            foreach($collectCategoryData as &$collectCategoryDatum) {
                $_collectCategoryData[$collectCategoryDatum['id']] = &$collectCategoryDatum;
                $collectTypeData[$collectCategoryDatum['id']] = &$collectCategoryDatum['ocr_type'];
            }


            $annexList = $this->LocalService()->patientFormContentImg->fetchAll([
                'where' => ' is_lock != 1 and is_form_ocr = 1 and is_del = 0 and ocr_state = 2 and info_collect_type in (' . implode(',', array_keys($collectTypeData)) . ') and create_time > ' . strtotime(date('Y-m-d') . ' -3 day'),
                'columns' => ['annexId' => 'id', 'annexPath' => 'img_src', 'itemsigId' => 'itemsig_id', 'patientId' => 'patient_id', 'itemId' => 'item_id', 'infoCollectType' => 'info_collect_type'],
                'limit' => 50
            ]);

            if(!empty($annexList)) {
                $pullMethodMapOcr = ['1' => 'pullTextOcr', '2' => 'pullTableOcr', '3' => 'pullCustomOcr'];
                $ocrTableMap = ['1' => 'collectText', '2' => 'collectTable', '3' => 'collectCustom'];


                foreach($annexList as $annex) {
                    $ocrMethodName = $pullMethodMapOcr[$collectTypeData[$annex['infoCollectType']]];

                    if(!empty($_signatoryCollectCategoryData[$annex['itemsigId']][$annex['infoCollectType']])) {
                        $ocrMethodName = $pullMethodMapOcr[$_signatoryCollectCategoryData[$annex['itemsigId']][$annex['infoCollectType']]['ocr_type']];
                    }

                    $ocrResult = $this->LocalService()->toolSys->{$ocrMethodName}(ArrayUtils::merge($annex, [
                        'sourceType' => 1
                    ]));

                    if(!empty($ocrResult)) {
                        //保存到对应的识别结果表中
                        $this->LocalService()->{$ocrTableMap[$collectTypeData[$annex['infoCollectType']]]}->save([
                            'content'           => Json::encode(current($ocrResult)),
                            'annex_id'          => &$annex['annexId'],
                            'item_id'           => &$annex['itemId'],
                            'itemsig_id'        => &$annex['itemsigId'],
                            'patient_id'        => &$annex['patientId'],
                            'info_collect_type' => &$annex['infoCollectType']
                        ]);

                        // 更新附件识别的状态
                        $this->LocalService()->patientFormContentImg->updateField($annex['annexId'], 'ocr_state', 1);


                        $this->_handleOtherTask($annex['annexId'], $collectTypeData[$annex['infoCollectType']], $_collectCategoryData[$annex['infoCollectType']]['category_code']);

                        // (出院记录)药物提取保存
                        if ($_collectCategoryData[$annex['infoCollectType']]['category_code'] == 'DischargeRecord') {
                            $drugOcrResult = $this->LocalService()->toolSys->pullTableOcr(ArrayUtils::merge($annex, [
                                'sourceType' => 1
                            ]));

                            $this->LocalService()->collectTable->save([
                                'content'           => Json::encode(current($drugOcrResult)),
                                'annex_id'          => &$annex['annexId'],
                                'item_id'           => &$annex['itemId'],
                                'itemsig_id'        => &$annex['itemsigId'],
                                'patient_id'        => &$annex['patientId'],
                                'info_collect_type' => &$annex['infoCollectType']
                            ]);

                            $this->_handleOtherTask($annex['annexId'], 0, 'Medical');
                        }
                    }
                }
            }
        }
    }

    public function PullExportSas() {
        $exportSasList = $this->LocalService()->exportSas->fetchAll([
            'where' => 'status = 0 and is_del = 0 and type = 1',
            "columns" => ['id', 'item_id', 'category'],
            "limit" => 50,
        ]);

        if(!empty($exportSasList)) {
            foreach ($exportSasList as $exportSas) {
                $result = $this->LocalService()->toolSys->pullExportSas($exportSas);

                if($result['result'] ?? '') {
                    $this->LocalService()->exportSas->isSetInfo(false)->update([
                        'status' => 1,
                        'path' => $result['result']
                    ], [
                        'id' => $exportSas['id'],
                    ]);
                }
            }
        }
    }

    /**
     * Notes: 处理化验单识别结果并保存到对应的数据库中
     * User: llbjj
     * DateTime: 2024/5/27 20:14
     *
     */
    private function _handleCheckImg(array &$ocrResult, array &$annex, string $saveTableName, string $annexTableName) {
        // 处理识别结果
        $ocrResult = current($ocrResult);
        $ocrResult = Com::changeOcrResult($ocrResult);

        //保存到对应的识别结果表中
        $this->LocalService()->{$saveTableName}->insert([
            'workannex_id' => $annex['annexId'],
            'content' => Json::encode([
                'user' => [
                    'info' => $ocrResult
                ]
            ])
        ]);

        // 更新附件识别的状态
        $this->LocalService()->{$annexTableName}->updateField($annex['annexId'], 'ocr_state', 1);
    }

    private function _handleOtherTask($annex_id, $ocrType, $collectCategoryCode) {
        if(in_array($ocrType, [1, 3])) {
            // 全文识别
            $this->LocalService()->swTaskClient->send([
                'svName' => 'itemPatientformimgcontent',
                'methodName' => 'splitImgOcr',
                'params' => [ 'annexId' => $annex_id]
            ]);
        }

        switch ($collectCategoryCode) {
            case 'Medical':
                // 表格识别
                $this->LocalService()->swTaskClient->send([
                    'svName' => 'doctoradviceOriginal',
                    'methodName' => 'handleOcrData',
                    'params' => [ 'annexId' => $annex_id]
                ]);
                break;
        }
    }
}