<?php
/**
 *
 * @author：llbjj
 * @DateTime：2022/5/6 10:57
 * @Description：
 *
 */

namespace Application\Service\DB\Item;

use Application\Service\Exceptions\InvalidArgumentException;
use Application\Service\Extension\Helper\ArrayHelper;
use Application\Service\Extension\Helper\SDMHelper;
use Application\Service\Extension\Helper\StringHelper;
use Application\Service\Extension\Laminas;
use Interop\Container\ContainerInterface;
use Laminas\Db\Sql\Expression;
use Laminas\Db\Sql\Predicate\Operator;
use Laminas\Db\Sql\Sql;
use Laminas\Db\Sql\Where;
use Laminas\Db\ResultSet\ResultSet;

class Question extends \Application\Service\DB\AbstractDb
{
    public function __construct($dbAdapter, ContainerInterface $container)
    {
        $this->tableName = 'yikeen_item_question';
        parent::__construct($dbAdapter, $container);
    }

    /**
     * 当前数据是否被质疑过
     * @param int $formId
     * @param int $patientId
     * @param int $checkTimeId
     * @param string $annexId
     * @return bool
     */
    public function isQuestion(int $formId, int $patientId, int $checkTimeId, bool $isShareForm = false): array
    {
        if ($isShareForm === false) {
            $field = Laminas::$serviceManager->itemFormField->fetchOne([
                'where' => ['form_id' => $formId, 'var_name' => 'CHECKIMG']
            ]);

            if (!$field) {
                throw new InvalidArgumentException('未找到对应的化验单字段id');
            }
        } else {
            $shareForm = ArrayHelper::getColumn(SDMHelper::app()->form->getGcoGroupForm($formId), 'id');
        }

        // 是否被质疑
        $query = Laminas::$serviceManager->itemQuestion->fetchAll([
            'order' => ['id DESC'],
            'where' => [
                'form_id' => $isShareForm ? $shareForm : $formId,
//                'question_type_id' => $field['id'],
                'checktime_id' => $checkTimeId,
                'patient_id' => $patientId,
                'is_del' => 0
            ]
        ]);

        if (count($query) == 1) {
            $query = current($query);
            return $query ? [
                'question' => $query['question'],
                'question_type' => call_user_func(function () use ($query) {
                    if ($query['question_type'] == 1) {
                        return '表单质疑';
                    } elseif ($query['question_type'] == 2) {
                        return '化验单图片质疑';
                    } elseif ($query['question_type'] == 0) {
                        return '中心质疑';
                    }

                    return '未知的类型';
                }),
                'question_status' => call_user_func(function () use ($query) {
                    if ($query['question_status'] == 0) {
                        return '待回复';
                    } elseif ($query['question_status'] == 1) {
                        return '待确认';
                    } elseif ($query['question_status'] == 2) {
                        return '沟通完成';
                    } elseif ($query['question_status'] == 4) { // 4不知道是啥状态, 我猜的是沟通中
                        return '沟通中';
                    }

                    return '未知的状态';
                })
            ] : [];
        } else {
            $r = [];
            foreach ($query as $item) {
                $r[] = [
                    'question' => $item['question'],
                    'question_type' => call_user_func(function () use ($query) {
                        if ($query['question_type'] == 1) {
                            return '表单质疑';
                        } elseif ($query['question_type'] == 2) {
                            return '化验单图片质疑';
                        } elseif ($query['question_type'] == 0) {
                            return '中心质疑';
                        }

                        return '未知的类型';
                    }),
                    'question_status' => call_user_func(function () use ($query) {
                        if ($query['question_status'] == 0) {
                            return '待回复';
                        } elseif ($query['question_status'] == 1) {
                            return '待确认';
                        } elseif ($query['question_status'] == 2) {
                            return '沟通完成';
                        } elseif ($query['question_status'] == 4) { // 4不知道是啥状态, 我猜的是沟通中
                            return '沟通中';
                        }

                        return '未知的状态';
                    })
                ];
            }
            return $r;
        }
    }

