<?php

namespace Application\Service;

use Application\Common\Enum;
use Application\Service\DB\Dictionary\Form;
use Application\Service\Extension\Helper\ArrayHelper;
use Application\Service\Extension\Helper\DataHelper;
use Application\Service\Extension\Helper\StringHelper;
use Application\Service\Extension\Laminas;
use Closure;
use EasyWeChat\Kernel\Exceptions\Exception;
use Interop\Container\ContainerInterface;
use Laminas\Validator\Exception\InvalidArgumentException;

class Logs extends BaseService {
    protected $redisObj;
    const logRedisListKey = 'logFileKey';
    protected $logFilePath; // 日志记录文件路径
    protected $formFieldPath;   // 表单结构配置路径
    protected $eventForm;   // 事件来源
    protected $target;  // 表单结构数据对应的键值（表单结构文件为二维数组）
    protected $relationTarget;
    protected $logFileName;    //日志记录文件名称
    protected $formFieldData;   // 表单结构数据
    protected $eventName;   // 事件说明->formMap.php
    protected $fnParams;    // 如果表单结构文件返回的是一个函数，则个fnParams为这个函数的参数数组
    protected $logFileContent;  // 日志文件的内容
    /**
     * eventForm 闭包函数
     * @var Closure|null
     */
    protected ?Closure $callableEventForm = null;

    /**
     * 表单日志存储eventForm
     * @var string|null
     */
    protected ?string $saveEventForm = null;

    /**
     * 表单id
     * @var int|null
     */
    protected ?int $formId = null;

    /**
     * @var array
     */
    protected array $newData = [];

    /**
     * 是否展示删除详情
     * @var bool
     */
    private bool $isDeleteDetail = false;

    /** @var int 项目id */
    private int $itemId = 0;

    /**
     * Operate create.
     */
    public const OPERATE_CREATE = 0;
    /**
     * Operate edit.
     */
    public const OPERATE_EDIT = 1;
    /**
     * Operate delete.
     */
    public const OPERATE_DELETE = 2;

    /**
     * 清空操作
     */
    public const OPERATE_FLUSH = 4;

    public function __construct(ContainerInterface $container)
    {
        parent::__construct($container);

        $this->redisObj = $this->LocalService()->redisExtend->setDatabase(13);
        $this->getLogFilePath();
        $this->getFormFieldPath();
    }

    /**
     * @desc 获取随机文件名
     * @param string $ext ,后缀
     * @return array,返回文件名及key
     */
    public function getRandomName($ext = 'txt') {
        $new_name = date('YmdHis');
        for ($i = 0; $i < 10; $i++) {
            $new_name .= chr(mt_rand(65, 90));
        }
        $key = uniqid() . $new_name;
        $data = $key . '.' . $ext;
        return $data;
    }

    /**
     *
     *创建文件,写内容
     * @param string $fileName
     * @param string $content
     * @return true|false
     */
    public function setFileContents($fileName, $content) {
        $newPath = $this->logFilePath.$fileName;
        $result = file_put_contents( $newPath, $content);
        return $result;
    }

    public function setIsDeleteDetail(bool $isDetail = false): Logs
    {
        $this->isDeleteDetail = $isDetail;
        return $this;
    }

    /**
     *
     *读取文件内容
     * @param string $fileName
     * @param string $content
     * @return
     */

    public function getFileContents($fileName) {
        return (is_file($fileName) and file_exists($fileName))? file_get_contents( $fileName ) : '';
    }

    /**
     * 用于表单处理做的兼容
     * @param string $formName
     * @return $this
     */
    public function setSaveEventForm(string $formName): Logs
    {
        $this->saveEventForm = $formName;
        return $this;
    }

    /**
     * 用于表单处理做的兼容
     * @param  int  $formId
     * @return $this
     */
    public function setFormId(int $formId): Logs
    {
        $this->formId = $formId;
        return $this;
    }

    public function setNewData(array $newData)
    {
        $this->newData = $newData;
        return $this;
    }

    public function setItemId(int $itemId = 0)
    {
        $this->itemId = $itemId;
        return $this;
    }


