<?php
/*
 * @Author: 863465124 863465124@qq.com
 * @Date: 2022-07-02 13:13:05
 * @LastEditors: 863465124 863465124@qq.com
 * @LastEditTime: 2022-08-18 11:39:47
 * @FilePath: /RemoteWorking/module/Application/src/Service/DB/Item/Patient.php
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
/**
 *
 * @author：llbjj
 * @DateTime：2022/5/6 10:57
 * @Description：
 *
 */

namespace Application\Service\DB\Item;

use Interop\Container\ContainerInterface;
use Application\Common\Crypt;
use Application\Common\Enum;
use Laminas\Cache\Exception\ExceptionInterface;
use Laminas\Db\Sql\Expression;
use Application\Service\Extension\Laminas;
use Application\Mvc\Controller\BasicController;
use Application\Service\ToolSys\ToolSys;
use Laminas\Db\Sql\Predicate\NotIn;
use Laminas\Db\Sql\Predicate\Operator;
use Laminas\Db\Sql\Where;


class Patient extends \Application\Service\DB\AbstractDb {
    public const PATIENT_ATTR_CONTENT_FIELD = 'patient_content';
    public function __construct($dbAdapter, ContainerInterface $container) {
        $this->tableName = 'yikeen_item_patient';
        $this->cryptFields = ['patient_name','patient_content'];
        $this->maskingFieldList = ['patient_tel'];
        parent::__construct($dbAdapter, $container);
    }
    public function encrypt($string){
        $string = Crypt::blockCipher()->encrypt($string);
        return $string;
    }
    public function decrypt($string){
        $string = Crypt::blockCipher()->decrypt($string);
        return $string;
    }

    public $randGroupId = 'randgroup_id';
    public $name = 'name';
    public $sex = 'sex';
    public $ns = 'ns';
    public $tel = 'tel';
    public $signatoryUserId = 'signatory_user_id';
    public $number = 'number';
    public $patientCardFlag = 'patient_card_flag';
    public $pid = 'pid';
    public $age = 'age';

    //病例信息
    public $collectName = 'patient_name';
    public $collectSex = 'patient_sex';
    public $collectNs = 'ns';
    public $collectTel = 'patient_tel';
    public $collectAge = 'patient_age';
    public $collectNumber = 'patient_number';
    public $collectPid = 'patient_card';

    public function getItemSignatoryUserData($item_id,$item_sign_id){
        $whereIteminfo['where'] = [
            'is_del' => 0,
            'id' => $item_id,
            'is_mainitem' => [0, 1],
        ];
        $itemInfo = $this->LocalService()->itemInfo->fetchOne($whereIteminfo);
        $signUser = [];
        if (empty($itemInfo)){
            return $signUser;
        }

        $itemIdBig = $itemInfo['fid'];
        $whereRealRole['where'] = [
            'is_del' => 0,
            'status' => 0,
            'item_id' => $itemIdBig,
            'code' => 'yjys',
        ];
        $realRoleInfo = $this->LocalService()->realRole->fetchOne($whereRealRole);
        if (empty($realRoleInfo)){
            return $signUser;
        }
        $roleUserWhere['where'] = [
            'is_del' => 0,
            'status' => 0,
            'role_id' => $realRoleInfo['id'],
            'item_sign_id' => $item_sign_id,
            'item_id' => $itemIdBig,
        ];

        $roleUser = $this->LocalService()->roleSignatoryRelation->fetchCol('signatory_user',$roleUserWhere['where']);
        if (!empty($roleUser)){
            $signatoryUserIds = implode(',',array_filter(array_unique($roleUser)));
            if (!empty($signatoryUserIds)){
                $whereSignatoryUser['where'] = [
                    'is_del' => 0,
                    'status' => 0,
                    'id' => array_filter(array_unique($roleUser)),
                ];
                $whereSignatoryUser['columns'] = ['value'=>'id','label'=>'user_name'];
                $signUser = $this->LocalService()->signatoryUser->fetchAll($whereSignatoryUser);
            }
        }
        return $signUser;
    }

    /**
     * Notes: 受试者统计
     * User: lltyy
     * DateTime: 2022/9/13 13:18
     *
     * @param array $arr
     *  where 受试者条件
     *  columns 受试者字段
     *  return_key 统计类型【1 性别统计 2 年龄段统计 3 研究分层性别统计 4 中心性别统计】
     * @return array
     */
    public function fetchPatientCountByKey($arr=[]){

        $where = isset($arr['where']) && !empty($arr['where']) ? $arr['where'] : [
            new Operator('id', Operator::OP_GT, 0),
        ];//条件
        $item_id = $arr['item_id'];
        $columns = isset($arr['columns']) && !empty($arr['columns']) ? $arr['columns'] : [];//字段
        $return_key = isset($arr['return_key']) && !empty($arr['return_key']) ? $arr['return_key'] : 0;//统计类型【0 性别统计 1 年龄性别统计 2 研究分层性别统计 3 中心性别统计】
        $return_type = isset($arr['return_type']) && !empty($arr['return_type']) ? $arr['return_type'] : 0;//【0 原逻辑 1 新功能新逻辑 】
        $limit = isset($arr['limit']) && !empty($arr['limit']) ? $arr['limit'] : 0;
        $page = isset($arr['page']) && !empty($arr['page']) ? $arr['page'] : 0;

        $data = [];
        $where_arr = [
            'where'=>$where,
            'columns'=>$columns,
            'order'=>['itemsig_id','patient_order','id']
        ];
        if (!empty($limit) && !empty($page)){
            $offset = intval(($page - 1) * $limit);
            $where_arr['limit'] = $limit;
            $where_arr['offset'] = $offset;
        }

        $patientType = $this->patientBasicFieldType();

        $patient_datas = $this->LocalService()->patient->fetchAll($where_arr);

        if(!empty($patient_datas)){
            $itemSignatoryData = [];
            $itemCheckcontentData = [];
            $itemPatientcheckcontentData = [];
            $patientFormData = [];
            if (!empty($return_type)){
                $itemsig_id_arr = array_filter(array_unique( array_column($patient_datas, 'itemsig_id')));
                $patient_id_arr = array_filter(array_unique( array_column($patient_datas, 'id')));

                if (in_array($return_key,[4,7])){
                    //中心
                    $itemFid = $this->LocalService()->itemInfo->getOneFieldVal('fid',[
                        'is_del' => 0,
                        'id' => $arr['item_id'] ?: 0,
                    ]);
                    $whereItemSignatory = [
                        'where'=>[
                            'is_del'=>0,
                            'item_id'=>$itemFid,
                            'id'=>$itemsig_id_arr,
                        ],
                        'columns'=>['id','signatory_id','plan_joingroup'],

                    ];
                    $itemSignatoryData = $this->LocalService()->itemSignatory->fetchAll($whereItemSignatory);

                    !empty($itemSignatoryData) && $itemSignatoryData = array_column($itemSignatoryData,null,'id');
                    $sign_id_arr = array_filter(array_unique( array_column($itemSignatoryData,'signatory_id')));
                    $whereSignatoryInfo = [
                        'where'=>[
                            'is_del'=>0,
                            'id'=>$sign_id_arr,
                        ],
                        'columns'=>[
                            'id',
                            'info_name',
                        ],
                    ];
                    $sign_datas = $this->LocalService()->signatoryInfo->fetchCol('info_name',$whereSignatoryInfo['where']);
                    if (!empty($sign_datas)){
                        $itemSignDatas[0] = '未知中心';
                        foreach ($itemSignatoryData as $itemsigIdk=>$infoIdv){
                            if(isset($sign_datas[$infoIdv['signatory_id']])){
                                $itemSignDatas[$itemsigIdk] = $sign_datas[$infoIdv['signatory_id']];
                            }
                        }
                        $patientType['itemsig_id'] = $itemSignDatas;
                    }
                }
                if ($return_key == 3){
                    //研究分层
                    $whereItemRandGroup = [
                        'is_del' => 0,
                        'item_id' => $arr['item_id'],
                    ];
                    $itemRandGroupData = $this->LocalService()->itemRandgroup->fetchCol('group_name',$whereItemRandGroup);
                    if (!empty($itemRandGroupData)){
                        $itemRandGroupDatas[0] = '未分组';
                        foreach ($itemRandGroupData as $groupId=>$groupName){
                            $itemRandGroupDatas[$groupId] = $groupName;
                        }
                        $patientType['randgroup_id'] = $itemRandGroupDatas;
                    }
                }
                //个人完成度统计 (受试者)
                if ($return_key == 8){
                    $itemCheckcontentWhere = [
                        'item_id'=>$arr['item_id'],//1218,//
                        'itemsig_id'=>$itemsig_id_arr,
                        'patient_id_arr'=>$patient_id_arr,
                    ];
                    //所有的表单
                    $itemCheckcontentData = $this->LocalService()->itemCheckcontent->getCount(['item_id'=>$arr['item_id']]);
                    //计划外
                    $itemPatientcheckcontentData = $this->getFormByPatientchecktime($itemCheckcontentWhere);
                    //已完成
                    $patientFormData = $this->patientFormData($itemCheckcontentWhere);
                }
            }

            foreach($patient_datas as $patient_datasKeys=>$patient_data){
                if (!empty($return_type)){
                    if ($patient_data['patient_sex'] == ''){
                        $patient_data['patient_sex'] = 2;
                    }
                }
                $field = 'patient_sex';
                $patient_sex = intval($patient_data['patient_sex']);


                //性别统计
                if($return_key == 1){
                    if($patient_sex == 2){
                        $data = [];
                        break;
                    }
                    $data[$patient_sex] = isset($data[$patient_sex]) && !empty($data[$patient_sex]) ? $data[$patient_sex] : 0;
                    $data[$patient_sex] += 1;
                }
                //年龄性别统计
                if($return_key == 2){
                    $field = 'age';
                    $patient_content_arr = json_decode($patient_data['patient_content'],1);
                    //获取受试者年龄
                    $patient_age = 0;
                    if(!empty($patient_content_arr)){
                        foreach($patient_content_arr as $content_key=>$patient_content){
                            if ($patient_content['field'] == 'age'){
                                $patient_age = $patient_content['value'];
                            }
                        }
                    }
                    if(empty($patient_age)){
                        continue;
                    }else{
                        $data[$patient_age] = isset($data[$patient_age]) && !empty($data[$patient_age]) ? $data[$patient_age] : 0;
                        $data[$patient_age] += 1;
                    }

                }
                //研究分层性别统计
                if($return_key == 3){
                    $field = 'randgroup_id';
                    $randgroup_id = $patient_data['randgroup_id'];
                    if (!empty($return_type)){
                        $data[$randgroup_id] = isset($data[$randgroup_id]) && isset($data[$randgroup_id]) && !empty($data[$randgroup_id]) ? $data[$randgroup_id] : 0;
                        $data[$randgroup_id] += 1;
                    }else{
                        $data[$randgroup_id][$patient_sex] = isset($data[$randgroup_id]) && isset($data[$randgroup_id][$patient_sex]) && !empty($data[$randgroup_id][$patient_sex]) ? $data[$randgroup_id][$patient_sex] : 0;
                        $data[$randgroup_id][$patient_sex] += 1;
                    }
                }
                //中心性别统计(或=入组数统计)
                if(in_array($return_key,[4,7])){
                    $field = 'itemsig_id';
                    $itemsig_id = $patient_data['itemsig_id'];
                    if (!empty($return_type)){
                        $data[$itemsig_id] = isset($data[$itemsig_id]) && !empty($data[$itemsig_id]) ? $data[$itemsig_id] : 0;
                        $data[$itemsig_id] += 1;
                    }else{
                        $data[$itemsig_id][$patient_sex] = isset($data[$itemsig_id]) && isset($data[$itemsig_id][$patient_sex]) && !empty($data[$itemsig_id][$patient_sex]) ? $data[$itemsig_id][$patient_sex] : 0;
                        $data[$itemsig_id][$patient_sex] += 1;
                    }
                }

                //月份统计
                if($return_key == 5){
                    $field = 'create_time';
                    $create_time = $patient_data['create_time']?date('Y-m',$patient_data['create_time']):0;
                    if (!empty($return_type)){
                        $data[$create_time] = isset($data[$create_time]) && !empty($data[$create_time]) ? $data[$create_time] : 0;
                        $data[$create_time] += 1;
                    }
                }
                //季统计
                if($return_key == 9){
                    $field = 'create_time';
                    $create_time_info = $patient_data['create_time']?date('Y-m',$patient_data['create_time']):0;
                    $create_time_arr = !empty($create_time_info) ? explode('-',$create_time_info) : 0;
                    $create_year = !empty($create_time_arr) ? $create_time_arr[0] : 0;
                    $create_month = !empty($create_time_arr) && isset($create_time_arr[1]) ? intval($create_time_arr[1]) : 0;
                    $create_key = $create_year.'-Q0';
                    if(in_array($create_month,[1,2,3])){
                        $create_key = $create_year.'-Q1';
                    }
                    if(in_array($create_month,[4,5,6])){
                        $create_key = $create_year.'-Q2';
                    }
                    if(in_array($create_month,[7,8,9])){
                        $create_key = $create_year.'-Q3';
                    }
                    if(in_array($create_month,[10,11,12])){
                        $create_key = $create_year.'-Q4';
                    }
                    if (!empty($return_type)){
                        $data[$create_key] = isset($data[$create_key]) && !empty($data[$create_key]) ? $data[$create_key] : 0;
                        $data[$create_key] += 1;
                    }
                }
                //年统计
                if($return_key == 10){
                    $field = 'create_time';
                    $create_year = $patient_data['create_time']?date('Y',$patient_data['create_time']):0;
                    if (!empty($return_type)){
                        $data[$create_year] = isset($data[$create_year]) && !empty($data[$create_year]) ? $data[$create_year] : 0;
                        $data[$create_year] += 1;
                    }
                }
                //状态统计
                if($return_key == 6){
                    $field = 'patient_status';
                    $patient_status = $patient_data['patient_status'];
                    if (!empty($return_type)){
                        $data[$patient_status] = isset($data[$patient_status]) && !empty($data[$patient_status]) ? $data[$patient_status] : 0;
                        $data[$patient_status] += 1;
                    }
                }
                //入组数统计
                if($return_key == 8){
                    $patient_name_number = '';
                    if (!empty($patient_data['patient_name'])){
                         $patient_name_number .= $patient_data['patient_name'];
                    }
                    if (!empty($patient_data['patient_number'])){
                        $patient_name_number .= '【'.$patient_data['patient_number'].'】';
                    }
                    $planNumber = isset($itemPatientcheckcontentData[$patient_data['id']])?$itemPatientcheckcontentData[$patient_data['id']]:0;
                    $completeNumber = isset($patientFormData[$patient_data['id']])?$patientFormData[$patient_data['id']]:0;
                    $temps = [];
                    $temps['label'] = $patient_name_number;
                    $temps['value'] = $completeNumber;
                    $temps['number'] = $itemCheckcontentData + $planNumber;
                    $data[$patient_datasKeys] = $temps;
                }
            }

            //受试者方式分布
            if($return_key == 11){
                //查询检查点
                $checktimeDatas = $this->LocalService()->itemChecktime->fetchAll([
                    'where'=> [
                        'item_id' => $item_id,
                        'is_del' => 0,
                    ],
                    'columns'=>['id','label'=>'check_name','var_name'],
                    'order'=>['check_order','id'],
                ]);

                //查询受试者检查点分布
                $patientchecktimeDatas = $this->LocalService()->itemPatientchecktime->fetchAll([
                    'where'=>[
                        'is_now_state' => 1,
                        'patient_id' => $patient_id_arr,
                        'is_del' => 0,
                        'item_id' => $arr['item_id'],
                    ],
                    'columns'=>['id','checktime_id','patient_id','itemsig_id'],
                    'group'=>'patient_id'
                ]);

                if($return_type == 2){
                    //获取中心
                    $whereitemSignatory['where'] = [
                        'id' => $itemsig_id_arr,
                        'is_del' => 0,
                    ];
                    $whereitemSignatory['columns'] = ['id','label'=>'number','signatory_id'];
                    $whereitemSignatory['order'] = ['order','number','id'];
                    $itemSignatoryDatas = $this->LocalService()->itemSignatory->fetchAll($whereitemSignatory);

                    $signatoryidArr = array_column($itemSignatoryDatas,'signatory_id');
                    $signInfo = $this->LocalService()->signatoryInfo->fetchCol('info_name',[
                        'id' => $signatoryidArr
                    ]);

                    $nowChecktime = [];
                    foreach($patientchecktimeDatas as $checkK=>$checkV){
                        $nowChecktime[$checkV['itemsig_id']][$checkV['checktime_id']][] = $checkV['patient_id'];
                    }

                    $signCount = [];
                    foreach($itemSignatoryDatas as $signkey=>&$signvalue){
                        $signvalue['info_name'] = $signInfo[$signvalue['signatory_id']];
                        foreach($checktimeDatas as $k=>$v){
                            $index = $nowChecktime[$signvalue['id']][$v['id']];
                            $signvalue['V'.$k] = isset($index) ? count($index) : 0;
                            $signCount['V'.$k] += isset($index) ? count($index) : 0;
                        }
                    }

                    $data = [$itemSignatoryDatas,$signCount];

                }else{

                    $nowChecktime = [];
                    foreach($patientchecktimeDatas as $checkK=>$checkV){
                        $nowChecktime[$checkV['checktime_id']][] = $checkV['patient_id'];
                    }

                    foreach($checktimeDatas as $key=>$value){
                        if(isset($nowChecktime[$value['id']])){
                            $checktimeDatas[$key]['value'] = count($nowChecktime[$value['id']]);
                        }else{
                            $checktimeDatas[$key]['value'] = 0;
                        }
                    }
                    $data = $checktimeDatas;
                }
            }

            ksort($data);
            if (!empty($data) && !empty($return_type)){
                $temp = [];
                $newData = [];
                if($return_key == 8 || $return_key == 11){
                    return $data;
                }

                foreach ($data as $key=>$datum) {
                    if (isset($patientType[$field])){
                        $keys = $patientType[$field][$key];
                        $temp['label'] = $keys;
                        $temp['value'] = $datum;
                        $temp['id'] = $key;
                        if ($return_key == 7 || $return_key == 4){
                            $planJoingroup = 0;
                            if (isset( $itemSignatoryData[$key]['plan_joingroup'])){
                                $planJoingroup = intval($itemSignatoryData[$key]['plan_joingroup']);
                            }
                            $temp['number'] = $planJoingroup;
                            $temp['score'] = 0;
                            if (!empty($planJoingroup)){

                                $temp['score'] = round(($datum/$planJoingroup)*100,2);
                            }
                        }

                        $newData[] = $temp;

                    }else{
                        $temp['label'] = $key;
                        $temp['value'] = $datum;
                        $newData[] = $temp;

                    }
                }

                return $newData;
            }
        }
        return $data;
    }

