<?php

namespace Application\Controller;


use Application\Common\Com;
use Application\Common\ImageResizeExtends;
use Application\Common\StatusCode;
use Application\Form\CommonModel;
use Application\Service\Extension\Helper\CurlHelper;
use Application\Service\Extension\Helper\FormHelper;
use Application\Service\Extension\Helper\SDMHelper;
use Application\Service\Extension\Helper\StringHelper;
use Application\Service\Extension\Laminas;
use Application\Service\Extension\Uploader\adapter\Oss;
use Application\Service\Extension\Uploader\ImageUploader;
use EasyWeChat\Kernel\Exceptions\HttpException;
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use EasyWeChat\Kernel\Exceptions\RuntimeException;
use Gumlet\ImageResizeException;
use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\Mvc\MvcEvent;
use Laminas\Stdlib\ArrayUtils;
use Laminas\View\Model\JsonModel;

class CommonController extends AbstractActionController
{
    /** @var string 上传附件接口地址 */
    public const UPLOAD_URL = '/common/upload';
    /** @var string 上传图片接口地址 */
    public const UPLOAD_IMG_URL = '/common/uploadImg';

    /** @var string 加密参数 */
    public const SECRET_KEY = 'yikeen';

    /** @var string[] 需要token验证的接口 */
    public const AUTH_ACTION = [
        'upload', // 上传附件
        'showPic', // 图片预览
        'signFileUrl', // 下载附件路径签名
    ];

    protected function attachDefaultListeners()
    {
        $event = $this->getEventManager();
        $event->attach(MvcEvent::EVENT_DISPATCH, [$this, 'checkLogin'], 99);
        parent::attachDefaultListeners(); // TODO: Change the autogenerated stub
    }

    /**
     * 检查是否登录
     * @param MvcEvent $event
     */
    function checkLogin(MvcEvent $event)
    {
//        $host = "{$_SERVER['REQUEST_SCHEME']}://{$this->getRequest()->getHeader('host')->getFieldValue()}/";
        if (in_array($event->getRouteMatch()->getParam('action'), self::AUTH_ACTION)) {
            if( ( $_COOKIE['thirdAppId'] ?? time() ) != ( $this->LocalService()->config['toolSys']['appId'] ?? '' ) ) {
                if( ( $_REQUEST['bucket'] ?? '' ) != 'login_url'){
                    Laminas::$serviceManager->identity->getIdentityData();
                }
            }
        }
    }

    public function errormsgAction() {
        $code = $this->params()->fromQuery('code');
        // $errData = explode('|', Crypt::blockCipher()->decrypt($code));
        $errData = explode('|', $code);
        echo "<pre>";print_r(file_get_contents(APP_PATH.'/runtime/'.$errData[1].'/'.str_ireplace(':','_', $errData[2]).'_'.$errData[0].'.log'));exit;
    }

    public function qrcodeAction() {
        $filePath = APP_PATH . '/data/qrcode_258.jpg';
        ImageResizeExtends::createFromString(file_get_contents($filePath))->output();
        die;
    }
    
    /**
     * 上传附件
     * @url http://xxx.com/common/upload
     * @return JsonModel
     * @throws \League\Flysystem\FilesystemException
     * @throws \OSS\Core\OssException
     */
    public function uploadAction(): JsonModel
    {
        $uploader = new ImageUploader();
        $config = Laminas::$app->getConfig();
        $uploader->setConfig([
            'allowExtensions' => ArrayUtils::merge($config['image_uploader']['allowFileExtensions'] ?? [], $config['image_uploader']['allowExtensions'] ?? []),
            'maxSize' => $config['image_uploader']['fileMaxSize'],
            'driver' => ImageUploader::DRIVER_OSS,
        ]);

        return $this->RenderApiJson()->Success($uploader->save($uploader::getInstanceByName('file')));
    }