    /**
     * $event_id 操作事件ID
     * $event_from 操作表名称
     * $new_data 新数据数组
     * $oper_type  操作类型：0：新增；1：编辑；2：删除；3：计划任务
     * $log_remark 操作说明，如果是删除操作，log_remark为删除的描述
     * $item_id 项目id
     * $relationForm 例如：检查项表单属性字典项，属性类别为单选、多选、下拉时，需要关联填写选项表单（接口中content表示选项信息，暂时固定为：content），表单结构：aData.php=>['attrForm'=>[], 'optionForm'=>[]],选项信息以json形式存放， 记录日志时，$relationForm = 'a.optionForm'
     * 无返回值
     * */
    public function saveFileLog($event_id,$event_from,$new_data=[],$oper_type=0, $log_remark='暂无说明',$item_id = 0, string $relationForm = '', Array $fnParams = []) {
        $item_id = $item_id ?: $this->itemId;
        $old_data = [];
        if(($oper_type != 2) && empty($new_data)) return false;
        // 如果是编辑，则比较前后数据是否做了变动，没有变动，则返回false
        $new_data = ArrayHelper::merge($new_data, $this->newData);
        if(isset($new_data['old_data_str'])) unset($new_data['old_data_str']);
        if($oper_type == 1){
            $old_data = json_decode($_POST['old_data_str'], TRUE) ?: [];
            $changeArr = $this->_getChangeData($old_data, $new_data);
            if(empty($changeArr)) return false;
        }

        if($oper_type == 3) {
            $arr['user_id'] = 0;
            $arr['user_realname'] = '计划任务';
            $arr['log_type'] = 0;
        } else {
            if (isset($new_data['create_user_id']) && isset($new_data['realname']) && isset($new_data['data_type_flag'])){
                //模板推送
                $arr['user_id'] = isset($new_data['create_user_id'])?$new_data['create_user_id'] : 0;
                $arr['user_realname'] = isset($new_data['realname'])?$new_data['realname'] : 0;
                $arr['log_type'] = 3;
            }else{
                $arr['user_id'] = $this->LocalService()->identity->getId();
                $arr['user_realname'] = $this->getUserNameAndPlatform()['user_realname'];
                $arr['log_type'] = $this->getUserNameAndPlatform()['platform'];
            }

//            $arr['user_realname'] = $this->LocalService()->identity->getRealName();
//            $arr['log_type'] = strtolower($this->LocalService()->identity->getPlatform()) == 'pc' ? 0 : 3;  // 操作平台类型：0后台，1real 3小程序
        }
        $itemsig_id = 0;
        if(isset($new_data['itemsig_id'])){
            $itemsig_id = $new_data['itemsig_id'];
        } elseif (isset($new_data['patient_id'])) {
            $itemsig_id = $this->LocalService()->patient->getOneFieldVal(
                'itemsig_id',
                "id = {$new_data['patient_id']}"
            );
        }

//        var_dump($getItemsigId);die;
//        if(isset($new_data['patient_id']))
        $arr['log_url'] = $_SERVER['REQUEST_URI'];
        $arr['log_ip'] = $_SERVER['REMOTE_ADDR'];
        $arr['create_time'] = time();
        $arr['old_data'] = $old_data;   // 操作前的数据数组
        $arr['fnParams'] = $fnParams;

        $arr['item_id'] = $item_id;
        $arr['event_id'] = $event_id;
        $arr['event_from'] = $this->getEventForm($event_from);
        $arr['new_data'] = $new_data;
        $arr['oper_type'] = $oper_type;
        $arr['log_remark'] = $log_remark;
        $arr['relation_form'] = $relationForm;
        $arr['role'] = ($event_from == 'ItemIdentificationresultchange') ? '图片审核员' : Laminas::$serviceManager->realRole->getRole($item_id,$itemsig_id);
        $content = serialize($arr);
        if($this->LocalService()->config['swAsyncTask']['log']) {
            // 开启了日志异步任务
            $this->LocalService()->swLogClient->send($content);
        }else{
            // $this->saveLogToFile($content);
            try{
                $this->saveLogToDb($content);
            }catch (\Exception $e){
                $this->saveLogToFile($content);
                throw $e;
            }
        }
    }