    /**
     * 当前数据是否被质疑过
     * @param int $formId
     * @param int $patientId
     * @param int $checkTimeId
     * @param string $annexId
     * @return bool
     */
    public function isQuestionV2(int $formId, int $patientId, int $checkTimeId, bool $isShareForm = false): array
    {
        if ($isShareForm === false) {
            $field = Laminas::$serviceManager->itemFormField->fetchOne([
                'where' => ['form_id' => $formId, 'var_name' => 'CHECKIMG']
            ]);

            if (!$field) {
                throw new InvalidArgumentException('未找到对应的化验单字段id');
            }
        } else {
            $shareForm = ArrayHelper::getColumn(SDMHelper::app()->form->getGcoGroupForm($formId), 'id');
        }

        // 是否被质疑
        $query = Laminas::$serviceManager->itemQuestion->fetchAll([
            'order' => ['id DESC'],
            'where' => [
                'form_id' => $isShareForm ? $shareForm : $formId,
//                'question_type_id' => $field['id'],
                'checktime_id' => $checkTimeId,
                'patient_id' => $patientId,
                'is_del' => 0
            ]
        ]);

        $r = [];
        $getStatus = function ($status) {
            if ($status == 0) {
                return '待回复';
            } elseif ($status == 1) {
                return '待确认';
            } elseif ($status == 2) {
                return '沟通完成';
            } elseif ($status == 4) { // 4不知道是啥状态, 我猜的是沟通中
                return '沟通中';
            }

            return '未知的状态';
        };
        foreach ($query as $item) {
            $r[] = [
                'question' => ($item['question_status'] == 2 ? "[{$getStatus($item['question_status'])}] " : '') . $item['question'],
                'question_type' => call_user_func(function () use ($query, $item) {
                    if ($item['question_type'] == 1) {
                        return '表单质疑';
                    } elseif ($item['question_type'] == 2) {
                        return '化验单图片质疑';
                    } elseif ($item['question_type'] == 0) {
                        return '中心质疑';
                    }

                    return '未知的类型';
                }),
                'question_status' => $getStatus($item['question_status'])
            ];
        }
        return $r;

    }

    /**
     * Notes: 获取有质疑数据的患者检查点表单【暂未完成先提交保存】
     * User: lltyy
     * DateTime: 2024/9/20 9:33
     *
     * @param array $info
     * @return array
     */
    public function haveQuestion($info = []){
        $item_id = isset($info['item_id']) && !empty($info['item_id']) ? $info['item_id'] : [];
        $itemsig_id = isset($info['itemsig_id']) && !empty($info['itemsig_id']) ? $info['itemsig_id'] : [];
        $patient_id = isset($info['patient_id']) && !empty($info['patient_id']) ? $info['patient_id'] : [];
        $return_type = isset($info['return_type']) && !empty($info['return_type']) ? $info['return_type'] : 0;//返回数据类型【0 患者检查点表单键值数组】
        $arr = [];

        //SDM质疑
        $where = [
            'is_del' => 0,
        ];
        if(!empty($item_id)){
            $where['item_id'] = StringHelper::toArray($item_id);
        }
        if(!empty($itemsig_id)){
            $where['item_sign_id'] = StringHelper::toArray($itemsig_id);
        }
        if(!empty($patient_id)){
            $where['patient_id'] = StringHelper::toArray($patient_id);
        }
        if(empty($return_type)){
            $where[] = new Operator('patient_id', Operator::OP_GT, 0);
            $where[] = new Operator('checktime_id', Operator::OP_GT, 0);
            $where[] = new Operator('form_id', Operator::OP_GT, 0);
        }
        $questionDatas = Laminas::$serviceManager->itemQuestion->fetchAll([
            'where'=>$where,
            'columns'=>['patient_id','checktime_id','form_id']
        ]);
        unset($where);
        if(!empty($questionDatas)){
            foreach($questionDatas as $questionKey=>$questionData){
                if($return_type == 0){
                    $arr_key = $questionData['patient_id'].'_'.$questionData['checktime_id'].'_'.$questionData['form_id'];
                    if(!in_array($arr_key,$arr)){
                        $arr[] = $arr_key;
                    }
                }
                unset($questionDatas[$questionKey]);
            }
        }
        unset($questionDatas);

        //EDC质疑

        return $arr;
    }