    /**
     * Notes:获取指定键值下的受试者信息
     * User: lltyy
     * DateTime: 2022/9/21 14:53
     *
     * @param $where
     * @param $key
     */
    public function getPatientByKey($where,$columns=[],$order=[],$key){
        $datas = [];
        $where_cond = [
            'where'=>$where,
            'columns'=>$columns,
            'order'=>$order
        ];
        $patients = $this->fetchAll($where_cond);
        if(!empty($patients)){
            foreach($patients as $patient){
                $key_id = $patient[$key];
                $datas[$key_id][] = $patient;
            }
        }
        return $datas;
    }

    /**
     * @note 如果非新增操作中，隐私字段且登录人是隐私字段管理员，则类型为原类型，否则为Text类型（只读）
     * @param int $item_id
     * @param string $fieldProp
     * @param string $fieldType
     * @param bool $isAdd
     * @return string
     * @throws ExceptionInterface
     */
    private function getPatientattrFormFieldType(int $item_id, string $fieldProp, string $fieldType, bool $isAdd = true) : string
    {
        $privacyPatientAttrs = $this->LocalService()->patientattrs->getPrivacyPatientAtts($item_id);

        return in_array($fieldProp, $privacyPatientAttrs) && !$this->LocalService()->identity->isValidMaskingAdmin() && !$isAdd ? 'Text' : $fieldType;
    }

    /**
     * Notes: 重组受试者属性信息
     * User: lltyy
     * DateTime: 2022/10/14 11:19
     *
     * @param $patientattrData
     * @param array $randGroupData
     * @param array $itemSignatoryUser
     * @param string $randGroupId
     * @param bool $isAdd
     * @return array
     * @throws ExceptionInterface
     */
    public function getPatientattrTemplate($patientattrData,$randGroupData=[],$itemSignatoryUser=[],$randGroupId='randgroup_id', bool $isAdd = true){
        $item_id = current($patientattrData)['item_id'] ?? 0;

        //属性类型
        $dictionaryFormtypeData = $this->LocalService()->dictionaryFormtype->fetchCol('type_code','is_del = 0');
        $patientattr = [];
        if (!empty($patientattrData)){
            foreach ($patientattrData as $k=>&$v){
                if (empty($v['attr_type'])){
                    $fieldType = isset($dictionaryFormtypeData[$v['attr_type_id']])?$dictionaryFormtypeData[$v['attr_type_id']]:'text';
                    $v['attr_type'] = $this->fieldType($fieldType);
                }
                $row = array_merge($v, ['name' => $v['attr_name']]);
                switch ($v['attr_type']){
                    case 1:
                        $patientattr[] = [
                            'type'=> $this->getPatientattrFormFieldType($item_id, $v['attr_field'], 'Input', $isAdd),
                            'label'=>$v['attr_name'],
                            'placeholder'=>'请输入'.$v['attr_name'],
                            'prop'=>$v['attr_field'],
                            'id'=>$v['id'],
                            'rules'=>$this->LocalService()->itemForm->getRules($row),
                        ];
                        break;
                    case 2:
                        $patientattr[] = [
                            'type'=> $this->getPatientattrFormFieldType($item_id, $v['attr_field'], 'Number', $isAdd),
                            'label'=>$v['attr_name'],
                            'placeholder'=>'请输入'.$v['attr_name'],
                            'prop'=>$v['attr_field'],
                            'id'=>$v['id'],
                            'rules'=>$this->LocalService()->itemForm->getRules($row),
                        ];

                        break;
                    case 3:
                        if (!empty($v['content'])){
                            $contentArr = json_decode($v['content'],1);
                            $radios = [];
                            foreach ($contentArr as $kc =>$vc){
                                $radios[] = ['label'=>$vc['select_name'],'value'=>$vc['select_variable']];
                            }
                            $patientattr[] = [
                                'type'=> $this->getPatientattrFormFieldType($item_id, $v['attr_field'], 'Radio', $isAdd),
                                'label'=>$v['attr_name'],
                                'placeholder'=>'请输入'.$v['attr_name'],
                                'prop'=>$v['attr_field'],
                                'id'=>$v['id'],
                                'radios'=>$radios,
                                'rules'=>$this->LocalService()->itemForm->getRules($row),
                            ];
                        }

                        break;
                    case 4:

                        if (!empty($v['content'])){

                            $contentArr = json_decode($v['content'],1);
                            $options = [];
                            foreach ($contentArr as $kc =>$vc){
                                $options[] = ['label'=>$vc['select_name'],'value'=>$vc['select_variable']];
                            }
                            $patientattr[] = [
                                'type'=> $this->getPatientattrFormFieldType($item_id, $v['attr_field'], 'Checkbox', $isAdd),
                                'label'=>$v['attr_name'],
                                'placeholder'=>'请输入'.$v['attr_name'],
                                'prop'=>$v['attr_field'],
                                'id'=>$v['id'],
                                'checkboxs' => $options,
                                'rules'=>$this->LocalService()->itemForm->getRules($row),
                            ];
                        }

                        break;
                    case 5:
                        $patientattr[] = [
                            'type'=> $this->getPatientattrFormFieldType($item_id, $v['attr_field'], 'Date', $isAdd),
                            'label'=>$v['attr_name'],
                            'placeholder'=>'请输入'.$v['attr_name'],
                            'prop'=>$v['attr_field'],
                            'id'=>$v['id'],
                            'rules'=>$this->LocalService()->itemForm->getRules($row),
                        ];
                        break;
                    case 6:
                        $patientattr[] = [
                            'type'=> $this->getPatientattrFormFieldType($item_id, $v['attr_field'], 'Uk', $isAdd),
                            'label'=>$v['attr_name'],
                            'placeholder'=>'请输入'.$v['attr_name'],
                            'prop'=>$v['attr_field'],
                            'id'=>$v['id'],
                            'rules'=>$this->LocalService()->itemForm->getRules($row),
                        ];
                        break;
                    case 7:
                        if (!empty($v['content'])){

                            $contentArr = json_decode($v['content'],1);
                            $options = [];
                            foreach ($contentArr as $kc =>$vc){
                                $options[] = ['label'=>$vc['select_name'],'value'=>$vc['select_variable']];
                            }
                            $patientattr[] = [
                                'type'=> $this->getPatientattrFormFieldType($item_id, $v['attr_field'], 'Select', $isAdd),
                                'label'=>$v['attr_name'],
                                'placeholder'=>'请输入'.$v['attr_name'],
                                'prop'=>$v['attr_field'],
                                'id'=>$v['id'],
                                'options' => $options,
                                'rules'=>$this->LocalService()->itemForm->getRules($row),
                            ];
                        }else{
                            if(($v['attr_field'] == $randGroupId) && !empty($randGroupData)){
                                $patientattr[] = [
                                    'type'=> $this->getPatientattrFormFieldType($item_id, $v['attr_field'], 'Select', $isAdd),
                                    'id'=>$v['id'],
                                    'label'=>$v['attr_name'],
                                    'placeholder'=>'请输入'.$v['attr_name'],
                                    'prop'=>$v['attr_field'],
                                    'options' => $randGroupData,
                                    'rules'=>$this->LocalService()->itemForm->getRules($row),
                                ];
                            }else if(($v['attr_field'] == 'signatory_user_id')){// && !empty($itemSignatoryUser)
                                $patientattr[] = [
                                    'type'=> $this->getPatientattrFormFieldType($item_id, $v['attr_field'], 'Select', $isAdd),
                                    'id'=>$v['id'],
                                    'label'=>$v['attr_name'],
                                    'placeholder'=>'请输入'.$v['attr_name'],
                                    'prop'=>$v['attr_field'],
                                    'options' => $itemSignatoryUser,
                                    'rules'=>$this->LocalService()->itemForm->getRules($row),
                                ];
                            }
                        }
                        break;
                    case 8:
                        $patientattr[] = [
                            'type'=> $this->getPatientattrFormFieldType($item_id, $v['attr_field'], 'UploadImg', $isAdd),
                            'label'=>$v['attr_name'],
                            'placeholder'=>'请输入'.$v['attr_name'],
                            'prop'=>$v['attr_field'],
                            'id'=>$v['id'],
                            'fileListImg'=>[],
                            'rules'=>$this->LocalService()->itemForm->getRules($row),
                        ];
                        break;
                    case 9:
                        $patientattr[] = [
                            'type'=> $this->getPatientattrFormFieldType($item_id, $v['attr_field'], 'UploadFile', $isAdd),
                            'label'=>$v['attr_name'],
                            'placeholder'=>'请输入'.$v['attr_name'],
                            'prop'=>$v['attr_field'],
                            'id'=>$v['id'],
                            'fileList'=>[],
                            'rules'=>$this->LocalService()->itemForm->getRules($row),
                        ];
                        break;
                    case 10:
                        $patientattr[] = [
                            'type'=> $this->getPatientattrFormFieldType($item_id, $v['attr_field'], 'Textarea', $isAdd),
                            'label'=>$v['attr_name'],
                            'placeholder'=>'请输入'.$v['attr_name'],
                            'prop'=>$v['attr_field'],
                            'id'=>$v['id'],
                            'rules'=>$this->LocalService()->itemForm->getRules($row),
                        ];
                        break;
                    case 11:
                        $patientattr[] = [
                            'type'=> $this->getPatientattrFormFieldType($item_id, $v['attr_field'], 'DateTimeSecond', $isAdd),
                            'label'=>$v['attr_name'],
                            'placeholder'=>'请输入'.$v['attr_name'],
                            'prop'=>$v['attr_field'],
                            'id'=>$v['id'],
                            'rules'=>$this->LocalService()->itemForm->getRules($row),
                        ];
                        break;
                    case 12:
                        $patientattr[] = [
                            'type'=> $this->getPatientattrFormFieldType($item_id, $v['attr_field'], 'DateTime', $isAdd),
                            'label'=>$v['attr_name'],
                            'placeholder'=>'请输入'.$v['attr_name'],
                            'prop'=>$v['attr_field'],
                            'id'=>$v['id'],
                            'rules'=>$this->LocalService()->itemForm->getRules($row),
                        ];
                        break;
                    case 17:
                            $radios = [];
                            $patientattr[] = [
                                'type'=> $this->getPatientattrFormFieldType($item_id, $v['attr_field'], 'Cascader', $isAdd),
                                'label'=>$v['attr_name'],
                                'placeholder'=>'请输入'.$v['attr_name'],
                                'prop'=>$v['attr_field'],
                                'id'=>$v['id'],
                                'cascaderOptions'=>$radios,
                                'rules'=>$this->LocalService()->itemForm->getRules($row),
                            ];
                        break;
                }
            }
        }
        return $patientattr;
    }
    public function fieldType($type='text'){
        $fieldTypeData = [
            1=>['text'],
            2=>['integer','decimal_one','decimal_two','decimal_three'],
            3=>['radio'],
            4=>['checkbox'],
            5=>['date_ymd'],
            6=>['date_uk'],
            7=>['select'],
            8=>['upload_img'],
            9=>['upload_file'],
            10=>['textarea'],
            11=>['date_ymd_hi'],
            12=>['date_ymd_his'],
            17=>['Cascader'],

        ];
        foreach ($fieldTypeData as $fieldTypeDataKey=>$fieldTypeDataValue) {
            if (in_array($type,$fieldTypeDataValue)){
                return $fieldTypeDataKey;
            }
        }
        return 1;
    }