    /**
     * 获取eventForm
     * @param $eventForm
     * @return array|string
     * @throws \Exception
     */
    private function getEventForm($eventForm)
    {
        if (is_array($eventForm)) {
            return $eventForm;
        } elseif (is_string($eventForm)) {
            return ucfirst($eventForm);
        }

        throw new \Exception("不支持的类型~~");
    }

    /**
     * Notes: 将日志信息缓存到文件中，并将文件名称追加到redis队列中
     * DateTime: 2022/5/25 14:51
     *
     * @param string $fileContent
     */
    public function saveLogToFile(string $fileContent){
        $fileName = $this->getRandomName();
        $this->logFileName = $fileName;
        if($this->setFileContents($fileName, $fileContent)) $this->_pushRedis();
    }

    /**
     * Notes: 获取日志文件地址
     * DateTime: 2022/6/3 9:32
     *
     */
    public function getLogFilePath(){
        $logPath = $this->LocalService()->config['logPath'];
        $this->logFilePath = $logPath ?: APP_PATH.'/data/log/';
        if(!file_exists($this->logFilePath)){
            $result = mkdir($this->logFilePath, 0777, true);
            if(!$result){
                throw new InvalidArgumentException("日志记录文件路径【".$this->logFilePath."】创建失败！");
            }
        }
    }

    /**
     * Notes: 从redis中获取日志记录文件，并返回日志文件内容
     * DateTime: 2022/6/3 9:34
     *
     * @return false|string
     */
    public function getLogContentFromRedis(){
        $fileName = $this->_popRedis();
        if(empty($fileName)) return '';

        $filePath = $this->logFilePath . $fileName;
        if (!file_exists($filePath)) {
            throw new InvalidArgumentException("日志文件【{$fileName}】不存在！");
        }
        $this->logFileName = $fileName;
        return $this->getFileContents($filePath);
    }

    /**
     * Notes: 获取表单结构配置路径
     * DateTime: 2022/6/3 9:37
     *
     */
    public function getFormFieldPath(){
        $path = $this->LocalService()->config['formConfigPath'];
        $this->formFieldPath = $path ?: APP_PATH.'/formData/';
        if(!file_exists($this->formFieldPath)){
            $this->_pushRedis();
            throw new InvalidArgumentException("表单结构配置路径【{$this->formFieldPath}】不存在！");
        }
    }

    /**
     * Notes: 根据模块名称获取表单结构内容
     * DateTime: 2022/6/3 9:57
     *
     * @param $eventName
     */
    public function getFormFieldData(bool $delFile = false)
    {
        // 表单配置结构文件不存在且为异步日志，则将从redis中取出的文件名称重新放入redis中
        if(!file_exists($this->formFieldPath.$this->eventForm.'Data.php')){
            if(!empty($this->logFileName) and $delFile) $this->_pushRedis();
            throw new InvalidArgumentException("表单结构配置文件【{$this->eventForm}Data.php】不存在！");
        }
        $this->formFieldData =  include $this->formFieldPath.$this->eventForm.'Data.php';//数据表里配置的字段
        if(is_callable($this->formFieldData)) $this->formFieldData = ($this->formFieldData)($this->fnParams);
    }

    /**
     * Notes: 设置表单来源名称
     * DateTime: 2022/6/3 10:10
     *
     * @param $eventForm
     */
    public function setEventForm($eventForm){
        $this->eventForm = $eventForm;
        if(strpos($this->eventForm, '.')){
            $ex = explode('.', $this->eventForm);
            $this->eventForm = array_shift($ex);
            $this->target = $ex;
        }
        $this->eventForm = ucfirst($this->eventForm);
        $formMapData = include $this->formFieldPath.'formMap.php';
        $this->eventName = $formMapData[$this->eventForm];
    }