    /**
     * 显示图片
     * @throws ImageResizeException
     */
    public function showPicAction()
    {
        if($this->request->isPost()){
            $imgPath = $this->params()->fromPost('path');
            $bucket = $_POST['bucket'] ?: 'yikeen';
            $style = $_POST['style'] ?: 'thumb';
            //******************正则匹配  path、bucket 和 style 参数 【后端先做兼容，前端后续会拆分传输相应的参数】*****************
            preg_match_all('/(?:\?|&)([^&=]+)=([^&]+)/', $imgPath, $matches, PREG_SET_ORDER);
            if(!empty($matches)) {
                $params = [];
                foreach ($matches as $match) {
                    $key = urldecode($match[1]);
                    $value = urldecode($match[2]);
                    if(empty($value)) continue;
                    $params[$key] = $value;
                }
                $imgPath = $params['path'];
                if(isset($params['bucket'])) $bucket = $params['bucket'];
                if(isset($params['style']) && $params['style'] != 'thumb') $style = $params['style'];
            }

            //******************************************************************************************************
        }else{
            $imgPath = trim($this->params()->fromQuery("path", ''), '/');
            $bucket = $this->params()->fromQuery("bucket", 'yikeen');
            $style = $this->params()->fromQuery("style", 'thumb');
        }

        $bucket = $bucket == 'tmp' || $bucket == 'login_url' ? 'yikeen' : $bucket;

        $fileUpLoader = new Oss(Laminas::$app->getConfig()['image_uploader'], $bucket);
        // style => ['iphone' => 最不清楚的, 'sample' => 还挺清楚的, 'origin' => 原图, 'thumb' => 高度为100的缩略图]
        $imgUrl = $fileUpLoader->getSignUrl($imgPath, $style);

        $imgContent = file_get_contents($imgUrl);
        if(!$imgContent) {
            $imgUrl = $fileUpLoader->getOriginUrl($imgPath);
            $imgContent = file_get_contents($imgUrl);

            if(!in_array($style, ['origin', 'ocr'])) {
                $imgStyleMapWidth = [
                    'sample' => '1000',
                    'thumb' => '80',
                    'iphone' => '400',
                ];
                $imageResizeExtends = ImageResizeExtends::createFromString($imgContent);
                // 压缩图片
                $imageResizeExtends = $imageResizeExtends->resizeToWidth($imgStyleMapWidth[$style]);
                $imageResizeExtends->output();
                exit;
            }
        }

        if($_COOKIE['thirdAppId'] ?? '') {
            $imageResizeExtends = ImageResizeExtends::createFromString($imgContent);
            // 原图显示，检测图片的大小
            $imgSize = Com::customFilesize($imgUrl);
            if ($imgSize / 1024 / 1024 > 20) {
                // 压缩图片
                $imageResizeExtends = $imageResizeExtends->resizeToWidth(3000);
            }
            $imageResizeExtends->outputLength(null, null, get_headers($imgUrl, 1)['Content-Length']);
            exit;
        }

        echo $imgContent;die;
    }

    /**
     * Notes: 在线文件下载
     * User: llbjj
     * DateTime: 2024/5/31 9:11
     *
     * @throws \OSS\Core\OssException
     * @throws \OSS\Http\RequestCore_Exception
     */
    public function downloadAction() {
        $filePath = trim($this->params()->fromQuery('path', ''), '/');
        $fileName = $this->params()->fromQuery('fileName', '');
        $bucket = $this->params()->fromQuery('bucket', 'yikeen');

        $fileUpLoader = new Oss(Laminas::$app->getConfig()['image_uploader'], $bucket);
        $fileUpLoader->downloadOnline($filePath, $fileName);
    }

    /**
     * @note 文件签名
     * @return JsonModel
     */
    public function signFileUrlAction(): JsonModel
    {
        $filePath = $this->params()->fromPost('path');
        $bucket = $this->params()->fromPost('bucket', 'yikeen');

        $filePath = str_ireplace(Oss::getUploadDomain(), '', $filePath);

        $fileUpLoader = new Oss(Laminas::$app->getConfig()['image_uploader'], $bucket);

        return $this->RenderApiJson()->Success([
            'signUrl' => $fileUpLoader->getSignUrl($filePath),
        ]);
    }