    /**
     * Notes : 按时间展示质疑信息
     * @param array $info
     * @return array[]
     * Author:唐伯虎不虎
     * Date:2024/11/26 11:32
     */
    public function getQuestionInfo($info = []){
        $res = [
            'patient_form_checktime'=>[]
        ];
        $item_id    = isset($info['item_id']) && !empty($info['item_id']) ? $info['item_id'] : [];
        $itemsig_id = isset($info['itemsig_id']) && !empty($info['itemsig_id']) ? $info['itemsig_id'] : [];
        $patient_id = isset($info['patient_id']) && !empty($info['patient_id']) ? $info['patient_id'] : [];
        $form_id = isset($info['form_id']) && !empty($info['form_id']) ? $info['form_id'] : [];
        $content_id = isset($info['content_id']) && !empty($info['content_id']) ? $info['content_id'] : [];
        $checktime_id = isset($info['checktime_id']) && !empty($info['checktime_id']) ? $info['checktime_id'] : [];
        $type       = isset($info['type']) && !empty($info['type']) ? $info['type'] : 0;
        $info_type       = isset($info['info_type']) && !empty($info['info_type']) ? $info['info_type'] : 0;//是否为常规类识别【0 否 1 是】

        //SDM质疑
        $where = [
            'is_del' => 0,
            'question_type' => [1, 2],
        ];
        $edc_where = [
            'is_report' => 1,
            'is_report_special' => 1,
        ]; //化验单未查，自动发的质疑不统计
        if($info_type == 1){
            $where = [
                'is_del' => 0,
                'question_type' => 1,
            ];
            $edc_where = [
                'is_del' => 0,
                'error_type' => 1,
                'is_report_special' => 1,
            ];
        }
        if(!empty($item_id)){
            $where['item_id'] = StringHelper::toArray($item_id);
            $edc_where['item_id'] = StringHelper::toArray($item_id);
        }
        if(!empty($itemsig_id)){
            $where['item_sign_id'] = StringHelper::toArray($itemsig_id);
            $edc_where['sign_id'] = StringHelper::toArray($itemsig_id);
        }

        if(!empty($patient_id)){
            $where['patient_id'] = StringHelper::toArray($patient_id);
            $edc_where['patient_id'] = StringHelper::toArray($patient_id);
        }

        if(!empty($form_id)){
            $where['form_id'] = StringHelper::toArray($form_id);
            $edc_where['form_id'] = StringHelper::toArray($form_id);
        }
        if($info_type == 0 && !empty($content_id)){
            $where['content_id'] = StringHelper::toArray($content_id);
            $edc_where['formcontent_id'] = StringHelper::toArray($content_id);
        }

        if(!empty($checktime_id)){
            $where['checktime_id'] = StringHelper::toArray($checktime_id);
            $edc_where['checktime_id'] = StringHelper::toArray($checktime_id);
        }


        switch ($type) {
            case 0:
                $edc_where['is_closed'] = [0, 1];
                break;
            case 1;
                $where[] = new Operator('question_status', Operator::OP_NE, 2);
                $edc_where['is_closed'] = 0;
                break;
            case 2;
                $where[] = new Operator('question_status', Operator::OP_NE, 2);
                $edc_where['is_closed'] = 0;
                break;
            case 3;

                $where['question_status'] = 2;
                $edc_where['is_closed'] = 1;
                break;
        }

        $questionDatas = Laminas::$serviceManager->itemQuestion->fetchAll([
            'where'=>$where,
            'columns'=>['id','patient_id','checktime_id','form_id','question_status','question','question_type','content_id']
        ]);

        if(!empty($questionDatas)){
            $question_statusArr = [0=>'待回复',1 =>'待确认',2=>'沟通完成',4=>'沟通中'];
            $question_typeArr = [0=>'中心质疑',1 =>'表单质疑',2=>'2化验单图片质疑'];
            foreach ($questionDatas as &$questionData){
                $question_status  = isset($question_statusArr[$questionData['question_status']])&& !empty($question_statusArr[$questionData['question_status']])?$question_statusArr[$questionData['question_status']] : '';
                $question_types  = isset($question_typeArr[$questionData['question_type']])&& !empty($question_typeArr[$questionData['question_type']])?$question_typeArr[$questionData['question_type']] : '';
                $questionData['question_type']    = $question_types;
                $questionData['question_status']  = $question_status;
                if($question_status == '沟通完成'){
                    $questionData['question']  = '('.$question_status.')'.$questionData['question'];
                }
                $res[$questionData['form_id']][$questionData['checktime_id']][$questionData['patient_id']]['itemQuestionForminfo'][] = $questionData;
                $patient_form_checktime_key = $questionData['patient_id'].'_'.$questionData['form_id'].'_'.$questionData['checktime_id'];
                if(!in_array($patient_form_checktime_key,$res['patient_form_checktime'])){
                    $res['patient_form_checktime'][] = $patient_form_checktime_key;
                }
            }
        }

        //查询edc质疑
        $edcquestionDatas = Laminas::$serviceManager->itemPatientFormLogicError->fetchAll([
            'where'=>$edc_where,
            'columns'=>['id','patient_id','checktime_id','form_id','is_closed','expression_note','item_id','sign_id','create_user_id','create_time','is_reply','formcontent_id']
        ]);
        if(!empty($edcquestionDatas)){
            $edcquestion_statusArr = [0=>'未关闭',1 =>'已关闭'];
            foreach ($edcquestionDatas as &$edcquestionDatas){
                $roleName = SDMHelper::app()->user->getEDCRoleNameString($edcquestionDatas['create_user_id'],$edcquestionDatas['item_id'], $edcquestionDatas['sign_id']);
                $name = SDMHelper::app()->user->getRealName($edcquestionDatas['create_user_id']);
                if(empty($edcquestionDatas['create_user_id'])){
                    $name = 'System';
                    $roleName = '系统';
                }
                $message = $edcquestionDatas['expression_note'] . " [$roleName] $name " . date('Y-m-d H:i:s', $edcquestionDatas['create_time']);
                $edcquestionDatas['message']  =$edcquestionDatas['is_closed'] == 1 ? '[已关闭]'.$message : $message;
                $edcquestionDatas['edcquestion_status']  = isset($edcquestion_statusArr[$edcquestionDatas['is_closed']])&& !empty($edcquestion_statusArr[$edcquestionDatas['is_closed']])?$edcquestion_statusArr[$edcquestionDatas['is_closed']] : '';
                $res[$edcquestionDatas['form_id']][$edcquestionDatas['checktime_id']][$edcquestionDatas['patient_id']]['edcQuestionData'][] = $edcquestionDatas;
                $edc_patient_form_checktime_key = $edcquestionDatas['patient_id'].'_'.$edcquestionDatas['form_id'].'_'.$edcquestionDatas['checktime_id'];
                if(!in_array($edc_patient_form_checktime_key,$res['patient_form_checktime'])){
                    $res['patient_form_checktime'][] = $edc_patient_form_checktime_key;
                }
            }
        }

        unset($questionDatas);
        unset($edcquestionDatas);
        return $res;
    }