    /**
     * Notes: 获取数组的描述信息
     * User: llbjj
     * DateTime: 2022/6/3 10:28
     *
     */
    public function getChangeRemark(array &$changeArr, &$oldData = null, string $target = '') {
        $changeRemarkDatas = [];

        foreach($changeArr as $fieldKey => $fieldVal){
            $target = $target ?: $this->target;
            if($fieldKey === 'content'){
                $target = $this->relationTarget;
                $fieldVal = json_decode($fieldVal, true);
            }

            $formFieldData = $target ? ArrayHelper::getValue($this->formFieldData, implode('.', $target)) : $this->formFieldData;

            if($fieldKey === 'content' && !empty($fieldVal) && is_array($fieldVal)){

                $contentRemarks = [];
                $contentOldData = isset($oldData[$fieldKey]) ? json_decode($oldData[$fieldKey], true) : [];
                foreach($fieldVal as $contentKey => $content){
                    if(!empty($content)){
                        $changeType = isset($contentOldData[$contentKey]) ? '编辑：' : '新增：';
                        $contentOldData[$contentKey] = $contentOldData[$contentKey] ?? [];
                        if(array_diff_assoc($content, $contentOldData[$contentKey])) {
                            unset($content['id']);
                            $contentDatas = $this->getChangeRemark($content, $contentOldData[$contentKey], $target);
                            foreach($contentDatas as $contentData){
                                array_push($contentRemarks, $changeType.implode(' | ', $contentData));
                            }
                        }
                    }
                }

                array_push($changeRemarkDatas, implode('</br>', $contentRemarks));
            }else{
                $originKey = $fieldKey;
                // 处理多层关联表单key
                $fieldKey = $this->handleFieldKey($fieldKey);

                // 新增判断是否为手动填写
                if (isset($formFieldData[$fieldKey]) || $fieldKey == Form::ATTACH_SDTX) {
                    if (isset($formFieldData[$fieldKey]['val_soure']) and is_callable($formFieldData[$fieldKey]['val_soure'])){
                        $fieldVal = $formFieldData[$fieldKey]['val_soure']($this->LocalService(),$fieldVal);
                        if(isset($oldData[$fieldKey])) $oldData[$fieldKey] = $formFieldData[$fieldKey]['val_soure']($this->LocalService(),$oldData[$fieldKey]);
                    }else{
                        if (!isset($formFieldData[$fieldKey]['type'])) {
                            continue;
                        }
                        switch ($formFieldData[$fieldKey]['type']){
                            case 'Radio' || Enum::FORM_FIELD_TYPE_RADIO:
                                $formValueData = $formFieldData[$fieldKey];
                                $fieldVal = $this->getValue($formValueData,$fieldVal);
                                if(isset($oldData[$fieldKey])) $oldData[$fieldKey] = $this->getValue($formValueData, $oldData[$fieldKey]);
                                break;
                            case 'Select':
                                $formValueData = $formFieldData[$fieldKey]['options'];
                                $fieldVal = $this->getValue($formValueData,$fieldVal);
                                if(isset($oldData[$fieldKey])) $oldData[$fieldKey] = $this->getValue($formValueData, $oldData[$fieldKey]);
                                break;
                            case 'Checkbox':
                                if (isset($formFieldData[$fieldKey]['value']) && !empty($formFieldData[$fieldKey]['value'])){
                                    $vcArr = explode(',',$fieldVal);
                                    $vS = '';
                                    foreach ($vcArr as $k=>$v) {
                                        if (!is_numeric($v)){
                                            continue;
                                        }
                                        $vS .= $formFieldData[$fieldKey]['value'][$v].',';
                                    }
                                    $fieldVal = rtrim($vS,',');
                                }
                                break;
                            case 'Date':
                                $fieldVal = $fieldVal ? date('Y-m-d',$fieldVal) : '';
                                break;
                            case 'DateTime':
                                $fieldVal = $fieldVal ? date('Y-m-d H:i:s',$fieldVal) : '';
                                break;
                            case 'Switch':
                                $formValueData = $formFieldData[$fieldKey]['switchs'];
                                $fieldVal = $this->getValue($formValueData,$fieldVal);
                                if(isset($oldData[$fieldKey])) $oldData[$fieldKey] = $this->getValue($formValueData, $oldData[$fieldKey]);
                                break;

                        }
                    }

                    if (isset($oldData[$originKey])) {
                        // 处理如果之前的数据是数组, 需要转成json, 并且不转译汉字, 因为前端没转译汉字
                        $oldData[$originKey] = is_array($oldData[$originKey]) ?
                            json_encode($oldData[$originKey], JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE) :
                            $oldData[$originKey];

                        if ($fieldVal != $oldData[$originKey]) {
                            $fieldVal = "{$oldData[$originKey]} => {$fieldVal}";
                        } else {
                            continue;
                        }
                    }

                    array_push($changeRemarkDatas, $this->getLabel($formFieldData, $fieldKey) . '：' . $fieldVal);
                }
            }

        }
        yield $changeRemarkDatas;
    }