    /**
     * 上传图片
     * @url http://xxx.com/common/uploadImg
     * @return JsonModel
     * @throws \League\Flysystem\FilesystemException
     * @throws \OSS\Core\OssException
     */
    public function uploadImgAction(): JsonModel
    {
        $uploader = new ImageUploader();
        $config = Laminas::$app->getConfig();
        $uploader->setConfig([
            'allowExtensions' => $config['image_uploader']['allowExtensions'],
            'maxSize' => $config['image_uploader']['imgMaxSize'],
            'driver' => ImageUploader::DRIVER_OSS,
        ]);

        return $this->RenderApiJson()->Success($uploader->save($uploader::getInstanceByName('file')));
    }

    /**
     * 渲染表单组件
     *  - TableButton (表格按钮)
     */
    public function renderFormComponentAction(): JsonModel
    {
        $componentName = $this->params()->fromPost('component', '');
        $item_id = $this->params()->fromPost('item_id',0);//副项目ID
        //获取该项目下设置的化验单采集时间类型
        $dateType = 1;
        if(!empty($item_id)){
            $dateType = Laminas::$serviceManager->itemCheckdate->getOneFieldVal('date_type','is_del = 0 and item_id = '.$item_id);
            $dateType = empty($dateType) ? 1 : $dateType;
        }
        $dateType = intval($dateType);
        $model = new CommonModel();
        $datas = $model->render($componentName,$dateType);
        return $this->RenderApiJson()->Success($datas,'',['dateType'=>$dateType]);
    }

    /**
     * 验证公式格式
     * @return JsonModel
     */
    public function formatExpressionAction(): JsonModel
    {
        // 表单变量 //计算符号
        list($constVar, $condition) = FormHelper::getCalculateConditionWithClass();

        $expression = str_replace(' ', '', $_POST['expression']);

        // 正则验证
        $pregConst = implode('|', $constVar);
        preg_match("/^($pregConst)=(.*)/", $expression, $match);

        if (!$match || count($match) != 3 && $match[2] == '') {
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, "语法错误 `a = b + c` 才是正确的格式, 或者你没有定义好的变量当作开头!!");
        }

        $expressionLen = strlen($expression);

        $res = [];
        for ($i = 0; $i < $expressionLen; $i++) {
            if ($expression[$i] === '(') {
                $res[] = $expression[$i];
            } elseif ($expression[$i] === ')') {
                $res[] = $expression[$i];
            } elseif (in_array($expression[$i], $condition)) {
                $res[] = $expression[$i];
            } else {
                $res[] = "$expression[$i]";
            }
        }

        $parseExpression = (implode('', $res));
        $exStr = array_filter(explode(' ', $parseExpression));