    public function errorInfo($whereSearch,$item_id,$type,$limit,$offset)
    {
        $where = ' and q.is_del = 0 and q.question_type in(1,2)';
        $edc_where = ' and q.is_report = 1 and q.is_report_special = 1'; //化验单未查，自动发的质疑不统计
        switch ($type) {
            case 0:
                $where .= ' and q.question_status <> 2';
                $edc_where .= ' and q.is_closed in(0,1)';
                break;
            case 1;
                $where .= ' and q.question_status <> 2';
                $edc_where .= ' and q.is_closed = 0';
                break;
            case 2;
                $where .= ' and q.question_status <> 2';
                $edc_where .= ' and q.is_closed = 0';
                break;
            case 3;
                $where .= ' and q.question_status = 2';
                $edc_where .= ' and q.is_closed = 1';
                break;
        }


        $questionCountwhereArray = explode('and ',$whereSearch);
        $questionCountwhere = '';
        foreach($questionCountwhereArray as $questionV)
        {
            $questionV = trim($questionV,'');
            if($questionV == " ") continue;
            $questionCountwhere .= ' and annex.'.$questionV;
        }

        $sql = new Sql(Laminas::$app->getServiceManager()->get('dbAdapter'));
        $select = $sql->select();
        $select->from(['annex' => 'yikeen_item_patientworkannex']) // 主表
        ->columns(['form_id','checktime_id','patient_id','annex_id'=>'id'])
            ->join(
                ['q' => 'yikeen_item_question'],
                "annex.patient_id = q.patient_id and annex.checktime_id = q.checktime_id and annex.form_id = q.form_id",
                ['id','patient_id','checktime_id','form_id','question_status','question','question_type'],
                $select::JOIN_LEFT
            )
            ->where("annex.is_del = 0 and annex.item_id = $item_id and annex.annex_type != 2 and annex.category_id != 0".$questionCountwhere.$where)
            ->order('annex.id')->group('annex.checktime_id')->group('annex.patient_form_id')->group('annex.form_id')->limit($limit)->offset($offset);

        $resultSet = new ResultSet();
        $statement = $sql->prepareStatementForSqlObject($select);
//        		$sqlString = $sql->buildSqlString($select);
//		var_dump($sqlString);die;
        $questionDatas = $resultSet->initialize($statement->execute())->toArray();

        if(!empty($questionDatas)){
            $question_statusArr = [0=>'待回复',1 =>'待确认',2=>'沟通完成',4=>'沟通中'];
            $question_typeArr = [0=>'中心质疑',1 =>'表单质疑',2=>'2化验单图片质疑'];
            foreach ($questionDatas as &$questionData){
                $question_status  = isset($question_statusArr[$questionData['question_status']])&& !empty($question_statusArr[$questionData['question_status']])?$question_statusArr[$questionData['question_status']] : '';
                $question_types  = isset($question_typeArr[$questionData['question_type']])&& !empty($question_typeArr[$questionData['question_type']])?$question_typeArr[$questionData['question_type']] : '';
                $questionData['question_type']    = $question_types;
                $questionData['question_status']  = $question_status;
                if($question_status == '沟通完成'){
                    $questionData['question']  = '('.$question_status.')'.$questionData['question'];
                }
                $res[$questionData['form_id']][$questionData['checktime_id']][$questionData['patient_id']]['itemQuestionForminfo'][] = $questionData;
                $patient_form_checktime_key = $questionData['patient_id'].'_'.$questionData['form_id'].'_'.$questionData['checktime_id'];
                if(!in_array($patient_form_checktime_key,$res['patient_form_checktime'])){
                    $res['patient_form_checktime'][] = $patient_form_checktime_key;
                }
            }
        }


        $mainDB = Laminas::$serviceManager->config['db']['adapters']['edcDbAdapter']['dsn'];
        $mainDbName = StringHelper::getDatabaseNameFromDsn($mainDB);

        $select = $sql->select();
        $select->from(['annex' => 'yikeen_item_patientworkannex']) // 主表
        ->columns(['form_id','checktime_id','patient_id'])
            ->join(
                ['q' => new \Laminas\Db\Sql\TableIdentifier('yikeen_item_patient_form_logic_error', $mainDbName)],
                "annex.patient_id = q.patient_id and annex.checktime_id = q.checktime_id and annex.form_id = q.form_id",
                ['id','patient_id','checktime_id','form_id','is_closed','expression_note','item_id','sign_id','create_user_id','create_time','is_reply'],
                $select::JOIN_INNER
            )
            ->where("annex.is_del = 0 and annex.item_id = $item_id and annex.annex_type != 2 and annex.category_id != 0".$questionCountwhere.$edc_where)
            ->order('annex.id')->group('annex.checktime_id')->group('annex.patient_form_id')->group('annex.form_id')->limit($limit)->offset($offset);
        //		$sqlString = $sql->buildSqlString($select);
//		var_dump($sqlString);die;
        $resultSet = new ResultSet();
        $statement = $sql->prepareStatementForSqlObject($select);
        $edcquestionDatas = $resultSet->initialize($statement->execute())->toArray();
        if(!empty($edcquestionDatas)){
            $edcquestion_statusArr = [0=>'未关闭',1 =>'已关闭'];
            foreach ($edcquestionDatas as &$edcquestionDatas){
                $roleName = SDMHelper::app()->user->getEDCRoleNameString($edcquestionDatas['create_user_id'],$edcquestionDatas['item_id'], $edcquestionDatas['sign_id']);
                $name = SDMHelper::app()->user->getRealName($edcquestionDatas['create_user_id']);
                $message = $edcquestionDatas['expression_note'] . " [$roleName] $name " . date('Y-m-d H:i:s', $edcquestionDatas['create_time']);
                $edcquestionDatas['message']  =$edcquestionDatas['is_closed'] == 1 ? '[已关闭]'.$message : $message;
                $edcquestionDatas['edcquestion_status']  = isset($edcquestion_statusArr[$edcquestionDatas['is_closed']])&& !empty($edcquestion_statusArr[$edcquestionDatas['is_closed']])?$edcquestion_statusArr[$edcquestionDatas['is_closed']] : '';
                $res[$edcquestionDatas['form_id']][$edcquestionDatas['checktime_id']][$edcquestionDatas['patient_id']]['edcQuestionData'][] = $edcquestionDatas;
                $edc_patient_form_checktime_key = $edcquestionDatas['patient_id'].'_'.$edcquestionDatas['form_id'].'_'.$edcquestionDatas['checktime_id'];
                if(!in_array($edc_patient_form_checktime_key,$res['patient_form_checktime'])){
                    $res['patient_form_checktime'][] = $edc_patient_form_checktime_key;
                }
            }
        }

        unset($questionDatas);
        unset($edcquestionDatas);
        return $res;
    }