    /**
     * 处理fieldKey
     * 如果是关联表单, fieldKey会以`-`切割开
     * @param $fieldKey
     * @return mixed|string
     */
    private function handleFieldKey($fieldKey): string
    {
        if (stripos($fieldKey, '-') !== false) {
            $fieldKey = explode('-', $fieldKey)[0];
        }

        return $fieldKey;
    }

    /**
     * 获取labelKey
     * @return string
     */
    private function getLabel($formFieldData, $fieldKey): string
    {
        if (isset($formFieldData[$fieldKey]['label'])) { // 普通表单配置
            return $formFieldData[$fieldKey]['label'];
        } elseif (isset($formFieldData[$fieldKey]['name'])) { // 关联表单
            return $formFieldData[$fieldKey]['name'];
        } elseif ($fieldKey === Form::ATTACH_SDTX) { // 手动填写
            return '手动填写';
        }

        return '???';
    }

    /**
     *
     *添加入库
     * @param string $key
     * @return
     */

    public function saveLogToDb(String $fileContents = '') {
        $delFile = false;
        if(empty($fileContents)){
            $delFile =  true;
            $fileContents = $this->getLogContentFromRedis();
        }

        $data = unserialize($fileContents);
        if (empty($data)) {
            return false;
        }

        $remarkS = '';

        // 设置事件来源信息
        $this->relationTarget = $data['relation_form'];
        $this->fnParams = $data['fnParams'];


        if (!is_array($data['event_from'])) {
            $this->setEventForm($data['event_from']);
        }

        if (in_array($data['oper_type'], [0, 1])){
            if (!is_array($data['event_from'])) {
                $this->getFormFieldData($delFile);
                if(empty($this->formFieldData) || !is_array($this->formFieldData)) return false;
            } else {
                $this->formFieldData = $data['event_from'];
            }
//var_dump($data['new_data']);die;
            // 获取操作 修改的数据
            $changeArr = $data['oper_type'] ? $this->_getChangeData($data['old_data'],$data['new_data']) : $data['new_data'];


            unset($changeArr['old_data_str']);
            if (empty($changeArr)) return false;

            $remarkSDatas = $this->getChangeRemark($changeArr, $data['old_data']);

            foreach($remarkSDatas as $remarkSData){
                $remarkS = implode('</br>', $remarkSData);
            }

            $remarkS .= $this->_getCheckTimeAndStageString($data);
            $remarkS .= $this->_setEditReason($data);
            if(empty($remarkS)) return false;

            //$operTypeName = $data['oper_type'] ? '修改' : '新增';
            //$remarkS = $data['user_realname'].$operTypeName.'：<br>'.implode('<br>',$remarkData);
            $operTypeName = $data['oper_type'] ? '修改' : '新增';
            $remarkS = $data['user_realname'].$operTypeName.'：</br>'.$remarkS;
        }else{
            $remarkS = $this->_getOperateString($data);
            $remarkS .= $this->eventName.'【'.$data['log_remark'].'】' . $this->_getMultiDeleteRemarkDetail($data) . $this->_getCheckTimeAndStageString($data);
        }

        unset($data['user_realname']);
        unset($data['relation_form']);
        unset($data['fnParams']);
        $data['new_data'] = !empty($data['new_data']) ? serialize($data['new_data']) : '';
        $data['old_data'] = !empty($data['old_data']) ? serialize($data['old_data']) : '';
        $data['change_data'] = $remarkS;//serialize($changeArr);
        $data['event_from'] = $this->saveEventForm ?: $this->eventForm; // 对表单日志做的兼容

        $result = $this->LocalService()->adminLog->insert($data);
        if (empty($result)) {
            $this->_pushRedis();
            return false;
        }
        if($delFile) @unlink($this->logFilePath.$this->logFileName);
        return true;
    }