        return $this->RenderApiJson()->Success([
            'expression' => implode('', $exStr)
        ]);
    }

    /**
     * @return JsonModel
     */
    public function calculateExpressionAction(): JsonModel
    {
        // 防止被除数写0, eval报错好像try catch抓不到。
        register_shutdown_function(function () {
            $err = error_get_last();
            if (isset($err['message']) && $err['message'] == 'Division by zero') {
                $msg = ['code' => 60011, 'msg' => '请输入正确的数字'];
                die(json_encode($msg));
            }
        });

        try {
            $formId = $this->params()->fromPost('id');

            $expression = $this->LocalService()->itemForm->fetchOne([
                'where' => ['id' => $formId]
            ])['expression'];

            if (!$expression) {
                return $this->RenderApiJson()->Success([], '该表单暂未设置公式。');
            }

            $expression = FormHelper::getFormatFormExpression($expression);
            $runStr = $runExpression = '';

            $constVar = FormHelper::getCalculateConditionWithClass()[0];

            foreach ($expression['expression'] as $v) {
                if (in_array($v, $constVar)) {
                    $runStr .= '$' . "$v = " . floatval($this->params()->fromPost($v) ?: 0) . '; ';
                    $runExpression .= '$' . $v;
                } else {
                    $runExpression .= $v;
                }
            }

            $func = <<<EOL
            function run() {
                $runStr;
                return $runExpression;
            }
EOL;

            eval($func);
            $res = round(run(), 2);
        } catch (\Throwable $e) {
            $res = -1;
        }

        return $this->RenderApiJson()->Success([
            'res' => $res
        ]);
    }

    /**
     * 计算公式
     * @url: http://xxx.com/common/v2/calculateExpression
     * @return JsonModel
     */
    public function calculateExpressionV2Action(): JsonModel
    {
        $values = $this->params()->fromPost();
        $expression = Laminas::$serviceManager->itemForm->fetchOne([
            'where' => ['id' => $this->params()->fromPost('id')]
        ])['expression'];

        $expressionArr = explode('=', $expression);
        unset($expressionArr[0]);
        $expression = implode('=', $expressionArr);

        $exec = SDMHelper::app()->expression->setExpression($expression)->setValues($values)->execute();

        return $this->RenderApiJson()->Success([
            'res' => $exec->getExecuteVal(),
            'message' => '',
            'exStr' => $exec->getExecuteCompile(),
            'values' => $values
        ]);
    }

    /**
     * 获取上一个小程序版本
     * @url http://xxx.com/common/miniVersion
     * @return JsonModel
     * @throws HttpException
     * @throws InvalidArgumentException
     * @throws InvalidConfigException
     * @throws RuntimeException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function miniVersionAction(): JsonModel
    {
        $platform = $this->getRequest()->getPost('platform');
        $refresh = $this->getRequest()->getPost('refresh');

        $token = Laminas::$serviceManager->wechat->getMiniApp($platform)->access_token->getToken();
        $cacheKey = "applets:" . $platform;

        if (($cache = Laminas::$serviceManager->redisExtend->getRedisInstance()->get($cacheKey)) && !$refresh) {
            $data = StringHelper::jsonDecode($cache);
            return $this->RenderApiJson()->Success([
                'last_version' => $data['version_list'][0]['user_version'],
                'cached_at' => $data['cached_at']
            ]);
        } else {
            $response = CurlHelper::getMiniAppHistoryVersion($token['access_token']);
            if (!$response) {
                return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, "获取版本数据出错啦!");
            }

            $data = StringHelper::jsonDecode($response);
            if ($data['errcode'] == 0) {
                $data['cached_at'] = time();
                Laminas::$serviceManager->redisExtend->getRedisInstance()->setex($cacheKey, 60*60*2, json_encode($data)); // 缓存两个小时
                return $this->RenderApiJson()->Success([
                    'last_version' => $data['version_list'][0]['user_version'] ?? 99999, // 取不到给个默认值
                    'cached_at' => $data['cached_at']
                ]);
            } else {
                return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, $data['errmsg']);
            }
        }
    }

    /**
     * 用于微信公众号和受试者手机号绑定
     * @url xxx.com/common/patient-mobile
     */
    public function patientMobileAction()
    {
        $mobile = $this->params()->fromQuery('mobile');
        $openid = $this->params()->fromQuery('openid');
        $sign = $this->params()->fromQuery('sign');

        if ($sign !== md5($mobile . self::SECRET_KEY)) {
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, 'sign error.');
        }

        // 不传openid 是查询当前手机号是否属于受试者
        if (!$openid) {
            if ($query = Laminas::$serviceManager->patient->fetchOne([
                'where' => ['patient_tel' => $mobile, 'is_del' => 0]
            ])) {
                if ($query['openid']) {
                    die('-1'); // 已经绑定用户了
                } else {
                    die('1'); // 找不到手机号
                }
            }
            die('0');
        }

        Laminas::$serviceManager->patient->isSetInfo(false)->update(['openid' => $openid], ['patient_tel' => $mobile]);
        return $this->RenderApiJson()->Success();
    }


    public function editSendAction() {
        $com = new Com();
//        $id = $_POST['id'] ?:1;
        $item_id = $_POST['item_id'] ?: 0;
        $patient_id = $_POST['patient_id'] ?: 0;
        $itemsig_id = $_POST['itemsig_id'] ?: 0;
        $date = $_POST['date'] ? : 0;
        if (empty($item_id) || empty($patient_id)) return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, '参数不正确');
        //验证链接
        if((strtotime(date('Y-m-d',$date)) != strtotime(date('Y-m-d'))) || empty($date)){
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, '信息已过期');
        }


        $whereMess['where'] = [
            'is_del' => 0,
            'item_id' => $item_id,
        ];
        $whereMess['columns'] = ['item_id','content'];
        $itemMessageSendInfos = $this->LocalService()->itemMessageSend->fetchOne($whereMess);
        if (empty($itemMessageSendInfos)) return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, '后台推送新增表单还未设置');