    /**
     * Notes: 查询后台质疑信息
     * @param
     * @return
     * @author haojinhua
     * @date 2024-10-11
     */
    public function newquestionInfo($info = []){
        $res = [
            'patient_form_checktime'=>[]
        ];

        $item_id    = isset($info['item_id']) && !empty($info['item_id']) ? $info['item_id'] : [];
        $itemsig_id = isset($info['itemsig_id']) && !empty($info['itemsig_id']) ? $info['itemsig_id'] : [];
        $type       = isset($info['type']) && !empty($info['type']) ? $info['type'] : 0;//查询的质疑类型【1 未质疑 2 已质疑  3 沟通完成】

        //图片质疑-----》后台质疑沟通   【1 未质疑 2 已质疑 3 质疑关闭】
        $item_question_where = [
            'is_del' => 0,
            'question_type' => [1, 2],
        ];
        if(!empty($item_id)){
            $item_question_where['item_id'] = StringHelper::toArray($item_id);
        }
        if(!empty($itemsig_id)){
            $item_question_where['item_sign_id'] = StringHelper::toArray($itemsig_id);
        }

        if($type == 2){
            //查询未沟通完成的
            $item_question_where[] = new Operator('question_status', Operator::OP_NE, 2);
        }elseif($type == 3){
            //查询沟通完成的
            $item_question_where['question_status'] = 2;
        }


        $questionDatas = Laminas::$serviceManager->itemQuestion->fetchAll([
            'where'=>$item_question_where,
            'columns'=>['id','patient_id','checktime_id','form_id','question_status']
        ]);
        if(!empty($questionDatas)){
            $question_statusArr = [0=>'待回复',1 =>'待确认',2=>'沟通完成',4=>'沟通中'];
            foreach ($questionDatas as $questionData){
                $question_status  = isset($question_statusArr[$questionData['question_status']])&& !empty($question_statusArr[$questionData['question_status']])?$question_statusArr[$questionData['question_status']] : '';
                $res[$questionData['form_id']][$questionData['checktime_id']][$questionData['patient_id']]['question_status'][] = $question_status;
                $patient_form_checktime_key = $questionData['patient_id'].'_'.$questionData['form_id'].'_'.$questionData['checktime_id'];
                if(!in_array($patient_form_checktime_key,$res['patient_form_checktime'])){
                    $res['patient_form_checktime'][] = $patient_form_checktime_key;
                }
            }
        }
        unset($questionDatas);
        return $res;
    }