    //表单配置切换获取随机时，调整受试者数据
    public function delGroupAndNumber($item_id,$type = 0){//0手改自，1自改手
        if(empty($item_id)){
            return false;
        }
        $wherePatient = [
            'is_del' => 0,
            'item_id' => $item_id,
        ];
        $patientCount = $this->LocalService()->patient->getCount($wherePatient);
        if(empty($patientCount)){
            return true;
        }
        $patientNumberIdData = $this->LocalService()->patient->fetchCol('random_number_id',$wherePatient);
        if (!empty($type)){
            $itemRandomdetailsIds = implode(',',array_filter(array_unique($patientNumberIdData)));

            if (!empty($itemRandomdetailsIds)){
                $upItemRandomdetails['is_use'] = 0;
                $resultItemRandomdetails = $this->LocalService()->itemRandomdetails->update($upItemRandomdetails,[
                    'is_annul' => 0,
                    'id' => array_filter(array_unique($patientNumberIdData)),
                ]);
            }
        }
        $upItemPatient['random_number_id'] = 0;
        $upItemPatient['random_number'] = '';
        $upItemPatient['randgroup_id'] = 0;

        $this->LocalService()->patient->update($upItemPatient,[
            'is_del' => 0,
            'id' => array_keys($patientNumberIdData)
        ]);
        return true;

    }

    /**
     * Notes:获取指定键值下的信息
     * User: lltyy
     * DateTime: 2022/9/21 14:53
     *
     * @param $where //查询条件
     * @param array $columns //查询字段
     * @param array $order //排序值
     * @param array $key_arr //键值数组【键值=>数据类型（0 单笔 1 多笔）】
     * @return array
     * @return array
     */
    public function fetchDataByKey($where,$columns=[],$order=[],$key_arr=[]){
        $arr = [];
        $where_cond = [
            'where'=>$where,
            'columns'=>$columns,
            'order'=>$order
        ];
        $datas = $this->fetchAll($where_cond);
        if(!empty($datas)){
            foreach($datas as $data){
                foreach($key_arr as $key=>$data_type){
                    $key_id = $data[$key];
                    if($data_type == 1){
                        $arr[$key][$key_id][] = $data;
                    }else{
                        $arr[$key][$key_id] = $data;
                    }
                }
            }
        }
        return $arr;
    }


    public function isPatientLock($item_id = 0,$is_lock = 0){
        if (empty($item_id)) return false;
        $patientInfo = $this->LocalService()->patient->fetchOne([
            'where'=>[
                'is_del' => 0,
                'item_id' => $item_id,
            ],
        ]);
        if (!empty($patientInfo)){
            $result = $this->LocalService()->patient->update(['is_lock'=>$is_lock],[
                'is_del' => 0,
                'item_id' => $item_id,
            ]);
        }
        return true;
    }

    /**
     * Notes : 获取受试者，格式按照 姓名 + 中心号+筛选号
     * Author:唐伯虎不虎
     * Date:2023/6/8 10:45
     */
    public function getpatient($item_id)
    {
        //查询父级ID
        $fid = $this->LocalService()->itemInfo->getOneFieldVal('fid',[
            'is_del' => 0,
            'id' => $item_id,
        ]);//获取项目名称

        //查询项目下所有中心
        $sign = $this->LocalService()->itemSignatory->fetchAll([
            'where' => [
                'is_del' => 0,
                'item_id' => $fid,
            ],
            'columns' => ['id', 'item_id', 'signatory_id','is_teamleader', 'number', 'remark','order'],
            'order' => ['order','id'],
        ]);
        $signDatas = [];
        foreach($sign as $k=>$v){
            $signDatas[$v['id']] = $v['number'];
        }
        $patientDatas = $this->LocalService()->patient->fetchAll(
            [
                'where'=> [
                    'is_del' => 0,
                    'item_id' => $item_id,
                ],
                'columns'=>['value'=>'id','label'=>'patient_name','patient_number','itemsig_id'],
                'order'=>['patient_number asc','id'],
            ]
        );

        foreach($patientDatas as $k=>$v){
            if(!empty($signDatas[$v['itemsig_id']])){
                if(empty($v['patient_name'])){
                    $patientDatas[$k]['patient_name'] = $signDatas[$v['itemsig_id']];
                }else{
                    $patientDatas[$k]['patient_name'] = $v['patient_name'].'_'.$signDatas[$v['itemsig_id']];

                }
                if($v['patient_number'] != '') $patientDatas[$k]['patient_name'] .= '-'.$v['patient_number'];
            }else{
                if(empty($v['patient_name'])) {
                    $patientDatas[$k]['patient_name'] = $signDatas[$v['itemsig_id']];
                }else{
                    if($v['patient_number'] != '') $patientDatas[$k]['patient_name'] .= '_'.$v['patient_number'];
                }
            }
        }

        return $patientDatas;
    }

    public function getpater($item_id)
    {
        $fid = $this->LocalService()->itemInfo->getOneFieldVal('fid',[
            'is_del' => 0,
            'id' => $item_id,
        ]);//获取项目名称

        $datas = $this->LocalService()->realRolemodulerelation->fetchAll(
            [
                'where'=> [
                    'module_id' => [87, 88],
                    'status' => 0,
                    'item_id' => $fid,
                ],
                'columns'=>['role_id'],
            ]
        );
        $role_id = implode(',',array_unique(array_column($datas,'role_id')));
        $useridArr = [];
        if(!empty($role_id)){
            $userid = $this->LocalService()->roleSignatoryRelation->fetchCol('signatory_user',[
                'role_id' => array_unique(array_column($datas,'role_id')),
                'is_del' => 0,
                'status' => 0,
            ]);
            $backdata = [];
            foreach($userid as $k=>$v){
                if(in_array($v,$useridArr)) continue;
                $useridArr[] = $v;
                $pater_tel = $this->LocalService()->signatoryUser->getOneFieldVal('user_tel',[
                    'is_del' => 0,
                    'id' => $v,
                ]);//获取项目名称
                if(empty($pater_tel)) continue;
                $username = $this->LocalService()->adminUser->fetchOne(['where'=> [
                    'is_del' => 0,
                    'mobile' => $pater_tel,
                ],'columns'=>['realname','id']]);//获取项目名称

                $arr['value'] = $username['id'];
                $arr['label'] = $username['realname'];
                $backdata[] = $arr;
            }
            return $backdata;
        }
        return [];
    }

    /**
     * Notes: 获取计划外下的表单数据
     * @param array $data
     *    item_id 副项目ID
     *    itemsig_id 项目中心ID
     *    patient_id_arr 受试者ID数组
     */
    public function getFormByPatientchecktime($data=[]){
        $item_id = isset($data['item_id']) ? $data['item_id'] : 0;//副项目ID
        $itemsig_id = isset($data['itemsig_id']) ? $data['itemsig_id'] : 0;//项目中心ID
        $patient_id_arr = isset($data['patient_id_arr']) ? $data['patient_id_arr'] : [];//受试者ID数组
        $where = [
            'is_del'=>0,
            'item_id'=>$item_id,
        ];
        if(!empty($itemsig_id)){
            $where['itemsig_id']= $itemsig_id;
        }
        if(!empty($patient_id_arr)){
            $where['patient_id']= $patient_id_arr;
        }

        $where_arr = [
            'where'=>$where,
            'columns'=>['patient_id','patientchecktime_id','form_id','is_choose']
        ];

        $info_datas = $this->LocalService()->itemPatientcheckcontent->fetchAll($where_arr);
        $arr = [];
        if(!empty($info_datas)){
            foreach($info_datas as $info_data){
                $check_id = $info_data['patientchecktime_id'];
                $patient_id = $info_data['patient_id'];
                $arr[$patient_id] += 1;
            }
        }
        return $arr;
    }



    public function patientFormData($data=[]){

        //已完成的工作===yikeen_item_patient_form
        $item_id = isset($data['item_id']) ? $data['item_id'] : 0;//副项目ID
        $itemsig_id = isset($data['itemsig_id']) ? $data['itemsig_id'] : 0;//项目中心ID
        $patient_id_arr = isset($data['patient_id_arr']) ? $data['patient_id_arr'] : [];//受试者ID数组
        $where = [
            'is_del'=>0,
            'is_complete'=>1,
            'item_id'=>$item_id,
        ];
        if(!empty($itemsig_id)){
            $where['itemsig_id']= $itemsig_id;
        }
        if(!empty($patient_id_arr)){
            $where['patient_id']= $patient_id_arr;
        }

        $where_arr = [
            'where'=>$where,
            'columns'=>['patient_id','patientchecktime_id','form_id','is_complete']
        ];
        $patientFormData = $this->LocalService()->patientForm->fetchAll($where_arr);
        $arr = [];
        if(!empty($patientFormData)){
            foreach($patientFormData as $info_data){
                $patient_id = $info_data['patient_id'];
                $arr[$patient_id] += 1;
            }
        }
        return $arr;

    }

    //获取中心名称
    public function getItemSigName($where){
        $itemSignatoryData = $this->LocalService()->itemSignatory->fetchAll($where);
        if(empty($itemSignatoryData)){
            return $itemSignatoryData;
        }
        $itemSignatoryData = array_column($itemSignatoryData,null,'id');
        $sign_id_arr = array_filter(array_unique( array_column($itemSignatoryData,'signatory_id')));
        $whereSignatoryInfo = [
            'where'=>[
                'is_del'=>0,
                'id'=>$sign_id_arr,
            ],
            'columns'=>[
                'id',
                'info_name',
            ],
        ];
        $sign_datas = $this->LocalService()->signatoryInfo->fetchCol('info_name',$whereSignatoryInfo['where']);
        if (!empty($sign_datas)){
            foreach ($itemSignatoryData as $itemsigIdk=>&$infoIdv){
                $infoIdv['signatory_name'] = '';
                if(isset($sign_datas[$infoIdv['signatory_id']])){
                    $infoIdv['signatory_name'] = $sign_datas[$infoIdv['signatory_id']];
                }
            }
        }
        return $itemSignatoryData;
    }

    //字段转换
    public function patientBasicFieldType(){
        $patientType = [
            'patient_sex'=>[
                0=>'男',
                1=>'女',
                2=>'未知',
            ],
            'randgroup_id'=>[
                0=>'未分组',
            ],
            'itemsig_id'=>[
                0=>'未知中心',
            ],
            'patient_status'=>[
                0=>'未知',
                1=>'脱落',
                2=>'筛败',
                3=>'完成',
                4=>'终止',
                9=>'进行中',
            ],

        ];
        return $patientType;
    }