//        if (empty($itemMessageSendInfos)){
//            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, '信息已过期');
//        }
//        $current_time = date('G');
//        if ($current_time < $itemMessageSendInfos['send_time']){
//            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, '信息已过期');
//        }

        $fieldId = implode(',',array_column(json_decode($itemMessageSendInfos['content'],true),'id'));


        $itemMessageFieldData = $this->LocalService()->itemMessageField->fetchAll(['where' => 'is_del=0 and item_id='.$item_id.' and (id in('.$fieldId.') or parent in('.$fieldId.'))','order' => ['mess_order']]);
        $relation = [];
        if(!empty($itemMessageFieldData)){
            $relationFieldDatas = [];
            $relationFieldData = [];
            $relationIdArr = [];
            $relationId = array_filter(array_column($itemMessageFieldData,'relation_id'));
            if (!empty($relationId)){
                $relationIds = implode(',',$relationId);
                $relationFieldData = $this->LocalService()->itemMessageField->fetchAll(['where' => 'is_del=0 and item_id='.$item_id.' and (id in('.$relationIds.') or parent in('.$relationIds.'))','order' => ['mess_order']]);

            }
            if(!empty($relationFieldData)){
                $relationFieldData = $com->getTree($relationFieldData,0,0,2,'parent');
                $relationIdArr = array_column($relationFieldData,'id');
            }
            $relationFieldDatas = $this->LocalService()->itemMessageSend->getPatientattrTemplate($relationFieldData);
            $unsetArr = [];
            foreach ($itemMessageFieldData as $itemMessageFieldDataK=>$itemMessageFieldDataV){
                if (!empty($itemMessageFieldDataV['relation_id'])){
                    $relationIdData = explode(',',$itemMessageFieldDataV['relation_id']);
                    foreach ($relationFieldDatas as $relationFieldDatasK=>$relationFieldDatasV) {
                        if (in_array($relationFieldDatasV['id'],$relationIdData)){
//                            $relationFieldDatasV['prop'] = $getTypeCode[$itemMessageFieldDataV['id']];
                            $relationFieldDatasV['prop'] = $relationFieldDatasV['id'];//$itemMessageFieldDataV['parent'].'-'.$itemMessageFieldDataV['id'].'-'.$relationFieldDatasV['id'];
                            $relation[$itemMessageFieldDataV['parent']][$itemMessageFieldDataV['id']][] = $relationFieldDatasV;
                        }

                    }
                }
                if (in_array($itemMessageFieldDataV['id'],$relationIdArr)){
                    unset($itemMessageFieldData[$itemMessageFieldDataK]);
                }
            }
        }

        !empty($itemMessageFieldData) && $itemMessageFieldData = $com->getTree($itemMessageFieldData,0,0,2,'parent');
        $FormFileDatas = $this->LocalService()->itemMessageSend->getPatientattrTemplate($itemMessageFieldData);
        $FormFileData =array_values($this->Introduce('MessageSend',['item_id'=>$item_id,'messageSend'=>$FormFileDatas,'MINI_PATIENT'=>1]));

        $itemMessageSendPatientWhere = [
            'where' => 'is_del=0 and is_write=0 and item_id='.$item_id.' and patient_id='.$patient_id.' and FROM_UNIXTIME(create_time ,"%Y-%m-%d")="'.date('Y-m-d').'"',
            'columns'=>['item_id','content','itemsig_id','patient_id','id'],
        ];
        $itemMessageSendInfo = $this->LocalService()->itemMessageSendPatient->fetchOne($itemMessageSendPatientWhere);
        if (!empty($itemMessageSendInfo)){
            $itemInfoName = $this->LocalService()->itemInfo->getOneFieldVal('name','id='.$item_id)?:'';
            $patientInfo = $this->LocalService()->patient->fetchOne(['where'=>'is_del=0 and id='.$patient_id,'columns'=>['id','patient_name','patient_number']]);
            $itemMessageSendInfo['itemInfoName'] = $itemInfoName;
            $itemMessageSendInfo['patient_name'] = '';
            if (!empty($patientInfo)){
                if (!empty($patientInfo['patient_name'])){
                    $itemMessageSendInfo['patient_name'] = $patientInfo['patient_name'];
                }
                if (!empty($patientInfo['patient_number'])){
                    $itemMessageSendInfo['patient_name'] .= '【'.$patientInfo['patient_number'].'】';
                }
            }

            if  (!empty($itemMessageSendInfo['content'])){
                $itemMessageSendInfo['content'] = json_decode($itemMessageSendInfo['content'],true);
            }else{
                $itemMessageSendInfo['content'] = [];
            }

        }else{
            $itemMessageSendInfo = ['is_write'=>1];
        }