    /**
     * Notes:查询图片质疑回复信息
     * @param
     * @return
     * @author haojinhua
     * @date 2024-11-01
     */
    public function getreplayinfo($where = ''){
        $where  = !empty($where) ? $where : [
            'is_del' => 0,
        ];
        $datas = [];
        //查询历史回复信息
        $itemReplyDatas = $this->LocalService()->itemReply->fetchAll([
            'where' =>  $where,
            'columns' =>  ['id','question_id','reply_status','remarks','create_user_id','create_time','completed_id'],
        ]);

        if(!empty($itemReplyDatas)){
            $itemquestion = $this->LocalService()->itemQuestion->fetchCol('item_id','id > 0');
            $itemsigquestion = $this->LocalService()->itemQuestion->fetchCol('item_sign_id','id > 0');
            $userNameArr = $this->LocalService()->adminUser->fetchCol('realname', 'is_del = 0');
            $question_statusArr = [0=>'回复',1 =>'确认',2=>'沟通完成',4=>'沟通中'];
            list($sig_user_arr,$user_role_arr,$siguser_role_arr,$itemsig_arr) = $this->LocalService()->realRole->getUserRole();
            $itemDatas = $this->LocalService()->itemInfo->fetchDataByKey('is_del = 0',['id','name','number','fid'],['id'],['id'=>0]);
            $itemData = isset($itemDatas['id']) ? $itemDatas['id'] : [];
            //角色数组
            $roleNameArr = $this->LocalService()->realRole->fetchCol('role_name','is_del = 0');
            foreach ($itemReplyDatas as $itemReplyData){
                $reply_status    = isset($question_statusArr[$itemReplyData['reply_status']])&& !empty($question_statusArr[$itemReplyData['reply_status']])?$question_statusArr[$itemReplyData['reply_status']] : '';
                $remark = $itemReplyData['remarks'];
                if(!empty($remark)){
                    $n_remark = json_decode($remark, true) ? json_decode($remark, true) : $remark;
                }
                $remarks = $itemReplyData['remarks'];
                if(is_array($n_remark)){
                    $remarks = $n_remark['remarks'];
                    unset($n_remark);
                }
                //带出操作人 时间
                $create_time  = date('Y-m-d H:i:s', $itemReplyData['create_time']);  //操作时间
                $create_user  = isset($userNameArr[$itemReplyData['create_user_id']]) & !empty($userNameArr[$itemReplyData['create_user_id']]) ? $userNameArr[$itemReplyData['create_user_id']] : ''; //操作人/角色
                $role_name = '';

                $item_id    =  isset($itemquestion[$itemReplyData['question_id']]) && !empty($itemquestion[$itemReplyData['question_id']]) ? $itemquestion[$itemReplyData['question_id']] : 0;
                $itemsig_id =  isset($itemsigquestion[$itemReplyData['question_id']]) && !empty($itemsigquestion[$itemReplyData['question_id']]) ? $itemsigquestion[$itemReplyData['question_id']] : 0;

                $fid     = isset($itemData[$item_id]) && !empty($itemData[$item_id]) ? $itemData[$item_id]['fid'] : '0';
                if ($fid > 0) {
                    $item_id = $fid;
                }
                //查询用户角色
                $user_id     = $itemReplyData['create_user_id'];
                $sig_user_id = isset($sig_user_arr[$user_id]) && !empty($sig_user_arr[$user_id]) ? $sig_user_arr[$user_id]['sig_user_id'] : '';
                $role_ids    = isset($siguser_role_arr[$item_id][$itemsig_id][$sig_user_id]) && !empty($siguser_role_arr[$item_id][$itemsig_id][$sig_user_id]) ? $siguser_role_arr[$item_id][$itemsig_id][$sig_user_id] : 0;
                if(!empty($role_ids)){
                    foreach ($role_ids as $role_id){
                        $role_name .= isset($roleNameArr[$role_id]) && !empty($roleNameArr[$role_id]) ? $roleNameArr[$role_id].'|' : '';
                    }
                }

                $datas[$itemReplyData['question_id']]['replays'][] = $itemReplyData;
                $datas[$itemReplyData['question_id']]['colsed'] = $itemReplyData;
                unset($role_ids);
                if($itemReplyData['reply_status'] == 2){
                    $reply_status = $reply_status.'('.$create_user.'['.$role_name.'])'.$create_time;
                }
                $itemReplyData['remarks'] = $remarks;  //重新赋值
                //print_r($itemReplyData);die;


                $remarks = $remarks.'('.$create_user.'['.$role_name.'])'.$create_time;
                $datas[$itemReplyData['question_id']][] = [
                    'replay_content' => $remarks,
                    'reply_info' => $reply_status,
                    'reply_status' => $itemReplyData['reply_status'],
                ];


            }
        }
        //print_r($datas);die;
        unset($itemReplyDatas);
        unset($userNameArr);
        unset($question_statusArr);
        unset($itemquestion);
        unset($itemsigquestion);
        unset($userNameArr);
        unset($sig_user_arr);
        unset($user_role_arr);
        unset($siguser_role_arr);
        unset($itemDatas);
        return $datas;
    }