    private function writeDb(){

    }

    /**
     * 获取删除详情
     * @param $data
     * @return string
     */
    private function _getMultiDeleteRemarkDetail($data): string
    {
        if ($this->isDeleteDetail === false) {
            return '';
        }

        $contentData = StringHelper::jsonDecode(Laminas::$serviceManager->patientFormContent->fetchOne([
            'where' => ['id' => $data['event_id']]
        ])['data'], false);

        if (!$contentData) {
            return '';
        }

        $remark = '</br>';
        foreach ($contentData as $field => $v) {
            $field = DataHelper::getFieldId($field);
            if (isset($data['event_from'][$field])) {
                // 单选
                if ($data['event_from'][$field]['type'] == Enum::FORM_FIELD_TYPE_RADIO) {
                    $remark .= "{$this->getLabel($data['event_from'], $field)} => {$this->getValue($data['event_from'][$field], $v)}" . '</br>';
                } else {
                    $remark .= "{$this->getLabel($data['event_from'], $field)} => {$v}" . '</br>';
                }
            }
        }

        return $remark;
    }

    /**
     * 获取操作转译后的文本
     * @param $data
     * @return string
     */
    private function _getOperateString($data): string
    {
        if (isset($data['oper_type']) && $data['oper_type'] == self::OPERATE_FLUSH) {
            return ($data['user_realname'] ?? '') . "重置了: ";
        }

        return $data['oper_type'] == '3' ? '定时任务 操作：' : ($data['user_realname'] ?? '') . ' 删除了：';
    }

    /**
     * 获取阶段和检查点信息
     * @param $data
     * @return string
     */
    private function _getCheckTimeAndStageString($data): string
    {
        $remarkS = '';
        if(isset($data['new_data']['patient_id'])){
            $patientInfo = $this->LocalService()->patient->fetchOne(['where'=> [
                'id' => $data['new_data']['patient_id']
            ],'columns'=>['patient_name','patient_number']]);

            if(!empty($patientInfo['patient_name']) || !empty($patientInfo['patient_number'])){
                if(!empty($patientInfo['patient_name'])){
                    $patientName = '</br>'."受试者：".$patientInfo['patient_name'];
                    if(!empty($patientInfo['patient_number'])){
                        $patientName .= '</br>'."受试者：".$patientInfo['patient_name']."【".$patientInfo['patient_number'].'】';
                    }
                }else{
                    $patientName = '</br>'."受试者："."【".$patientInfo['patient_number'].'】';
                }
                $remarkS .= $patientName;
            }
        }

        if(isset($data['new_data']['form_id'])){
            $formInfo = $this->LocalService()->itemForm->fetchOne(['where'=> [
                'id' => $data['new_data']['form_id']
            ],'columns'=>['name']]);
            if(!empty($formInfo['name'])){
                $remarkS .= '</br>'."表单：".$formInfo['name'];
            }
        }

        if (isset($data['new_data']['checktime_id'])) {
            $checktimeInfo = $this->LocalService()->itemChecktime->fetchOne(['where'=>['id' => $data['new_data']['checktime_id']],'columns'=>['check_name','stage_id']]);
            if (!empty($checktimeInfo['stage_id'])) {
                $stageInfo = $this->LocalService()->itemResearchstage->fetchOne(['where'=> [
                    'id' => $checktimeInfo['stage_id']
                ],'columns'=>['stage_name']]);
                if(!empty($checktimeInfo['stage_id'])){
                    $remarkS .= '</br>'."阶段：".$stageInfo['stage_name'];
                }
            }
            if(!empty($checktimeInfo['check_name'])){
                $remarkS .= '</br>'."检查点：".$checktimeInfo['check_name'];
            }
        }

        return rtrim($remarkS, '</br>');
    }