//        if (empty($itemMessageSendInfo)){
//            $whereMess['where'] = 'is_del=0 and item_id = ' . $item_id;
//            $whereMess['columns'] = ['item_id','content'];
//            $itemMessageSendInfo = $this->LocalService()->itemMessageSend->fetchOne($whereMess);
//            if (!empty($itemMessageSendInfo)){
//                $itemMessageSendInfo['id'] = 0;
//                $itemMessageSendInfo['patient_id'] = $patient_id;
//                $itemInfoName = $this->LocalService()->itemInfo->getOneFieldVal('name','id='.$item_id)?:'';
//                $patientInfo = $this->LocalService()->patient->fetchOne(['where'=>'is_del=0 and id='.$patient_id,'columns'=>['id','patient_name','patient_number']]);
//
//                $itemMessageSendInfo['itemInfoName'] = $itemInfoName;
//                $itemMessageSendInfo['patient_name'] = '';
//                if (!empty($patientInfo)){
//                    if (!empty($patientInfo['patient_name'])){
//                        $itemMessageSendInfo['patient_name'] = $patientInfo['patient_name'];
//                    }
//                    if (!empty($patientInfo['patient_number'])){
//                        $itemMessageSendInfo['patient_name'] .= '【'.$patientInfo['patient_number'].'】';
//                    }
//                }
//
//                if  (!empty($itemMessageSendInfo['content'])){
//                    $itemMessageSendInfo['content'] = json_decode($itemMessageSendInfo['content'],true);
//                }else{
//                    $itemMessageSendInfo['content'] = [];
//                }
//            }else{
//                $itemMessageSendInfo = [];
//            }
//        }else{
//            $itemMessageSendInfo = ['is_write'=>1];
//        }

        $data['itemMessageSendInfo'] = $itemMessageSendInfo;
        $data['FormFileData'] =$FormFileData;
        $data['relation'] =$relation;

        return $this->RenderApiJson()->Success($data);


    }

    public function savePatientSendAction() {
        $id = $newData['id'] = $_POST['id'] ?: 0;
        $newData['item_id'] = $_POST['item_id'] ?: 0;
        $newData['patient_id'] = $_POST['patient_id'] ?: 0;
        $newData['itemsig_id'] = $_POST['itemsig_id'] ?: 0;
        $newData['content'] = $_POST['content'] ?: '';
        $newData['create_user_id'] = $newData['update_user_id'] = $_POST['user_id'] ?: 0;
        $date = $_POST['date'] ? : 0;
        $com = new Com();
        if (empty($newData['item_id']) || empty($newData['content']) || empty($newData['patient_id'])){
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, '参数不正确');
        }
        //验证链接
        if((strtotime(date('Y-m-d',$date)) != strtotime(date('Y-m-d'))) || empty($date)){
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, '信息已过期');
        }
        $itemMessageSendInfo = $this->LocalService()->itemMessageSend->fetchOne(['where'=>'is_del=0 and item_id='.$newData['item_id']]);
        if (empty($itemMessageSendInfo)){
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, '信息已过期');
        }
        $current_time = date('G');
//        if ($current_time < $itemMessageSendInfo['send_time']){
//            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, '信息已过期');
//        }


        $checkSave = [
            'item_id'=>$newData['item_id'],
            'sendPatientData'=>$newData['content'],
        ];

        //没有填写数据