    public function getFormDrug($where = []){
        $enum = new Enum();
        $types =  $enum::FORM_FIELD_TYPE_RADIO.','. $enum::FORM_FIELD_TYPE_CHECKBOX.','. $enum::FORM_FIELD_TYPE_DROPDOWN;
        $itemFormWhere = [
            'is_del' => 0,
            'group_id' => 4,
        ];
        $itemFormData = $this->LocalService()->itemForm->fetchCol('name',$itemFormWhere);
        if (empty($itemFormData))  return [];
        $formIdArr = array_keys($itemFormData);

        $itemFormFieldWhere = [
            'is_del' => 0,
            'name' => '药物名称',
            'form_id' => $formIdArr,
        ];
        $condTypeFlag = 0;
        if (isset($where['condType'])){
            $condTypeFlag = 1;
            if ($where['condType'] == 3){
                $condTypeFlag = 3;
                $itemFormFieldWhere = [
                    'is_del' => 0,
                    'is_disease' => 1,
                ];
            }
            $itemFormData = $this->LocalService()->itemFormField->fetchCol('form_id',$itemFormFieldWhere);
            if (empty($itemFormData))  return [];
            $formIdArr = $itemFormData;
        }


        $formContentWhere = [
            'where'=>[
                'is_del'=>0,
                'form_id'=>$formIdArr,
            ],
            'columns'=>[
                'id','patient_id','form_id','item_id','itemsig_id','checktime_id','data'
            ]

        ];
        if (!isset($where['type']) && empty($where['type'])){
            $limit = $where['limit'] ?: 20;
            $page = $where['page'] ?: 1;
            $offset = intval(($page - 1) * $limit);
            $formContentWhere['limit'] = $limit;
            $formContentWhere['offset'] = $offset;
        }


        if (empty($condTypeFlag)){
            $itemFormData = $this->LocalService()->itemFormField->fetchCol('name',$itemFormFieldWhere);
        }else if($condTypeFlag == 3){
            $itemFormData = $this->fieldTypeMoreData();
        }

        if (isset($where['formContentIds'])) $formContentWhere['where']['id'] = explode(',',$where['formContentIds']);
        $patientformcontent = $this->LocalService()->patientFormContent->fetchAll($formContentWhere);
        $patientformcontentCount = $this->LocalService()->patientFormContent->getCount($formContentWhere['where']);

        $redisData = [];
        foreach ($patientformcontent as $patientformcontentKey=>&$patientformcontentValue){
            $patientformcontentValue['drug_id'] = 0;
            $patientformcontentValue['disease_id'] = 0;
            $flag = 0;
            if (!empty($patientformcontentValue['data'])){
                $formDrugDatas = $patientformcontentValue['data'] = json_decode($patientformcontentValue['data'],true);
                if (!empty($formDrugDatas)){
                    foreach ($formDrugDatas as $formDrugDatasKey=>&$formDrugDatasValue){
                        if (empty($condTypeFlag)){
                            if (isset($itemFormData[$formDrugDatasKey])){
                                if (!empty($formDrugDatasValue)){
                                    $patientformcontentValue['drug_name'] = trim($formDrugDatasValue);
                                    $patientformcontentValue['drug_id'] = $formDrugDatasKey;
                                    $flag = 1;
                                    if (isset($redisData[$patientformcontentValue['drug_name']])){
                                        $redisData[$patientformcontentValue['drug_name']] .= ','.$patientformcontentValue['id'];
                                    }else{
                                        $redisData[$patientformcontentValue['drug_name']] = $patientformcontentValue['id'];
                                    }
                                }

                            }
                        }else if($condTypeFlag == 3){
                            if (!empty($itemFormData)){
                                $itemFormData = array_column($itemFormData,null,'id');
                            }

                            if (isset($itemFormData[$formDrugDatasKey])){
                                if ($itemFormData[$formDrugDatasKey]['type'] == $enum::FORM_FIELD_TYPE_TEXT){
                                    if (!empty($formDrugDatasValue)){
                                        $patientformcontentValue['name'] = trim($formDrugDatasValue);
                                        $patientformcontentValue['disease_id'] = $formDrugDatasKey;
                                        $flag = 1;
                                        if (isset($redisData[$patientformcontentValue['name']])){
                                            $redisData[$patientformcontentValue['name']] .= ','.$patientformcontentValue['id'];
                                        }else{
                                            $redisData[$patientformcontentValue['name']] = $patientformcontentValue['id'];
                                        }
                                    }


                                }else if(in_array($itemFormData[$formDrugDatasKey]['type'],explode(',',$types))){
                                    if (!empty($formDrugDatasValue)){
                                        if (!is_array($formDrugDatasValue)){
                                            $formDrugDatasValue = explode(',',$formDrugDatasValue);
                                        }
                                        foreach ($formDrugDatasValue as $formTypeData) {
                                            if(isset($itemFormData[$formDrugDatasKey]['radio'][$formTypeData])){
                                                $formTypeName = $itemFormData[$formDrugDatasKey]['radio'][$formTypeData];
                                                if (!empty($formTypeName)){
                                                    $patientformcontentValue['name'] .= trim($formTypeName).',';
                                                    $patientformcontentValue['disease_id'] = $formDrugDatasKey;
                                                    $flag = 1;
                                                    if (isset($redisData[$formTypeName])){
                                                        $redisData[$formTypeName] .= ','.$patientformcontentValue['id'];
                                                    }else{
                                                        $redisData[$formTypeName] = $patientformcontentValue['id'];
                                                    }
                                                }

                                            }
                                        }
                                        $patientformcontentValue['name'] = trim($patientformcontentValue['name'],',');
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if (empty($flag)){
                unset($patientformcontent[$patientformcontentKey]);
            }
        }
        if (isset($where['type']) && !empty($where['type']) && !empty($redisData)){
            if (empty($condTypeFlag)){
                $this->redisDatas($redisData,1);
            }else if($condTypeFlag == 3){
                $this->redisDatas($redisData,1,'','diseaseName');
            }
        }
        $returnData['patientformcontent'] = $patientformcontent;
        $returnData['patientformcontentCount'] = $patientformcontentCount;
        return $returnData;
    }

    public function redisDatas($data=[],$type=0,$keys = '',$redisK = 'drugName'){
        $redis = Laminas::$serviceManager->redisExtend->setDatabase(14)->getRedisInstance();
        $result = '';
        if ($type == 1){
            foreach ($data as $drugName => $formContentIds){
                $result = $redis->set($redisK.':'.$drugName,$formContentIds);
            }
        }else if($type == 2){
            !empty($keys) && $result = $redis->get($keys);
        }else{
            if (empty($keys)){
                $keys = '*';
            }else{
                $keys = '*'.$keys.'*';
            }

            $result = $redis->keys($redisK.':'.$keys);
        }
        return $result;
    }

    public function fieldTypeMoreData(){
        $enum = new Enum();
        $types =  $enum::FORM_FIELD_TYPE_RADIO.','. $enum::FORM_FIELD_TYPE_CHECKBOX.','. $enum::FORM_FIELD_TYPE_DROPDOWN;
        $itemFormFieldWhere['where'] = 'is_del=0  and is_disease = 1 and type in('.$enum::FORM_FIELD_TYPE_TEXT.','.$types.')';
        $itemFormFieldWhere['columns'] = ['id','name','parent','is_disease','type','form_id'];
        $itemFormFieldData = $this->LocalService()->itemFormField->fetchAll($itemFormFieldWhere);

        $radioArr = [];
        $radioData = [];
        $radioDatas = [];
        if (!empty($itemFormFieldData)){
            $parentIdArr = [];
            $parentIdStr = '';
            foreach ($itemFormFieldData as $itemFormFieldDataK=>$itemFormFieldDataV){
                if (in_array($itemFormFieldDataV['type'],explode(',',$types))){
                    $parentIdArr[] = $itemFormFieldDataV['id'];
                    $parentIdStr .= $itemFormFieldDataV['id'].',';
                }
            }

            if (!empty($parentIdArr)){
                $itemFormFieldParentWhere['where'] = [
                    'is_del' => 0,
                    'parent' => $parentIdArr,
                ];
                $itemFormFieldParentWhere['columns'] = ['id','name','parent','is_disease','type','form_id'];
                $itemFormMoreData = $this->LocalService()->itemFormField->fetchAll($itemFormFieldParentWhere);

                if (!empty($itemFormMoreData)){
                    $itemFormMoreId = array_column($itemFormMoreData,'id');
                    $itemFormFieldRadioWhere['where'] = [
                        'field_id' => $itemFormMoreId
                    ];
                    $itemFormFieldRadioWhere['columns'] = ['id','value','field_id'];
                    $itemFormFieldRadioData = $this->LocalService()->itemFormFieldRadio->fetchAll($itemFormFieldRadioWhere);
                    $i = 0;
                    if (!empty($itemFormFieldRadioData)){
                        foreach ($itemFormMoreData as $itemFormMoreDataK=>&$itemFormMoreDataV){
                            foreach ($itemFormFieldRadioData as $itemFormFieldRadioDataK=>$itemFormFieldRadioDataV){
                                if ($itemFormFieldRadioDataV['field_id'] == $itemFormMoreDataV['id']){
                                    $radioArr[$itemFormMoreDataV['parent']][$itemFormFieldRadioDataV['value']] = $itemFormMoreDataV['name'];
                                    $radioData[$itemFormMoreDataV['parent']][$i]['id'] = $itemFormMoreDataV['id'];
                                    $radioData[$itemFormMoreDataV['parent']][$i]['name'] = $itemFormMoreDataV['name'];
                                    $radioData[$itemFormMoreDataV['parent']][$i]['radioId'] = $itemFormFieldRadioDataV['id'];
                                    $radioData[$itemFormMoreDataV['parent']][$i]['radioValue'] = $itemFormFieldRadioDataV['value'];
                                    $radioData[$itemFormMoreDataV['parent']][$i]['form_id'] = $itemFormMoreDataV['form_id'];
                                    $radioData[$itemFormMoreDataV['parent']][$i]['parent_field_id'] = $itemFormMoreDataV['parent'];

                                    $radioDatas[$i]['id'] = $itemFormMoreDataV['id'];
                                    $radioDatas[$i]['name'] = $itemFormMoreDataV['name'];
                                    $radioDatas[$i]['radioId'] = $itemFormFieldRadioDataV['id'];
                                    $radioDatas[$i]['radioValue'] = $itemFormFieldRadioDataV['value'];
                                    $radioDatas[$i]['form_id'] = $itemFormMoreDataV['form_id'];
                                    $radioDatas[$i]['parent_field_id'] = $itemFormMoreDataV['parent'];

                                    $i++;
                                }
                            }
                        }
                    }


                }

            }

            foreach ($itemFormFieldData as $itemFormFieldDataKs=>&$itemFormFieldDataVs){
                if (isset($radioArr[$itemFormFieldDataVs['id']])){
                    $itemFormFieldDataVs['radio'] = $radioArr[$itemFormFieldDataVs['id']];
                }else{
                    $a[$itemFormFieldDataVs['id']] = $itemFormFieldDataVs['name'];
                    $itemFormFieldDataVs['radio'][$itemFormFieldDataVs['id']] = $itemFormFieldDataVs['name'];
                }

            }
        }

        return $itemFormFieldData;
    }

    public function asyncSend($where = []){
        if(empty($where['db_file_name']) || empty($where['method_name'])) return false;
        $this->LocalService()->swTaskClient->send([
            'svName' => $where['db_file_name'],
            'methodName' => $where['method_name'],
            'params' => $where
        ]);
        return true;
    }


    public function checkCollectPatient($where = []){

        $newData = [];
        $data = ['msg'=>'','newData'=>[]];
        $collectPatientDatas = [];
        if (empty($where['collect_patient_id'])){
            $data['msg'] = '病例库的受试者id不能为空';
            return $data;
        }
        $collectPatient = [
            'where'=> [
                'is_del' => 0,
                'id' => explode(',', $where['collect_patient_id'])
            ],
        ];
        $collectPatientData = $this->LocalService()->collectPatient->fetchAll($collectPatient);
        if (empty($collectPatientData)){
            $data['msg'] = '数据不存在';
            return $data;
        }
        $collectPatientDatas = array_column($collectPatientData,null,'id');
        $collectPatientTel = array_filter(array_column($collectPatientData,'patient_tel'));

        //属性查询
        $wherePatientattr['where'] = [
            'is_del' => 0,
            'item_id' => $where['item_id'],
        ];
        $wherePatientattr['order'] = ['attr_order','id'];
        $wherePatientattr['columns'] = ['id','attr_name'=>'attr_name','attr_field'=>'attr_field','attr_type'=>'attr_type','is_required'=>'is_required','content'=>'content','patient_write','attr_type_id'];
        $patientattrData = $this->LocalService()->patientattrs->fetchAll($wherePatientattr);
        if (empty($patientattrData)){
            $data['msg'] = '还未设置字段属性不可添加';
            return $data;
        }

        //验证手机号
        if (!empty($collectPatientTel)){
            $telWhere = [
                'where'=>[
                    'is_del'=>0,
                    'patient_tel'=>$collectPatientTel,
                ],
            ];
            $patientInfoTel = $this->LocalService()->patient->fetchOne($telWhere);
            if(!empty($patientInfoTel)){
                $data['msg'] = '手机已存在';
                return $data;
            }

        }


        //排序
        $wherePatientOrderMax = [
            'is_del' => 0,
            'item_id' => $where['item_id'],
            'itemsig_id' => $where['itemsig_id'],
        ];
        $maxOrder = $this->LocalService()->patient->getMaxOrder('patient_order',$wherePatientOrderMax);
        empty($maxOrder) && $maxOrder = 10;
        $numberArr = [];
        $nameString = '';
        $repeatNameArr = [];
        foreach ($collectPatientDatas as $collectPatientDataK=>$collectPatientDataV){
            $patient_content = [];
            $newData[$collectPatientDataK]['patient_order'] = $maxOrder;
            $newData[$collectPatientDataK]['collect_patient_id'] = $collectPatientDataV['id'];
            $newData[$collectPatientDataK]['patient_name'] = '';
            $newData[$collectPatientDataK]['patient_number'] = '';
            if (isset($collectPatientDataV[$this->collectNumber]) && !empty($collectPatientDataV[$this->collectNumber])){
                $numberArr[] = trim($collectPatientDataV[$this->collectNumber]);
            }
            if (isset($collectPatientDataV[$this->collectName]) && !empty($collectPatientDataV[$this->collectName]) && empty($collectPatientDataV[$this->collectNumber])){
                if (!isset($repeatNameArr[trim($collectPatientDataV[$this->collectName])])){
                    $repeatNameArr[trim($collectPatientDataV[$this->collectName])] = trim($collectPatientDataV[$this->collectName]);
                    $nameString .= "'".trim($collectPatientDataV[$this->collectName])."',";
                }else{
                    $data['msg'] .= '受试者姓名不能重复('.$collectPatientDataV[$this->collectName].')<br>';
                }
            }
            foreach ($patientattrData as $contentKey=>$contentValue) {
                $patient_content[$contentKey] = ['id'=>$contentValue['id'],'field'=>$contentValue['attr_field'],'value'=>''];

                //判断名称及同步
                if ($contentValue['attr_field'] == $this->name){
                    $patient_content[$contentKey]['value'] = isset($collectPatientDataV[$this->collectName])?$collectPatientDataV[$this->collectName]:'';
                    $newData[$collectPatientDataK]['patient_name'] = isset($collectPatientDataV[$this->collectName])?$collectPatientDataV[$this->collectName]:'';
                    continue;

                }
                //判断姓别及同步
                if ($contentValue['attr_field'] == $this->sex){
                    $patient_content[$contentKey]['value'] = '';
                    $newData[$collectPatientDataK]['patient_sex'] = '';
                    if (isset($collectPatientDataV[$this->collectSex]) && !empty($collectPatientDataV[$this->collectSex])){
                        $patient_content[$contentKey]['value'] = ($collectPatientDataV[$this->collectSex] == 1)?'0':'1';
                        $newData[$collectPatientDataK]['patient_sex'] = ($collectPatientDataV[$this->collectSex] == 1)?'0':'1';

                    }
                    continue;
                }
                //判断缩写及同步
                if ($contentValue['attr_field'] == $this->ns){
                    $patient_content[$contentKey]['value'] = isset($collectPatientDataV[$this->collectNs])?$collectPatientDataV[$this->collectNs]:'';
                    $newData[$collectPatientDataK]['patient_name_easy'] = isset($collectPatientDataV[$this->collectNs])?$collectPatientDataV[$this->collectNs]:'';
                    continue;

                }
                //判断手机号
                if ($contentValue['attr_field'] == $this->tel){
                    $patient_content[$contentKey]['value'] = isset($collectPatientDataV[$this->collectTel])?$collectPatientDataV[$this->collectTel]:'';
                    $newData[$collectPatientDataK]['patient_tel'] = isset($collectPatientDataV[$this->collectTel])?$collectPatientDataV[$this->collectTel]:'';
                    continue;

                }
                //判断筛选号
                if ($contentValue['attr_field'] == $this->number){
                    $patient_content[$contentKey]['value'] = isset($collectPatientDataV[$this->collectNumber])?$collectPatientDataV[$this->collectNumber]:'';
                    $newData[$collectPatientDataK]['patient_number'] = isset($collectPatientDataV[$this->collectNumber])?$collectPatientDataV[$this->collectNumber]:'';
                    continue;
                }
                //判断身份证号
                if ($contentValue['attr_field'] == $this->pid){
                    $patient_content[$contentKey]['value'] = isset($collectPatientDataV[$this->collectPid])?$collectPatientDataV[$this->collectPid]:'';
                    continue;
                }

                //判断年龄
                if ($contentValue['attr_field'] == $this->age){
                    $patient_content[$contentKey]['value'] = isset($collectPatientDataV[$this->collectAge])?$collectPatientDataV[$this->collectAge]:'';
                }
            }
            if (empty($newData[$collectPatientDataK]['patient_name']) &&  empty($newData[$collectPatientDataK]['patient_number'])){
                $data['msg'] .= '受试者姓名或筛选号不能都为空('.$newData[$collectPatientDataK]['collect_patient_id'].')<br>';
            }
            $newData[$collectPatientDataK]['patient_content'] = $patient_content;
            $maxOrder += 10;

        }

        $data['newData'] = $newData;
        $data['numberArr'] = $numberArr;
        $data['nameString'] = $nameString;
        $data['repeatNameArr'] = $repeatNameArr;
        return $data;

    }


    /**
     * Notes:获取入组受试者
     * User: lltyy
     * DateTime: 2024/5/13 10:48
     *
     * @param int $item_id
     * @param string $itemsig_id
     * @param string|string $patient_id
     * @param $patient_status
     * @param $return_type //返回类型【0 明细 1 id】
     * @return array[]
     */
    public function getItemGroupPatient(int $item_id, $itemsig_id = '', string $patient_id = '', $patient_status,$return_type=0)
    {
        $whereArr['where'] = [
            'is_del' => 0,
            'item_id' => $item_id,
            new Operator('joining_date', Operator::OP_GT, 0),
        ];
        if ($itemsig_id != '') $whereArr['where']['itemsig_id'] = explode(',', $itemsig_id);
        if ($patient_id != '' && $patient_id != 0) $whereArr['where']['id'] = explode(',', $patient_id);
        if ($patient_status != 10 || strlen($patient_status) > 2) {
            $whereArr['where']['patient_status'] = explode(',', $patient_status);
        }

        $whereArr['columns'] = ['id', 'itemsig_id', 'patient_name','joining_date', 'patient_number', 'random_number', 'randgroup_id', 'random_id', 'order' => 'patient_order', 'patient_content', 'patient_status'];
        if($return_type == 1){
            $whereArr['columns'] = ['id', 'itemsig_id','joining_date', 'patient_name', 'patient_number'];
        }
        $whereArr['order'] = ['patient_order','id'];
        $patientDatas = $this->LocalService()->patient->fetchAll($whereArr);
        $datas = [
            'sig'=>[],
            'month'=>[],
            'year'=>[],
            'quarter'=>[]
        ];
        if(!empty($patientDatas)){
            foreach ($patientDatas as $patientKey => $patientData) {
                $patientData_sig = $patientData['itemsig_id'];
                $patientData_id = $patientData['id'];
                $datas['sig'][$patientData_sig][$patientData_id] = $patientData;

                $patientData_date = date('Y-m',$patientData['joining_date']);
                $patientData_date_arr = explode('-',$patientData_date);
                $patientData_year = $patientData_date_arr[0];
                $patientData_month = intval($patientData_date_arr[1]);
                $patientData_q = $patientData_year.'-Q0';
                if(in_array($patientData_month,[1,2,3])){
                    $patientData_q = $patientData_year.'-Q1';
                }
                if(in_array($patientData_month,[4,5,6])){
                    $patientData_q = $patientData_year.'-Q2';
                }
                if(in_array($patientData_month,[7,8,9])){
                    $patientData_q = $patientData_year.'-Q3';
                }
                if(in_array($patientData_month,[10,11,12])){
                    $patientData_q = $patientData_year.'-Q4';
                }
                $datas['month'][$patientData_date][] = $patientData;
                $datas['year'][$patientData_year][] = $patientData;
                $datas['quarter'][$patientData_q][] = $patientData;
            }
        }
        return $datas;
    }

    /**
     * Notes : 按条件获取受试者
     * @param $item_id
     * @param $itemsig_id
     * @param $patient_id
     * @param $patient_status
     * @param $limit
     * @param $offset
     * @param $random_id
     * @return array
     * Author:唐伯虎不虎
     * Date:2024/6/19 11:28
     */
    public function getItempatinet( $item_id, $itemsig_id , $patient_id, $patient_status,$limit,$offset,$random_id)
    {
        $whereArr['where'] = (new Where())->equalTo('item_id', $item_id)
                                ->equalTo('is_del', 0)
                                ->greaterThan('joining_type', 0);

        if(empty($random_id) && empty($patient_id)){
            $whereArr['where']->nest()
                              ->isNull('random_id')
                              ->or
                              ->equalTo('random_id', 0)
                              ->unnest();
        }elseif(!empty($random_id) ){
            $whereArr['where']->equalTo('random_id', $random_id);
        }
        if ($itemsig_id != '') $whereArr['where']->in('itemsig_id', explode(',', $itemsig_id));
        if ($patient_id != '' && $patient_id != 0) $whereArr['where']->in('id', explode(',', $patient_id));
        if ($patient_status != 10 || strlen($patient_status) > 2) {
            $whereArr['where']->in('patient_status', explode(',', $patient_status));
        }

        $whereArr['columns'] = ['id', 'itemsig_id', 'patient_name', 'patient_number', 'random_number', 'randgroup_id', 'random_id', 'order' => 'patient_order', 'patient_status'];
        $whereArr['order'] = ['itemsig_id','patient_order','id'];

        if(!empty($limit)){
            $whereArr['limit'] = $limit;
            $whereArr['offset'] = $offset;
        }

        $data = $this->LocalService()->patient->fetchAll($whereArr);
        $patientDatas = [];
        //检查项
        foreach ($data as $k => $v) {
            $patientDatas[$v['id']] = $v;
        }
        return $patientDatas;
    }

    public function _getPatientName($patient_id)
    {
        $patientInfo = $this->fetchOne([
            'where'=> [
                'is_del' => 0,
                'id' => $patient_id,
            ],
            'columns'=>['id','patient_name','patient_number','patient_name_easy']
        ]);
        if(empty($patientInfo)) return '';

        $patientName = '';

        if(!empty($patientInfo['patient_name'])) $patientName .= $patientInfo['patient_name'];

        if(empty($patientName)) $patientName .= $patientInfo['patient_name_easy'];

        if(!empty($patientInfo['patient_number'])) $patientName .= '【'.$patientInfo['patient_number'].'】';

        return $patientName;
    }

    /**
     * Notes: 是否关注的公众号的患者信息数量统计
     * @param
     * @return
     * @author haojinhua
     * @date 2024-08-13
     */
    public function getfocusedPatient(){
        $res = [];

        //未关注人员的patient_openid数组
        $nofocusedopenidData = $this->LocalService()->toolSys->wechatUserStatusList([
            'user_type' => 'patient',
            'user_status' => 'unsubscribe'
        ]);
        $nofocusedPatientDatas = !empty($nofocusedopenidData['unsubscribe']) ? $nofocusedopenidData['unsubscribe'] : [];


        //获取人员ID
        $user_cound = [
            'where' => 'is_del = 0',
            'columns' => ['id','mobile','patient_openid'],
            'order'  =>['id']
        ];

        $user_infos = $this->LocalService()->adminUser->fetchAll($user_cound);

        //$nofocused_user 未关注的人员ID
        $userIdData = $nofocused_user = [];
        if (!empty($user_infos)) {
            foreach ($user_infos as $user_info) {
                $user_id        = $user_info['id'];
                $patient_openid = $user_info['patient_openid'];
                $userIdData[$user_info['mobile']] = $user_id;
                if ($patient_openid == '' || in_array($patient_openid, $nofocusedPatientDatas)) {
                    $nofocused_user[] = $user_info['id'];
                }
            }
        }


        $where = 'is_del = 0 ';
        $where_cound = [
            'where' => $where,
            'columns' => ['id','item_id','itemsig_id','patient_tel','is_send_msg'],
            'order'  =>['patient_order','id']
        ];

        $patient_infos = $this->fetchAll($where_cound);
        if(!empty($patient_infos)){
             foreach ($patient_infos as $patient_info){
                 $res[$patient_info['item_id']][$patient_info['itemsig_id']]['allfocus'] = !empty( $res[$patient_info['item_id']][$patient_info['itemsig_id']]['allfocus']) ?  $res[$patient_info['item_id']][$patient_info['itemsig_id']]['allfocus'] : 0;
                 $res[$patient_info['item_id']][$patient_info['itemsig_id']]['focus'] = !empty( $res[$patient_info['item_id']][$patient_info['itemsig_id']]['focus']) ?  $res[$patient_info['item_id']][$patient_info['itemsig_id']]['focus'] : 0;
                 $res[$patient_info['item_id']][$patient_info['itemsig_id']]['nofocus'] = !empty( $res[$patient_info['item_id']][$patient_info['itemsig_id']]['nofocus']) ?  $res[$patient_info['item_id']][$patient_info['itemsig_id']]['nofocus'] : 0;
                 $res[$patient_info['item_id']][$patient_info['itemsig_id']]['allfocus'] ++;
                 $user_id = isset($userIdData[$patient_info['patient_tel']]) && !empty($userIdData[$patient_info['patient_tel']]) ? $userIdData[$patient_info['patient_tel']] : 0;
                if(empty($user_id) || in_array($user_id,$nofocused_user)){ //统计未关注数量
                    $res[$patient_info['item_id']][$patient_info['itemsig_id']]['nofocus'] ++;
                }else{
                    //关注公众号的
                    $res[$patient_info['item_id']][$patient_info['itemsig_id']]['patient_id'][] = $patient_info['id'];
                    $res[$patient_info['item_id']][$patient_info['itemsig_id']]['focus'] ++;
                }
             }
        }

        unset($nofocusedPatientDatas);
        unset($user_infos);
        unset($patient_infos);

        return $res;

    }

    /**
     * Notes: 获取每个项目及中心的患者数
     * User: lltyy
     * DateTime: 2024/12/4 8:15
     *
     */
    public function getItemSigPatientCount(array $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'] : [];
        $now_date = isset($info['now_date']) && !empty($info['now_date']) ? $info['now_date'] : date('Y-m-d');
        $return_type = isset($info['return_type']) && !empty($info['return_type']) ? $info['return_type'] : 0;//返回数据类型 0 日进度信息 1 周进度信息 2 月进度信息 3 日\周\月进度信息

        //昨日 开始、结束日期
        $pre_date = date('Y-m-d',strtotime($now_date . ' -1 day'));
        $pre_date_start = strtotime($pre_date.' 00:00:00');
        $pre_date_end = strtotime($now_date.' 00:00:00');

        //本周开始[周一]、结束[当天]日期
        $now_week_monday_date = date('Y-m-d', strtotime('Monday this week', strtotime($now_date)));
        $now_week_start_date = strtotime($now_week_monday_date.' 00:00:00');// 获取周一的日期
        $now_week_end_date = strtotime(date('Y-m-d', strtotime($now_date . ' +1 day')).' 00:00:00');

        //上周的开始[周一]、结束[周日]日期
        $pre_week_start_date = strtotime(date('Y-m-d', strtotime('-1 week', strtotime($now_week_monday_date))).' 00:00:00');// 获取周一的日期
        $pre_week_end_date = $now_week_start_date;
        unset($now_week_monday_date);

        //本月开始、结束日期
        $now_month_first_date = date('Y-m-d', strtotime('first day of', strtotime($now_date)));
        $now_month_start_date = strtotime($now_month_first_date.' 00:00:00');// 获取1号的日期
        $now_month_end_date = strtotime(date('Y-m-d', strtotime($now_date . ' +1 day')).' 00:00:00');

        //上月开始、结束日期
        $pre_month_start_date = strtotime(date('Y-m-d', strtotime('-1 month', strtotime($now_month_first_date))).' 00:00:00');// 获取上月1号的日期
        $pre_month_end_date = $now_month_start_date;
        unset($now_month_first_date);
        //日进度信息
        $dayArr = [
            'item'=>[],//项目患者数
            'sig'=>[],//项目中心患者数
            'sig_ranking'=>[],//项目中心患者排名
            'othersig_ranking'=>[],//无数据项目中心排名
        ];
        //周进度信息
        $weekArr = [
            'item'=>[],//项目患者数
            'sig'=>[],//项目中心患者数
            'sig_ranking'=>[],//项目中心患者排名
            'othersig_ranking'=>[],//无数据项目中心排名
        ];
        //月进度信息
        $monthArr = [
            'item'=>[],//项目患者数
            'sig'=>[],//项目中心患者数
            'sig_ranking'=>[],//项目中心患者排名
            'othersig_ranking'=>[],//无数据项目中心排名
        ];
        //获取患者信息
        $where = [
            'is_del' => 0,
        ];
        if(!empty($item_id)){
            $where['item_id'] = $item_id;
        }
        if(!empty($itemsig_id)){
            $where['itemsig_id'] = $itemsig_id;
        }
        $datas = $this->fetchAll([
            'where'=>$where,
            'columns'=>['item_id','itemsig_id','create_time']
        ]);
        unset($where);
        if(!empty($datas)){
            foreach($datas as $dataKey=>$data){
                $data_item = $data['item_id'];
                $data_itemsig = $data['itemsig_id'];
                $data_create = $data['create_time'];

                //日进度
                $day_is_add = $day_is_pre = 0;
                if($data_create < $pre_date_end){
                    if($data_create >= $pre_date_start){
                        $day_is_pre = 1;
                    }
                    $day_is_add = 1;
                }
                if($day_is_add == 1){
                    $dayArr['item'][$data_item] = [
                        'all'=>isset($dayArr['item'][$data_item]) && !empty($dayArr['item'][$data_item]['all']) ? $dayArr['item'][$data_item]['all'] : 0,
                        'preAdd'=>isset($dayArr['item'][$data_item]) && !empty($dayArr['item'][$data_item]['preAdd']) ? $dayArr['item'][$data_item]['preAdd'] : 0
                    ];
                    $dayArr['sig'][$data_item][$data_itemsig] = [
                        'all'=>isset($dayArr['sig'][$data_item]) && isset($dayArr['sig'][$data_item][$data_itemsig]) && !empty($dayArr['sig'][$data_item][$data_itemsig]['all']) ? $dayArr['sig'][$data_item][$data_itemsig]['all'] : 0,
                        'preAdd'=>isset($dayArr['sig'][$data_item]) && isset($dayArr['sig'][$data_item][$data_itemsig]) && !empty($dayArr['sig'][$data_item][$data_itemsig]['preAdd']) ? $dayArr['sig'][$data_item][$data_itemsig]['preAdd'] : 0
                    ];

                    //累计增加数
                    $dayArr['item'][$data_item]['all'] += 1;
                    $dayArr['sig'][$data_item][$data_itemsig]['all'] += 1;
                    //昨日新增数
                    if($day_is_pre == 1){
                        $dayArr['item'][$data_item]['preAdd'] += 1;
                        $dayArr['sig'][$data_item][$data_itemsig]['preAdd'] += 1;
                    }
                }
                unset($day_is_add);
                unset($day_is_pre);

                //周进度
                $week_is_add = $week_is_pre = $week_is_preall = $week_is_now = 0;
                if($data_create < $now_week_end_date){
                    if($data_create < $pre_week_end_date){
                        if($data_create >= $pre_week_start_date){
                            $week_is_pre = 1;
                        }
                        $week_is_preall = 1;
                    }else{
                        $week_is_now = 1;
                    }
                    $week_is_add = 1;
                }
                if($week_is_add == 1){
                    $weekArr['item'][$data_item] = [
                        'all'=>isset($weekArr['item'][$data_item]) && !empty($weekArr['item'][$data_item]['all']) ? $weekArr['item'][$data_item]['all'] : 0,
                        'nowAdd'=>isset($weekArr['item'][$data_item]) && !empty($weekArr['item'][$data_item]['nowAdd']) ? $weekArr['item'][$data_item]['nowAdd'] : 0,
                        'preAllAdd'=>isset($weekArr['item'][$data_item]) && !empty($weekArr['item'][$data_item]['preAllAdd']) ? $weekArr['item'][$data_item]['preAllAdd'] : 0,
                        'preAdd'=>isset($weekArr['item'][$data_item]) && !empty($weekArr['item'][$data_item]['preAdd']) ? $weekArr['item'][$data_item]['preAdd'] : 0
                    ];
                    $weekArr['sig'][$data_item][$data_itemsig] = [
                        'all'=>isset($weekArr['sig'][$data_item]) && isset($weekArr['sig'][$data_item][$data_itemsig]) && !empty($weekArr['sig'][$data_item][$data_itemsig]['all']) ? $weekArr['sig'][$data_item][$data_itemsig]['all'] : 0,
                        'nowAdd'=>isset($weekArr['sig'][$data_item]) && isset($weekArr['sig'][$data_item][$data_itemsig]) && !empty($weekArr['sig'][$data_item][$data_itemsig]['nowAdd']) ? $weekArr['sig'][$data_item][$data_itemsig]['nowAdd'] : 0,
                        'preAllAdd'=>isset($weekArr['sig'][$data_item]) && isset($weekArr['sig'][$data_item][$data_itemsig]) && !empty($weekArr['sig'][$data_item][$data_itemsig]['preAllAdd']) ? $weekArr['sig'][$data_item][$data_itemsig]['preAllAdd'] : 0,
                        'preAdd'=>isset($weekArr['sig'][$data_item]) && isset($weekArr['sig'][$data_item][$data_itemsig]) && !empty($weekArr['sig'][$data_item][$data_itemsig]['preAdd']) ? $weekArr['sig'][$data_item][$data_itemsig]['preAdd'] : 0
                    ];

                    //累计增加数
                    $weekArr['item'][$data_item]['all'] += 1;
                    $weekArr['sig'][$data_item][$data_itemsig]['all'] += 1;

                    //截止上周累计
                    if($week_is_preall == 1){
                        $weekArr['item'][$data_item]['preAllAdd'] += 1;
                        $weekArr['sig'][$data_item][$data_itemsig]['preAllAdd'] += 1;
                        //上周新增数
                        if($week_is_pre == 1){
                            $weekArr['item'][$data_item]['preAdd'] += 1;
                            $weekArr['sig'][$data_item][$data_itemsig]['preAdd'] += 1;
                        }
                    }

                    //本周新增数
                    if($week_is_now == 1){
                        $weekArr['item'][$data_item]['nowAdd'] += 1;
                        $weekArr['sig'][$data_item][$data_itemsig]['nowAdd'] += 1;
                    }
                }
                unset($week_is_add);
                unset($week_is_pre);
                unset($week_is_preall);
                unset($week_is_now);

                //月进度
                $month_is_add = $month_is_pre = $month_is_preall = $month_is_now = 0;
                if($data_create < $now_month_end_date){
                    if($data_create < $pre_month_end_date){
                        if($data_create >= $pre_month_start_date){
                            $month_is_pre = 1;
                        }
                        $month_is_preall = 1;
                    }else{
                        $month_is_now = 1;
                    }
                    $month_is_add = 1;
                }
                if($month_is_add == 1){
                    $monthArr['item'][$data_item] = [
                        'all'=>isset($monthArr['item'][$data_item]) && !empty($monthArr['item'][$data_item]['all']) ? $monthArr['item'][$data_item]['all'] : 0,
                        'nowAdd'=>isset($monthArr['item'][$data_item]) && !empty($monthArr['item'][$data_item]['nowAdd']) ? $monthArr['item'][$data_item]['nowAdd'] : 0,
                        'preAllAdd'=>isset($monthArr['item'][$data_item]) && !empty($monthArr['item'][$data_item]['preAllAdd']) ? $monthArr['item'][$data_item]['preAllAdd'] : 0,
                        'preAdd'=>isset($monthArr['item'][$data_item]) && !empty($monthArr['item'][$data_item]['preAdd']) ? $monthArr['item'][$data_item]['preAdd'] : 0
                    ];
                    $monthArr['sig'][$data_item][$data_itemsig] = [
                        'all'=>isset($monthArr['sig'][$data_item]) && isset($monthArr['sig'][$data_item][$data_itemsig]) && !empty($monthArr['sig'][$data_item][$data_itemsig]['all']) ? $monthArr['sig'][$data_item][$data_itemsig]['all'] : 0,
                        'nowAdd'=>isset($monthArr['sig'][$data_item]) && isset($monthArr['sig'][$data_item][$data_itemsig]) && !empty($monthArr['sig'][$data_item][$data_itemsig]['nowAdd']) ? $monthArr['sig'][$data_item][$data_itemsig]['nowAdd'] : 0,
                        'preAllAdd'=>isset($monthArr['sig'][$data_item]) && isset($monthArr['sig'][$data_item][$data_itemsig]) && !empty($monthArr['sig'][$data_item][$data_itemsig]['preAllAdd']) ? $monthArr['sig'][$data_item][$data_itemsig]['preAllAdd'] : 0,
                        'preAdd'=>isset($monthArr['sig'][$data_item]) && isset($monthArr['sig'][$data_item][$data_itemsig]) && !empty($monthArr['sig'][$data_item][$data_itemsig]['preAdd']) ? $monthArr['sig'][$data_item][$data_itemsig]['preAdd'] : 0
                    ];

                    //累计增加数
                    $monthArr['item'][$data_item]['all'] += 1;
                    $monthArr['sig'][$data_item][$data_itemsig]['all'] += 1;

                    //截止上月累计
                    if($month_is_preall == 1){
                        $monthArr['item'][$data_item]['preAllAdd'] += 1;
                        $monthArr['sig'][$data_item][$data_itemsig]['preAllAdd'] += 1;
                        //上周新增数
                        if($month_is_pre == 1){
                            $monthArr['item'][$data_item]['preAdd'] += 1;
                            $monthArr['sig'][$data_item][$data_itemsig]['preAdd'] += 1;
                        }
                    }

                    //本月新增数
                    if($month_is_now == 1){
                        $monthArr['item'][$data_item]['nowAdd'] += 1;
                        $monthArr['sig'][$data_item][$data_itemsig]['nowAdd'] += 1;
                    }
                }
                unset($month_is_add);
                unset($month_is_pre);
                unset($month_is_preall);
                unset($month_is_now);

                unset($data_item);
                unset($data_itemsig);
                unset($data_create);
                unset($datas[$dataKey]);
            }
        }
        unset($datas);
        unset($pre_date);
        unset($pre_date_start);
        unset($pre_date_end);
        unset($now_week_start_date);
        unset($now_week_end_date);
        unset($pre_week_start_date);
        unset($pre_week_end_date);
        unset($now_month_start_date);
        unset($now_month_end_date);
        unset($pre_month_start_date);
        unset($pre_month_end_date);

        //日进度排名
        if(!empty($dayArr['sig'])){
            $itemSigCountArr = $itemSigPreCountArr = [];
            foreach($dayArr['sig'] as $arr_itemid=>$arr_item_sigs){
                foreach($arr_item_sigs as $arr_item_sigid=>$arr_item_sig){
                    $itemSigCountArr[$arr_itemid][$arr_item_sig['all']][] = $arr_item_sigid;
                    $itemSigPreCountArr[$arr_itemid][$arr_item_sig['preAllAdd']][] = $arr_item_sigid;
                }
            }
            //累计排名
            foreach($itemSigCountArr as $itemSigItemId=>$itemSigCounts){
                krsort($itemSigCounts);
                $itemSigRanking = 1;
                foreach($itemSigCounts as $itemSigCount=>$itemSigCountSigs){
                    foreach($itemSigCountSigs as $itemSigCountSig){
                        $dayArr['sig_ranking'][$itemSigItemId][$itemSigCountSig]['now'] = $itemSigRanking;
                    }
                    $itemSigRanking++;
                    unset($itemSigCounts[$itemSigCount]);
                    unset($itemSigCountArr[$itemSigItemId][$itemSigCount]);
                }
                unset($itemSigCountArr[$itemSigItemId]);
                $dayArr['othersig_ranking'][$itemSigItemId]['now'] = $itemSigRanking;
                unset($itemSigRanking);
            }
            unset($itemSigCountArr);

            //上周、月排名
            foreach($itemSigPreCountArr as $itemSigPreItem=>$itemSigPreCounts){
                krsort($itemSigPreCounts);
                $itemSigPreRanking = 1;
                foreach($itemSigPreCounts as $itemSigPreCount=>$itemSigPreCountSigs){
                    foreach($itemSigPreCountSigs as $itemSigPreCountSig){
                        $dayArr['sig_ranking'][$itemSigPreItem][$itemSigPreCountSig]['pre'] = $itemSigPreRanking;
                    }
                    $itemSigPreRanking++;
                    unset($itemSigPreCounts[$itemSigPreCount]);
                    unset($itemSigPreCountArr[$itemSigPreItem][$itemSigPreCount]);
                }
                unset($itemSigPreCountArr[$itemSigPreItem]);
                $dayArr['othersig_ranking'][$itemSigPreItem]['pre'] = $itemSigPreRanking;
                unset($itemSigPreRanking);
            }
            unset($itemSigPreCountArr);
        }

        //周进度排名
        if(!empty($weekArr['sig'])){
            $itemSigCountArr = $itemSigPreCountArr = [];
            foreach($weekArr['sig'] as $arr_itemid=>$arr_item_sigs){
                foreach($arr_item_sigs as $arr_item_sigid=>$arr_item_sig){
                    $itemSigCountArr[$arr_itemid][$arr_item_sig['all']][] = $arr_item_sigid;
                    $itemSigPreCountArr[$arr_itemid][$arr_item_sig['preAllAdd']][] = $arr_item_sigid;
                }
            }
            //累计排名
            foreach($itemSigCountArr as $itemSigItemId=>$itemSigCounts){
                krsort($itemSigCounts);
                $itemSigRanking = 1;
                foreach($itemSigCounts as $itemSigCount=>$itemSigCountSigs){
                    foreach($itemSigCountSigs as $itemSigCountSig){
                        $weekArr['sig_ranking'][$itemSigItemId][$itemSigCountSig]['now'] = $itemSigRanking;
                    }
                    $itemSigRanking++;
                    unset($itemSigCounts[$itemSigCount]);
                    unset($itemSigCountArr[$itemSigItemId][$itemSigCount]);
                }
                unset($itemSigCountArr[$itemSigItemId]);
                $weekArr['othersig_ranking'][$itemSigItemId]['now'] = $itemSigRanking;
                unset($itemSigRanking);
            }
            unset($itemSigCountArr);

            //上周排名
            foreach($itemSigPreCountArr as $itemSigPreItem=>$itemSigPreCounts){
                krsort($itemSigPreCounts);
                $itemSigPreRanking = 1;
                foreach($itemSigPreCounts as $itemSigPreCount=>$itemSigPreCountSigs){
                    foreach($itemSigPreCountSigs as $itemSigPreCountSig){
                        $weekArr['sig_ranking'][$itemSigPreItem][$itemSigPreCountSig]['pre'] = $itemSigPreRanking;
                    }
                    $itemSigPreRanking++;
                    unset($itemSigPreCounts[$itemSigPreCount]);
                    unset($itemSigPreCountArr[$itemSigPreItem][$itemSigPreCount]);
                }
                unset($itemSigPreCountArr[$itemSigPreItem]);
                $weekArr['othersig_ranking'][$itemSigPreItem]['pre'] = $itemSigPreRanking;
                unset($itemSigPreRanking);
            }
            unset($itemSigPreCountArr);
        }

        //月进度排名
        if(!empty($monthArr['sig'])){
            $itemSigCountArr = $itemSigPreCountArr = [];
            foreach($monthArr['sig'] as $arr_itemid=>$arr_item_sigs){
                foreach($arr_item_sigs as $arr_item_sigid=>$arr_item_sig){
                    $itemSigCountArr[$arr_itemid][$arr_item_sig['all']][] = $arr_item_sigid;
                    $itemSigPreCountArr[$arr_itemid][$arr_item_sig['preAllAdd']][] = $arr_item_sigid;
                }
            }
            //累计排名
            foreach($itemSigCountArr as $itemSigItemId=>$itemSigCounts){
                krsort($itemSigCounts);
                $itemSigRanking = 1;
                foreach($itemSigCounts as $itemSigCount=>$itemSigCountSigs){
                    foreach($itemSigCountSigs as $itemSigCountSig){
                        $monthArr['sig_ranking'][$itemSigItemId][$itemSigCountSig]['now'] = $itemSigRanking;
                    }
                    $itemSigRanking++;
                    unset($itemSigCounts[$itemSigCount]);
                    unset($itemSigCountArr[$itemSigItemId][$itemSigCount]);
                }
                unset($itemSigCountArr[$itemSigItemId]);
                $monthArr['othersig_ranking'][$itemSigItemId]['now'] = $itemSigRanking;
                unset($itemSigRanking);
            }
            unset($itemSigCountArr);

            //上月排名
            foreach($itemSigPreCountArr as $itemSigPreItem=>$itemSigPreCounts){
                krsort($itemSigPreCounts);
                $itemSigPreRanking = 1;
                foreach($itemSigPreCounts as $itemSigPreCount=>$itemSigPreCountSigs){
                    foreach($itemSigPreCountSigs as $itemSigPreCountSig){
                        $monthArr['sig_ranking'][$itemSigPreItem][$itemSigPreCountSig]['pre'] = $itemSigPreRanking;
                    }
                    $itemSigPreRanking++;
                    unset($itemSigPreCounts[$itemSigPreCount]);
                    unset($itemSigPreCountArr[$itemSigPreItem][$itemSigPreCount]);
                }
                unset($itemSigPreCountArr[$itemSigPreItem]);
                $monthArr['othersig_ranking'][$itemSigPreItem]['pre'] = $itemSigPreRanking;
                unset($itemSigPreRanking);
            }
            unset($itemSigPreCountArr);
        }

        //返回信息
        $arr = [];
        if($return_type == 0){
            $arr = $dayArr;
        }
        if($return_type == 1){
            $arr = $weekArr;
        }
        if($return_type == 2){
            $arr = $monthArr;
        }
        if($return_type == 3){
            $arr = [
                'day'=>$dayArr,
                'week'=>$weekArr,
                'month'=>$monthArr
            ];
        }

        unset($dayArr);
        unset($weekArr);
        unset($monthArr);
        return $arr;
    }



    /**
     * Notes: 获取每个检查点的患者数
     * User: lltyy
     * DateTime: 2024/12/4 8:15
     *
     */
    public function getCheckPatientCount(array $info = []){
        $item_id = isset($info['item_id']) && !empty($info['item_id']) ? $info['item_id'] : [];
        $check_id = isset($info['check_id']) && !empty($info['check_id']) ? $info['check_id'] : 0;
        $itemsig_id = isset($info['itemsig_id']) && !empty($info['itemsig_id']) ? $info['itemsig_id'] : [];

        $now_date = date('Y-m-d');
        $return_type = isset($info['return_type']) && !empty($info['return_type']) ? $info['return_type'] : 0;//返回数据类型 0 日进度信息 1 周进度信息 2 月进度信息 3 日\周\月进度信息

        //昨日 开始、结束日期
        $pre_date = date('Y-m-d',strtotime($now_date . ' -1 day'));
        $pre_date_start = strtotime($pre_date.' 00:00:00');
        $pre_date_end = strtotime($now_date.' 00:00:00');

        //本周开始[周一]、结束[当天]日期
        $now_week_monday_date = date('Y-m-d', strtotime('Monday this week', strtotime($now_date)));
        $now_week_start_date = strtotime($now_week_monday_date.' 00:00:00');// 获取周一的日期
        $now_week_end_date = strtotime(date('Y-m-d', strtotime($now_date . ' +1 day')).' 00:00:00');

        //上周的开始[周一]、结束[周日]日期
        $pre_week_start_date = strtotime(date('Y-m-d', strtotime('-1 week', strtotime($now_week_monday_date))).' 00:00:00');// 获取周一的日期
        $pre_week_end_date = $now_week_start_date;
        unset($now_week_monday_date);

        //本月开始、结束日期
        $now_month_first_date = date('Y-m-d', strtotime('first day of', strtotime($now_date)));
        $now_month_start_date = strtotime($now_month_first_date.' 00:00:00');// 获取1号的日期
        $now_month_end_date = strtotime(date('Y-m-d', strtotime($now_date . ' +1 day')).' 00:00:00');

        //上月开始、结束日期
        $pre_month_start_date = strtotime(date('Y-m-d', strtotime('-1 month', strtotime($now_month_first_date))).' 00:00:00');// 获取上月1号的日期
        $pre_month_end_date = $now_month_start_date;
        unset($now_month_first_date);
        //日进度信息
        $dayArr = [
            'item'=>[],//项目患者数
            'sig'=>[],//项目中心患者数
            'check'=>[],//项目检查点患者数
            'sig_ranking'=>[],//项目中心患者排名
            'othersig_ranking'=>[],//无数据项目中心排名
        ];
        //周进度信息
        $weekArr = [
            'item'=>[],//项目患者数
            'sig'=>[],//项目中心患者数
            'sig_ranking'=>[],//项目中心患者排名
            'othersig_ranking'=>[],//无数据项目中心排名
        ];
        //月进度信息
        $monthArr = [
            'item'=>[],//项目患者数
            'sig'=>[],//项目中心患者数
            'sig_ranking'=>[],//项目中心患者排名
            'othersig_ranking'=>[],//无数据项目中心排名
        ];
        //获取患者信息
        $where = [
            'is_del' => 0,
        ];
        if(!empty($item_id)){
            $where['item_id'] = $item_id;
        }
        if(!empty($itemsig_id)){
            $where['itemsig_id'] = $itemsig_id;
        }
        $datas = $this->fetchAll([
            'where'=>$where,
            'columns'=>['id','item_id','itemsig_id']
        ]);
        unset($where);
        if(!empty($datas)){

            //获取患者检查点
            $patientCheckArr = $patientNowCheck = [];
            $patientCheckDatas = $this->LocalService()->itemPatientchecktime->fetchAll([
                'where'=> [
                    'is_del' => 0,
                    'patient_id' => array_values(array_column($datas,'id')),
                ],
                'columns'=>['id','patient_id','is_now_state'],
                'order'=>['patient_id','check_order','id']
            ]);
            if(!empty($patientCheckDatas)){
                foreach($patientCheckDatas as $patientCheckKey=>$patientCheckData){
                    $patient_now_check = isset($patientNowCheck[$patientCheckData['patient_id']]) && !empty($patientNowCheck[$patientCheckData['patient_id']]) ? $patientNowCheck[$patientCheckData['patient_id']] : 0;
                    if(empty($patient_now_check)){
                        $patientCheckArr[$patientCheckData['patient_id']][] = $patientCheckData['id'];
                        if($patientCheckData['is_now_state'] == 1){
                            $patientNowCheck[$patientCheckData['patient_id']] = $patientCheckData['id'];
                        }
                    }
                    unset($patientCheckDatas[$patientCheckKey]);
                    unset($patient_now_check);
                }
            }
            unset($patientNowCheck);
            unset($patientCheckDatas);

            //获取患者检查点提交表单的最早时间
            $checkFormDateArr = [];
            $check_form_where = [
                'is_del' => 0,
                'patient_id' => array_values(array_column($datas,'id')),
                new Operator('patientchecktime_id', Operator::OP_GT, 0),
            ];

            //去除独立访视的检查点
            $no_check_arr = $this->LocalService()->itemChecktime->fetchCol('id',[
                'is_del' => 0,
                'is_isolate' => 1,
                'item_id' => array_values(array_column($datas,'item_id')),
            ]);
            if(!empty($no_check_arr)){
                $check_form_where[] = new NotIn('checktime_id', array_values($no_check_arr));
            }
            unset($no_check_arr);

            //去除贯穿圈出、电话随访类表单
            $no_formgroup = $this->LocalService()->dictionaryFormGroup->fetchCol('id',[
                'is_del' => 0,
                'code' => ["WP","Telephone_Follow_Up"],
            ]);
            $no_form_where = [
                'is_del' => 0,
                'item_id' => array_values(array_column($datas,'item_id')),
            ];
            if(!empty($no_formgroup)){
                $no_form_where ['group_id'] = array_values($no_formgroup);
            }else{
                $no_form_where = 'id < 0';
            }
            unset($no_formgroup);
            $no_form_arr = $this->LocalService()->itemForm->fetchCol('id',$no_form_where);
            unset($no_form_where);
            if(!empty($no_form_arr)){
                $check_form_where[] = new NotIn('form_id', array_values($no_form_arr) );
            }
            unset($no_form_arr);

            if(!empty($check_id)){
                $check_form_where['checktime_id'] = $check_id;;
            }
            if(isset($info['check_ids'])){
                if(!empty($info['check_ids'])){
                    $check_form_where['checktime_id'] = $info['check_ids'];
                }else{
                    $check_form_where = 'id < 0';
                }
            }
            $checkFormDatas = $this->LocalService()->patientForm->fetchAll([
                'where'=>$check_form_where,
                'columns'=>['patient_id','checktime_id','create_time','patientchecktime_id'],
                'order'=>['create_time desc','id']
            ]);
            unset($check_form_where);

            if(!empty($checkFormDatas)){
                foreach($checkFormDatas as $checkFormKey=>$checkFormData){
                    $patientChecks = isset($patientCheckArr[$checkFormData['patient_id']]) && !empty($patientCheckArr[$checkFormData['patient_id']]) ? $patientCheckArr[$checkFormData['patient_id']] : [];
                    if(in_array($checkFormData['patientchecktime_id'],$patientChecks)){
                        $checkFormDateArr[$checkFormData['patient_id']][$checkFormData['checktime_id']] = $checkFormData['create_time'];
                    }
                    unset($patientChecks);
                    unset($checkFormDatas[$checkFormKey]);
                }
            }
            unset($checkFormDates);
            unset($patientCheckArr);
            foreach($datas as $dataKey=>$data){
                $data_item = $data['item_id'];
                $data_itemsig = $data['itemsig_id'];
                $day_is_add = $day_is_pre = 0;//日进度
                $week_is_add = $week_is_pre = $week_is_preall = $week_is_now = 0;//周进度
                $month_is_add = $month_is_pre = $month_is_preall = $month_is_now = 0;//月进度
                if(isset($checkFormDateArr[$data['id']])){
                    foreach($checkFormDateArr[$data['id']] as $checkFormCheck=>$checkFormDate){
                        //日进度
                        if($checkFormDate < $pre_date_end){
                            $dayArr['check'][$checkFormCheck] = [
                                'all'=>isset($dayArr['check'][$checkFormCheck]) && !empty($dayArr['check'][$checkFormCheck]['all']) ? $dayArr['check'][$checkFormCheck]['all'] : 0,
                                'preAdd'=>isset($dayArr['check'][$checkFormCheck]) && !empty($dayArr['check'][$checkFormCheck]['preAdd']) ? $dayArr['check'][$checkFormCheck]['preAdd'] : 0
                            ];
                            $dayArr['check'][$checkFormCheck]['all'] += 1;
                            if($checkFormDate >= $pre_date_start){
                                $day_is_pre = 1;
                                $dayArr['check'][$checkFormCheck]['preAdd'] += 1;
                            }
                            $day_is_add = 1;
                        }
                        //周进度
                        if($checkFormDate < $now_week_end_date){
                            if($checkFormDate < $pre_week_end_date){
                                if($checkFormDate >= $pre_week_start_date){
                                    $week_is_pre = 1;
                                }
                                $week_is_preall = 1;
                            }else{
                                $week_is_now = 1;
                            }
                            $week_is_add = 1;
                        }
                        //月进度
                        if($checkFormDate < $now_month_end_date){
                            if($checkFormDate < $pre_month_end_date){
                                if($checkFormDate >= $pre_month_start_date){
                                    $month_is_pre = 1;
                                }
                                $month_is_preall = 1;
                            }else{
                                $month_is_now = 1;
                            }
                            $month_is_add = 1;
                        }
                        unset($checkFormDateArr[$data['id']][$checkFormCheck]);
                    }
                    unset($checkFormDateArr[$data['id']]);
                }
                //日进度
                if($day_is_add == 1){
                    $dayArr['item'][$data_item] = [
                        'all'=>isset($dayArr['item'][$data_item]) && !empty($dayArr['item'][$data_item]['all']) ? $dayArr['item'][$data_item]['all'] : 0,
                        'preAdd'=>isset($dayArr['item'][$data_item]) && !empty($dayArr['item'][$data_item]['preAdd']) ? $dayArr['item'][$data_item]['preAdd'] : 0
                    ];
                    $dayArr['sig'][$data_item][$data_itemsig] = [
                        'all'=>isset($dayArr['sig'][$data_item]) && isset($dayArr['sig'][$data_item][$data_itemsig]) && !empty($dayArr['sig'][$data_item][$data_itemsig]['all']) ? $dayArr['sig'][$data_item][$data_itemsig]['all'] : 0,
                        'preAdd'=>isset($dayArr['sig'][$data_item]) && isset($dayArr['sig'][$data_item][$data_itemsig]) && !empty($dayArr['sig'][$data_item][$data_itemsig]['preAdd']) ? $dayArr['sig'][$data_item][$data_itemsig]['preAdd'] : 0
                    ];

                    //累计增加数
                    $dayArr['item'][$data_item]['all'] += 1;
                    $dayArr['sig'][$data_item][$data_itemsig]['all'] += 1;
                    //昨日新增数
                    if($day_is_pre == 1){
                        $dayArr['item'][$data_item]['preAdd'] += 1;
                        $dayArr['sig'][$data_item][$data_itemsig]['preAdd'] += 1;
                    }
                }
                unset($day_is_add);
                unset($day_is_pre);

                //周进度
                if($week_is_add == 1){
                    $weekArr['item'][$data_item] = [
                        'all'=>isset($weekArr['item'][$data_item]) && !empty($weekArr['item'][$data_item]['all']) ? $weekArr['item'][$data_item]['all'] : 0,
                        'nowAdd'=>isset($weekArr['item'][$data_item]) && !empty($weekArr['item'][$data_item]['nowAdd']) ? $weekArr['item'][$data_item]['nowAdd'] : 0,
                        'preAllAdd'=>isset($weekArr['item'][$data_item]) && !empty($weekArr['item'][$data_item]['preAllAdd']) ? $weekArr['item'][$data_item]['preAllAdd'] : 0,
                        'preAdd'=>isset($weekArr['item'][$data_item]) && !empty($weekArr['item'][$data_item]['preAdd']) ? $weekArr['item'][$data_item]['preAdd'] : 0
                    ];
                    $weekArr['sig'][$data_item][$data_itemsig] = [
                        'all'=>isset($weekArr['sig'][$data_item]) && isset($weekArr['sig'][$data_item][$data_itemsig]) && !empty($weekArr['sig'][$data_item][$data_itemsig]['all']) ? $weekArr['sig'][$data_item][$data_itemsig]['all'] : 0,
                        'nowAdd'=>isset($weekArr['sig'][$data_item]) && isset($weekArr['sig'][$data_item][$data_itemsig]) && !empty($weekArr['sig'][$data_item][$data_itemsig]['nowAdd']) ? $weekArr['sig'][$data_item][$data_itemsig]['nowAdd'] : 0,
                        'preAllAdd'=>isset($weekArr['sig'][$data_item]) && isset($weekArr['sig'][$data_item][$data_itemsig]) && !empty($weekArr['sig'][$data_item][$data_itemsig]['preAllAdd']) ? $weekArr['sig'][$data_item][$data_itemsig]['preAllAdd'] : 0,
                        'preAdd'=>isset($weekArr['sig'][$data_item]) && isset($weekArr['sig'][$data_item][$data_itemsig]) && !empty($weekArr['sig'][$data_item][$data_itemsig]['preAdd']) ? $weekArr['sig'][$data_item][$data_itemsig]['preAdd'] : 0
                    ];

                    //累计增加数
                    $weekArr['item'][$data_item]['all'] += 1;
                    $weekArr['sig'][$data_item][$data_itemsig]['all'] += 1;

                    //截止上周累计
                    if($week_is_preall == 1){
                        $weekArr['item'][$data_item]['preAllAdd'] += 1;
                        $weekArr['sig'][$data_item][$data_itemsig]['preAllAdd'] += 1;
                        //上周新增数
                        if($week_is_pre == 1){
                            $weekArr['item'][$data_item]['preAdd'] += 1;
                            $weekArr['sig'][$data_item][$data_itemsig]['preAdd'] += 1;
                        }
                    }

                    //本周新增数
                    if($week_is_now == 1){
                        $weekArr['item'][$data_item]['nowAdd'] += 1;
                        $weekArr['sig'][$data_item][$data_itemsig]['nowAdd'] += 1;
                    }
                }
                unset($week_is_add);
                unset($week_is_pre);
                unset($week_is_preall);
                unset($week_is_now);

                //月进度
                if($month_is_add == 1){
                    $monthArr['item'][$data_item] = [
                        'all'=>isset($monthArr['item'][$data_item]) && !empty($monthArr['item'][$data_item]['all']) ? $monthArr['item'][$data_item]['all'] : 0,
                        'nowAdd'=>isset($monthArr['item'][$data_item]) && !empty($monthArr['item'][$data_item]['nowAdd']) ? $monthArr['item'][$data_item]['nowAdd'] : 0,
                        'preAllAdd'=>isset($monthArr['item'][$data_item]) && !empty($monthArr['item'][$data_item]['preAllAdd']) ? $monthArr['item'][$data_item]['preAllAdd'] : 0,
                        'preAdd'=>isset($monthArr['item'][$data_item]) && !empty($monthArr['item'][$data_item]['preAdd']) ? $monthArr['item'][$data_item]['preAdd'] : 0
                    ];
                    $monthArr['sig'][$data_item][$data_itemsig] = [
                        'all'=>isset($monthArr['sig'][$data_item]) && isset($monthArr['sig'][$data_item][$data_itemsig]) && !empty($monthArr['sig'][$data_item][$data_itemsig]['all']) ? $monthArr['sig'][$data_item][$data_itemsig]['all'] : 0,
                        'nowAdd'=>isset($monthArr['sig'][$data_item]) && isset($monthArr['sig'][$data_item][$data_itemsig]) && !empty($monthArr['sig'][$data_item][$data_itemsig]['nowAdd']) ? $monthArr['sig'][$data_item][$data_itemsig]['nowAdd'] : 0,
                        'preAllAdd'=>isset($monthArr['sig'][$data_item]) && isset($monthArr['sig'][$data_item][$data_itemsig]) && !empty($monthArr['sig'][$data_item][$data_itemsig]['preAllAdd']) ? $monthArr['sig'][$data_item][$data_itemsig]['preAllAdd'] : 0,
                        'preAdd'=>isset($monthArr['sig'][$data_item]) && isset($monthArr['sig'][$data_item][$data_itemsig]) && !empty($monthArr['sig'][$data_item][$data_itemsig]['preAdd']) ? $monthArr['sig'][$data_item][$data_itemsig]['preAdd'] : 0
                    ];

                    //累计增加数
                    $monthArr['item'][$data_item]['all'] += 1;
                    $monthArr['sig'][$data_item][$data_itemsig]['all'] += 1;

                    //截止上月累计
                    if($month_is_preall == 1){
                        $monthArr['item'][$data_item]['preAllAdd'] += 1;
                        $monthArr['sig'][$data_item][$data_itemsig]['preAllAdd'] += 1;
                        //上周新增数
                        if($month_is_pre == 1){
                            $monthArr['item'][$data_item]['preAdd'] += 1;
                            $monthArr['sig'][$data_item][$data_itemsig]['preAdd'] += 1;
                        }
                    }

                    //本月新增数
                    if($month_is_now == 1){
                        $monthArr['item'][$data_item]['nowAdd'] += 1;
                        $monthArr['sig'][$data_item][$data_itemsig]['nowAdd'] += 1;
                    }
                }
                unset($month_is_add);
                unset($month_is_pre);
                unset($month_is_preall);
                unset($month_is_now);

                unset($data_item);
                unset($data_itemsig);
                unset($data_check_date);
                unset($datas[$dataKey]);
            }
            unset($checkFormDateArr);
        }
        unset($datas);
        unset($pre_date);
        unset($pre_date_start);
        unset($pre_date_end);
        unset($now_week_start_date);
        unset($now_week_end_date);
        unset($pre_week_start_date);
        unset($pre_week_end_date);
        unset($now_month_start_date);
        unset($now_month_end_date);
        unset($pre_month_start_date);
        unset($pre_month_end_date);
        unset($check_form_where);

        //日进度排名
        if(!empty($dayArr['sig'])){
            $itemSigCountArr = $itemSigPreCountArr = [];
            foreach($dayArr['sig'] as $arr_itemid=>$arr_item_sigs){
                foreach($arr_item_sigs as $arr_item_sigid=>$arr_item_sig){
                    $itemSigCountArr[$arr_itemid][$arr_item_sig['all']][] = $arr_item_sigid;
                    $itemSigPreCountArr[$arr_itemid][$arr_item_sig['preAllAdd']][] = $arr_item_sigid;
                }
            }
            //累计排名
            foreach($itemSigCountArr as $itemSigItemId=>$itemSigCounts){
                krsort($itemSigCounts);
                $itemSigRanking = 1;
                foreach($itemSigCounts as $itemSigCount=>$itemSigCountSigs){
                    foreach($itemSigCountSigs as $itemSigCountSig){
                        $dayArr['sig_ranking'][$itemSigItemId][$itemSigCountSig]['now'] = $itemSigRanking;
                    }
                    $itemSigRanking++;
                    unset($itemSigCounts[$itemSigCount]);
                    unset($itemSigCountArr[$itemSigItemId][$itemSigCount]);
                }
                unset($itemSigCountArr[$itemSigItemId]);
                $dayArr['othersig_ranking'][$itemSigItemId]['now'] = $itemSigRanking;
                unset($itemSigRanking);
            }
            unset($itemSigCountArr);

            //上周、月排名
            foreach($itemSigPreCountArr as $itemSigPreItem=>$itemSigPreCounts){
                krsort($itemSigPreCounts);
                $itemSigPreRanking = 1;
                foreach($itemSigPreCounts as $itemSigPreCount=>$itemSigPreCountSigs){
                    foreach($itemSigPreCountSigs as $itemSigPreCountSig){
                        $dayArr['sig_ranking'][$itemSigPreItem][$itemSigPreCountSig]['pre'] = $itemSigPreRanking;
                    }
                    $itemSigPreRanking++;
                    unset($itemSigPreCounts[$itemSigPreCount]);
                    unset($itemSigPreCountArr[$itemSigPreItem][$itemSigPreCount]);
                }
                unset($itemSigPreCountArr[$itemSigPreItem]);
                $dayArr['othersig_ranking'][$itemSigPreItem]['pre'] = $itemSigPreRanking;
                unset($itemSigPreRanking);
            }
            unset($itemSigPreCountArr);
        }

        //周进度排名
        if(!empty($weekArr['sig'])){
            $itemSigCountArr = $itemSigPreCountArr = [];
            foreach($weekArr['sig'] as $arr_itemid=>$arr_item_sigs){
                foreach($arr_item_sigs as $arr_item_sigid=>$arr_item_sig){
                    $itemSigCountArr[$arr_itemid][$arr_item_sig['all']][] = $arr_item_sigid;
                    $itemSigPreCountArr[$arr_itemid][$arr_item_sig['preAllAdd']][] = $arr_item_sigid;
                }
            }
            //累计排名
            foreach($itemSigCountArr as $itemSigItemId=>$itemSigCounts){
                krsort($itemSigCounts);
                $itemSigRanking = 1;
                foreach($itemSigCounts as $itemSigCount=>$itemSigCountSigs){
                    foreach($itemSigCountSigs as $itemSigCountSig){
                        $weekArr['sig_ranking'][$itemSigItemId][$itemSigCountSig]['now'] = $itemSigRanking;
                    }
                    $itemSigRanking++;
                    unset($itemSigCounts[$itemSigCount]);
                    unset($itemSigCountArr[$itemSigItemId][$itemSigCount]);
                }
                unset($itemSigCountArr[$itemSigItemId]);
                $weekArr['othersig_ranking'][$itemSigItemId]['now'] = $itemSigRanking;
                unset($itemSigRanking);
            }
            unset($itemSigCountArr);

            //上周排名
            foreach($itemSigPreCountArr as $itemSigPreItem=>$itemSigPreCounts){
                krsort($itemSigPreCounts);
                $itemSigPreRanking = 1;
                foreach($itemSigPreCounts as $itemSigPreCount=>$itemSigPreCountSigs){
                    foreach($itemSigPreCountSigs as $itemSigPreCountSig){
                        $weekArr['sig_ranking'][$itemSigPreItem][$itemSigPreCountSig]['pre'] = $itemSigPreRanking;
                    }
                    $itemSigPreRanking++;
                    unset($itemSigPreCounts[$itemSigPreCount]);
                    unset($itemSigPreCountArr[$itemSigPreItem][$itemSigPreCount]);
                }
                unset($itemSigPreCountArr[$itemSigPreItem]);
                $weekArr['othersig_ranking'][$itemSigPreItem]['pre'] = $itemSigPreRanking;
                unset($itemSigPreRanking);
            }
            unset($itemSigPreCountArr);
        }

        //月进度排名
        if(!empty($monthArr['sig'])){
            $itemSigCountArr = $itemSigPreCountArr = [];
            foreach($monthArr['sig'] as $arr_itemid=>$arr_item_sigs){
                foreach($arr_item_sigs as $arr_item_sigid=>$arr_item_sig){
                    $itemSigCountArr[$arr_itemid][$arr_item_sig['all']][] = $arr_item_sigid;
                    $itemSigPreCountArr[$arr_itemid][$arr_item_sig['preAllAdd']][] = $arr_item_sigid;
                }
            }
            //累计排名
            foreach($itemSigCountArr as $itemSigItemId=>$itemSigCounts){
                krsort($itemSigCounts);
                $itemSigRanking = 1;
                foreach($itemSigCounts as $itemSigCount=>$itemSigCountSigs){
                    foreach($itemSigCountSigs as $itemSigCountSig){
                        $monthArr['sig_ranking'][$itemSigItemId][$itemSigCountSig]['now'] = $itemSigRanking;
                    }
                    $itemSigRanking++;
                    unset($itemSigCounts[$itemSigCount]);
                    unset($itemSigCountArr[$itemSigItemId][$itemSigCount]);
                }
                unset($itemSigCountArr[$itemSigItemId]);
                $monthArr['othersig_ranking'][$itemSigItemId]['now'] = $itemSigRanking;
                unset($itemSigRanking);
            }
            unset($itemSigCountArr);

            //上月排名
            foreach($itemSigPreCountArr as $itemSigPreItem=>$itemSigPreCounts){
                krsort($itemSigPreCounts);
                $itemSigPreRanking = 1;
                foreach($itemSigPreCounts as $itemSigPreCount=>$itemSigPreCountSigs){
                    foreach($itemSigPreCountSigs as $itemSigPreCountSig){
                        $monthArr['sig_ranking'][$itemSigPreItem][$itemSigPreCountSig]['pre'] = $itemSigPreRanking;
                    }
                    $itemSigPreRanking++;
                    unset($itemSigPreCounts[$itemSigPreCount]);
                    unset($itemSigPreCountArr[$itemSigPreItem][$itemSigPreCount]);
                }
                unset($itemSigPreCountArr[$itemSigPreItem]);
                $monthArr['othersig_ranking'][$itemSigPreItem]['pre'] = $itemSigPreRanking;
                unset($itemSigPreRanking);
            }
            unset($itemSigPreCountArr);
        }

        //返回信息
        $arr = [];
        if($return_type == 0){
            $arr = $dayArr;
        }
        if($return_type == 1){
            $arr = $weekArr;
        }
        if($return_type == 2){
            $arr = $monthArr;
        }
        if($return_type == 3){
            $arr = [
                'day'=>$dayArr,
                'week'=>$weekArr,
                'month'=>$monthArr
            ];
        }

        unset($dayArr);
        unset($weekArr);
        unset($monthArr);
        return $arr;
    }

}