    private function _setEditReason(array $requestData = []): string
    {
        $res = '</br> 修改原因：';
        if (isset($requestData['new_data']['edit_reason']) && $requestData['new_data']['edit_reason']) {
            $editReason = StringHelper::jsonDecode($requestData['new_data']['edit_reason']);
            foreach ($editReason as $v) {
                if ($v['prop']) {
                    $res .= '</br>' . Laminas::$serviceManager->SDMHelper->getFormHelper()->field->getFieldString(DataHelper::getFieldId($v['prop'])) . ': ' . ($v['value'] ?? '');
                }
            }
        }

        return $res;
    }

    /**
     * Notes: 向redis队列中加入日志文件名称
     * User: llbjj
     * DateTime: 2022/7/19 16:14
     *
     */
    private function _pushRedis(){
        $this->redisObj->rPush($this->logFileName,self::logRedisListKey);
    }

    /**
     * Notes: 丛redis队列中获取一条数据,遵循先进先出的规则
     * User: llbjj
     * DateTime: 2022/7/19 16:20
     *
     */
    private function _popRedis(){
        return $this->redisObj->lPop(self::logRedisListKey);
    }

    /**
     * Notes: 获取两个数组差集
     * User: llbjj
     * DateTime: 2022/7/20 16:39
     *
     * @param array $oldData
     * @param array $newData
     * @return array
     */
    private function _getChangeData(array &$oldData, array &$newData) {
        return array_map('unserialize', array_diff_assoc(array_map('serialize', $newData),array_map('serialize', $oldData)));
    }

    /**
     * Notes: 设置日志文件内容，如果日志过程中报错，将会把日志内容存入文件中，方便后续补录落库、查找问题
     * User: llbjj
     * DateTime: 2022/7/22 15:25
     *
     * @param string $logFileContent
     */
    private function setLogFileContent(string $logFileContent){
        $this->logFileContent = $logFileContent;
    }

    private function getValue($formValueData,$vc){
        if (isset($formValueData['children'])) {
            $formValueData['children'] = ArrayHelper::index($formValueData['children'], 'value');
        }

        foreach ($formValueData as $kS=>$vS) {
            if (isset($formValueData['children'])) {
                $vc = $formValueData['children'][$vc]['name'];
                break;
            }

            if (is_array($vS)) {
                foreach ($vS as $vSK=>$vSKV) {
                    if (isset($vSKV['value']) && $vc == $vSKV['value']){
                        $vc = $vSKV['label'];
                    }

                }
            }
//            if ($vc == $vS['value']){
//                $vc = $vS['label'];
//            }
        }

        return $vc;
    }
    public function getUserNameAndPlatform(){
        $arr = [
            'platform' =>0,
            'user_realname' =>$this->LocalService()->identity->getRealName(),
        ];
        $mobile = $this->LocalService()->identity->getMobile()?:0;
        $platform = strtolower($this->LocalService()->identity->getPlatform());
        if  ($platform =='mini' || $platform =='mini_real'){
            $arr['user_realname'] = $this->LocalService()->signatoryUser->getOneFieldVal('user_name',[
                'is_del' => 0,
                'user_tel' => $mobile,
            ]) ?: '';
            $arr['platform'] = ($platform =='mini') ? 3 :1;
        }else if  ($platform =='mini_patient'){
            $patientInfo = $this->LocalService()->patient->fetchOne(['where'=> [
                'is_del' => 0,
                'patient_tel' => $mobile,
            ]]) ?: '';
            $patient = '';
            if  (!empty($patientInfo)){
                if(!empty($patientInfo['patient_number'])) $patient = '【'.$patientInfo['patient_number'].'】';
                if(!empty($patientInfo['patient_name'])) $patient .= $patientInfo['patient_name'];
            }
            $arr['user_realname'] = $patient;
            $arr['platform'] = 2;
        }
        return $arr;
    }

}