//        $resultCheckSave = $this->LocalService()->itemMessageSend->checkSend($checkSave);
//        if (empty($resultCheckSave)) return $this->RenderApiJson()->Success();
        $itemMessageSendPatientWhere = [
            'where' => 'is_del=0 and item_id='.$newData['item_id'].' and patient_id='.$newData['patient_id'].' and FROM_UNIXTIME(create_time ,"%Y-%m-%d")="'.date('Y-m-d').'"',
            'columns'=>['item_id','content','itemsig_id','patient_id','id'],
        ];
        $itemMessageSendPatientInfo = $this->LocalService()->itemMessageSendPatient->fetchOne($itemMessageSendPatientWhere);
        if(empty($itemMessageSendPatientInfo) || !empty($itemMessageSendPatientInfo['is_write'])) return $this->RenderApiJson()->Success();


        $itemMessageFieldData = $this->LocalService()->itemMessageField->fetchAll(['where' => 'is_del=0 and item_id='.$newData['item_id'],'order' => ['mess_order']]);
        $itemMsgParent = [];
        $itemMsgParents = [];
        if (!empty($itemMessageFieldData)){
            $itemMsgParents = array_column($itemMessageFieldData,null,'id');
            foreach ($itemMessageFieldData as $itemMessageFieldDataK=>$itemMessageFieldDataV){
                if (empty($itemMessageFieldDataV['parent']) && $itemMessageFieldDataV['is_required'] == 1){
                    $itemMsgParent[] = $itemMessageFieldDataV['id'];
                }
            }

            $itemMessageFieldData = $com->getTree($itemMessageFieldData,0,0,2,'parent');
        }

//        !empty($itemMessageFieldData) && $itemMessageFieldData = $com->getTree($itemMessageFieldData,0,0,2,'parent');
        $FormFileDatas = $this->LocalService()->itemMessageSend->getPatientattrTemplate($itemMessageFieldData);


        $contentField = $newData;
        if (!empty($newData['content'])){
            $newContentData = json_decode($newData['content'],true);
            foreach ($newContentData as $newContentDataK=>$newContentDataV){
                $var_name = isset($itemMsgParents[$newContentDataV['id']]['var_name'])?$itemMsgParents[$newContentDataV['id']]['var_name']:'';
                $names = isset($itemMsgParents[$newContentDataV['id']]['name'])?$itemMsgParents[$newContentDataV['id']]['name']:'';
                if (in_array($newContentDataV['id'],$itemMsgParent) && empty($newContentDataV['value'])){
                    return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, '【'.$names.'】：不能为空');
                }
                $contentField[$var_name] = $newContentDataV['value'];
            }
            //必填写都填写则为已完成
//            $newData['is_complete'] = 1;
            $newData['is_write'] = 1;

            unset($contentField['content']);

        }
//        echo '<pre>';print_r($contentField);die;


        $FormFileData =$this->Introduce('MessageSendPatient',['item_id'=>$newData['item_id'],'messageSend'=>$FormFileDatas]);
//        $newData['update_user_id'] = $newData['user_id'];
//        $newData['create_user_id'] = $newData['user_id'];
        empty($newData['id']) && $newData['id'] = $itemMessageSendPatientInfo['id'];
        $newData['write_time'] = time();
//                echo '<pre>';print_r($FormFileData);die;
        $result = $this->LocalService()->itemMessageSendPatient->save($newData);
        unset($newData['write_time']);
        unset($newData['update_user_id']);
        $realname = $this->LocalService()->adminUser->getOneFieldVal('realname','is_del=0 and id='.$newData['create_user_id'])?:'';
//        unset($newData['create_user_id']);
        $contentField['realname'] = $realname;
        $contentField['data_type_flag'] = 1;
        if (!empty($result)) $this->LocalService()->log->saveFileLog($newData['id'],'MessageSendPatient',$contentField,0,'暂无说明',$newData['item_id'],'',['item_id'=>$newData['item_id'],'messageSend'=>$FormFileData]);

        return $this->RenderApiJson()->Success();

    }
    //引入
    private function Introduce($formValidator, array $params = []){
        $path=APP_PATH.'/formData/';
        $fromMap=include $path.'formMap.php';
        $fromData=include $path.ucfirst($formValidator).'Data.php';
        if (!empty($fromData)){
            if(is_callable($fromData)) return $fromData($params);
            return $fromData;
        }else{
            return [];
        }
    }


}