    /**
     * Notes: 获取待处理的ESD质疑数
     * User: lltyy
     * DateTime: 2024/11/18 8:17
     *
     * @param array $info
     * @return array
     */
    public function fetchNoreplyQuestion(array $info = []){
        $return_type = isset($info['return_type']) && !empty($info['return_type']) ? $info['return_type'] : 0;//返回类型 0 中心项目信息
        $item_id = isset($info['item_id']) && !empty($info['item_id']) ? $info['item_id'] : 0;//副项目ID
        $itemsig_id = isset($info['itemsig_id']) && !empty($info['itemsig_id']) ? $info['itemsig_id'] : 0;//项目中心ID

        //获取患者检查点信息
        $arr = [];
        $where = [
            'is_del' => 0,
            'question_status' => 0,
        ];
        if(!empty($item_id)){
            $where['item_id'] = $item_id;
        }
        if(!empty($itemsig_id)){
            $where['item_sign_id'] = $itemsig_id;
        }
        $datas = $this->fetchAll([
            'where'=>$where,
            'columns'=>['item_id','item_sign_id'],
            'order'=>['id']
        ]);
        unset($where);
        if(!empty($datas)){
            foreach($datas as $key=>$data){
                $data_item = $data['item_id'];
                $data_itemsig = $data['item_sign_id'];
                if($return_type == 0){
                    //每个中心的待处理质疑数
                    $arr['noreplay_question_count'][$data_itemsig][$data_item] = isset($arr['noreplay_question_count'][$data_itemsig][$data_item]) && !empty($arr['noreplay_question_count'][$data_itemsig][$data_item]) ? $arr['noreplay_question_count'][$data_itemsig][$data_item] : 0;
                    $arr['noreplay_question_count'][$data_itemsig][$data_item] += 1;

                    //需要质疑发信的中心
                    $arr['send_mes_sig'] = isset($arr['send_mes_sig']) && !empty($arr['send_mes_sig']) ? $arr['send_mes_sig'] : [];
                    if(!in_array($data_itemsig,$arr['send_mes_sig'])){
                        $arr['send_mes_sig'][] = $data_itemsig;
                    }

                    //需要质疑发信的项目
                    $arr['send_mes_item'] = isset($arr['send_mes_item']) && !empty($arr['send_mes_item']) ? $arr['send_mes_item'] : [];
                    if(!in_array($data_item,$arr['send_mes_item'])){
                        $arr['send_mes_item'][] = $data_item;
                    }
                }

                //释放空间
                unset($data_item);
                unset($data_itemsig);
                unset($datas[$key]);
            }
        }

        return $arr;
    }


}