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

namespace Application\Service\DB\Item;

use Application\Service\Extension\Laminas;
use Interop\Container\ContainerInterface;
use Application\Service\Extension\Helper\ArrayHelper;
use Laminas\Db\Sql\Predicate\Operator;

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

    public function sendTemplateMessage(){
        $app = $this->LocalService()->wechat->getApp();
        $miniAppId = $this->LocalService()->config['applets']['eyda']['app_id'];
        $itemStageData = $this->LocalService()->itemResearchstage->fetchCol('remind_time','is_del=0 and is_booked=1 and remind_time > 0 and is_remind=0');
        if (empty($itemStageData)) return false;

        $whereItemChecktime['where'] = [
            new Operator('is_del', Operator::OP_NE, 1),
            'stage_id' => array_keys($itemStageData),
        ];

        $whereItemChecktime['columns'] = ['id', 'stage_id','check_name'];
        $itemChecktimeData = $this->LocalService()->itemChecktime->fetchAll($whereItemChecktime);
        if (empty($itemChecktimeData)) return false;
        foreach ($itemChecktimeData as &$itemChecktimeDatum) {
            $itemChecktimeDatum['remind_time'] = $itemStageData[$itemChecktimeDatum['stage_id']];
        }
        $itemChecktimeDatas = $this->LocalService()->itemCsae->arrayChangeIndexs($itemChecktimeData);



        $whereItemPatientbooked['where'] = [
            'is_del' => 0,
            'checktime_id' => array_keys($itemChecktimeDatas),
            new Operator('booked_time', Operator::OP_GT, 0),
        ];
        $whereItemPatientbooked['columns'] = ['id','checktime_id','patient_id','booked_time'];

        $itemPatientbookedData = $this->LocalService()->itemPatientbooked->fetchAll($whereItemPatientbooked);
        if (empty($itemPatientbookedData)) return false;
        $patientIdArr = array_column($itemPatientbookedData,'patient_id');
        if (empty($patientIdArr)) return false;


        $wherePatientArr['where'] = [
            'is_del' => 0,
            'id' => $patientIdArr,
        ];
        $wherePatientArr['columns'] = ['id','patient_name','patient_number','item_id','itemsig_id','patient_tel'];//,'openid'
        $patientData = $this->LocalService()->patient->fetchAll($wherePatientArr);//$item_id
        if (empty($patientData)) return false;
        $patientDatas = $this->LocalService()->itemCsae->arrayChangeIndexs($patientData);

        //中心下的crc的所有人
        $roleSignatoryRelationDatas = $this->roleSignatoryRelationDatas($patientDatas);
        if (empty($roleSignatoryRelationDatas)) return false;

        $sendPatientBookedData = [];

        foreach($roleSignatoryRelationDatas as $roleSignatoryRelationDatasKey =>$roleSignatoryRelationDatasValue){

            //crc的openid为空就跳过
            if (empty($roleSignatoryRelationDatasValue)) continue;

            foreach($itemPatientbookedData as $bookedKey =>&$patientBookedData){
            //暂时先给crc发信息
                if(!isset($patientDatas[$patientBookedData['patient_id']])){
                    if ($patientDatas[$patientBookedData['patient_id']]['itemsig_id'] != $roleSignatoryRelationDatasKey){

                        unset($itemPatientbookedData[$bookedKey]);
                        continue;
                    }
                }
                $patientBookedData['itemsig_id'] = $patientDatas[$patientBookedData['patient_id']]['itemsig_id'];

                //是否预约
                if (!isset($itemChecktimeDatas[$patientBookedData['checktime_id']])){
                    unset($itemPatientbookedData[$bookedKey]);
                    continue;

                }

                $remind_time = !empty($itemChecktimeDatas[$patientBookedData['checktime_id']]['remind_time'])?$itemChecktimeDatas[$patientBookedData['checktime_id']]['remind_time']:0;
                $patientBookedData['stage_id'] = isset($itemChecktimeDatas[$patientBookedData['checktime_id']]['stage_id'])?$itemChecktimeDatas[$patientBookedData['checktime_id']]['stage_id']:0;
                $patientBookedData['remind_time'] =  $remind_time;
                if ($remind_time <= 0){
                    unset($itemPatientbookedData[$bookedKey]);
                    continue;
                }

                $booked_time = strtotime('-'.$remind_time.' days',$patientBookedData['booked_time']);
                $time = time();

                if (($booked_time > $time) || ($patientBookedData['booked_time'] < $time)){
                    unset($itemPatientbookedData[$bookedKey]);
                    continue;
                }

                $patientBookedData['booked_time'] = date('Y-m-d',$patientBookedData['booked_time']);

                //受试者
                $patientBookedData['patient_name'] = $patientDatas[$patientBookedData['patient_id']]['patient_name'];
                $patientBookedData['patient_tel'] = $patientDatas[$patientBookedData['patient_id']]['patient_tel'];
                $patientBookedData['patient_number'] = $patientDatas[$patientBookedData['patient_id']]['patient_number'];

                $patientBookedData['itemsig_name'] = '';
                $patientBookedData['item_name'] = '';
                //中心
                $itemSigninfo = $this->LocalService()->itemRandomdetails->itemSigninfo($patientDatas[$patientBookedData['patient_id']]['itemsig_id']);
                if (!empty($itemSigninfo) && isset($itemSigninfo[0]['info_name'])){
                    $patientBookedData['itemsig_name'] = $itemSigninfo[0]['info_name'];

                }
                $patientBookedData['item_name'] = $this->LocalService()->itemInfo->getOneFieldVal('name', 'is_del=0 and id='.$patientDatas[$patientBookedData['patient_id']]['item_id'])?:'';
                $patientBookedData['item_type'] = $this->LocalService()->itemInfo->getOneFieldVal('item_type', 'is_del=0 and id='.$patientDatas[$patientBookedData['patient_id']]['item_id'])?:0;
                !empty($patientBookedData['item_type']) && $miniAppId = $this->LocalService()->config['applets']['scritrials']['app_id'];

                //是否预约
                $patientBookedData['stage_id'] = $itemChecktimeDatas[$patientBookedData['checktime_id']]['stage_id'];
                $patientBookedData['check_name'] = $itemChecktimeDatas[$patientBookedData['checktime_id']]['check_name'];
                $patientBookedData['remind_time'] = $itemChecktimeDatas[$patientBookedData['checktime_id']]['remind_time'];
                $content = '请于'.$patientBookedData['booked_time'].'时间段内，到 '.$patientBookedData['itemsig_name'].' 中心，参加 '.$patientBookedData['check_name'].' 的随访';
                $patientBookedData['content'] = $content;

                //只发给crc
                $patientBookedData['openidArr'] = $roleSignatoryRelationDatasValue;
                foreach ($roleSignatoryRelationDatasValue as $roleSignatoryUserOpenid) {
                    $patientBookedData['openid'] = $roleSignatoryUserOpenid;
                    $senResult = $this->template($app,$patientBookedData,0,'openid',$miniAppId);
                    echo '<pre>'.var_export($senResult);

                }

                $sendPatientBookedData[$bookedKey] = $patientBookedData;
            }
        }

        if(empty($sendPatientBookedData)) return false;
        return true;
    }

    public function roleSignatoryRelationDatas($patientData = []){
        /**
        只给crc发送信息
         */
        //获取大项id
        $itemIdArr = array_column($patientData,'item_id');
        $itemsigIdArr = array_column($patientData,'itemsig_id');
        $itemFidArr= $this->LocalService()->itemInfo->fetchCol('fid', [
            'is_del' => 0,
            'id' => $itemIdArr,
        ]);
        if(empty($itemFidArr)) return false;

        //获取crc角色
        $itemFidArr = array_filter(array_unique($itemFidArr));
        $realRoleIdArr= $this->LocalService()->realRole->fetchCol('role_name', [
            'is_del' => 0,
            'code' => 'crc',
            'item_id' => $itemFidArr,
        ]);
        if(empty($realRoleIdArr)) return false;

        //中心下crc下的所有人
        $roleSignatoryRelationWhere['where'] = [
            'is_del' => 0,
            'status' => 0,
            'item_id' => $itemFidArr,
            'role_id' => array_keys($realRoleIdArr),
            'item_sign_id' => $itemsigIdArr,
        ];
        $roleSignatoryRelationWhere['columns'] = ['id','itemsig_id'=>'item_sign_id','signatory_user','role_id'];
        $roleSignatoryRelationData = $this->LocalService()->roleSignatoryRelation->fetchAll($roleSignatoryRelationWhere);
        if(empty($roleSignatoryRelationData)) return false;

        //crc的手机号
        $signatoryUserIdArr = array_filter(array_unique(array_column($roleSignatoryRelationData,'signatory_user')));
        $signatoryUserWhere = [
            'is_del' => 0,
            'id' => $signatoryUserIdArr,
            new Operator('user_tel', Operator::OP_NE, ''),
        ];
        $signatoryUserTelArr = $this->LocalService()->signatoryUser->fetchCol('user_tel',$signatoryUserWhere);

        $roleSignatoryRelationDatas = [];
        foreach ($roleSignatoryRelationData as $roleSignatoryRelationDataKey=>&$roleSignatoryRelationDataValue) {
            $roleSignatoryRelationDataValue['signatory_user_tel'] = 0;
            $roleSignatoryRelationDataValue['openid'] = '';
            if(isset($signatoryUserTelArr[$roleSignatoryRelationDataValue['signatory_user']])){
                $signatoryUserTel = $signatoryUserTelArr[$roleSignatoryRelationDataValue['signatory_user']];
                $roleSignatoryRelationDataValue['signatory_user_tel'] = $signatoryUserTel;
                $roleSignatoryRelationDataValue['openid'] = $this->LocalService()->adminUser->getOneFieldVal('openid', 'is_del=0 and mobile="'.$signatoryUserTel.'"')?:'';
                if (!empty($roleSignatoryRelationDataValue['openid'])){
                    if (isset($roleSignatoryRelationDatas[$roleSignatoryRelationDataValue['itemsig_id']])){
                        $roleSignatoryRelationDatas[$roleSignatoryRelationDataValue['itemsig_id']][] = $roleSignatoryRelationDataValue['openid'];
                    }else{
                        $roleSignatoryRelationDatas[$roleSignatoryRelationDataValue['itemsig_id']][] = $roleSignatoryRelationDataValue['openid'];
                    }

                }

            }
        }
        $newRoleSignatoryRelationDatas = [];
        foreach ($roleSignatoryRelationDatas as $roleSignatoryRelationDatasKey=>$roleSignatoryRelationDatasValue) {
            $newRoleSignatoryRelationDatas[$roleSignatoryRelationDatasKey] = array_filter(array_unique($roleSignatoryRelationDatasValue));
        }
        return $newRoleSignatoryRelationDatas;
    }

    public function template($app,$data,$type=0,$fieldKey = 'openid',$miniAppId='wx1bec9b82e7e32179'){
        $type = 1;
        $redis = Laminas::$serviceManager->redisExtend->setDatabase(13)->getRedisInstance();
        $keyErr = 'sendTemplateMessgeErr:'.$data[$fieldKey];
        $keySuccess = 'sendTemplateMessgeSuccess:'.$data[$fieldKey];
        $senResult = [
            'errcode'=>-1,
            'errmsg'=>'未发送',
            'msgid'=>'',
        ];
        if(empty($type)){
            $senResult =$app->template_message->send([
                'touser' => 'omKuM6bAzzU4N5knJobSuyAIWFHE',//宁'omKuM6X6VsHxxESv1uFME-ksGO9M',//$data['openid'],//omKuM6bAzzU4N5knJobSuyAIWFHE
                'template_id' => 'Erv7e2y5wCO_L8gviDnecqahDoW4zx3Nob0mSXiDBew',//'Erv7e2y5wCO_L8gviDnecqahDoW4zx3NobOmSXiDBew',//Erv7e2y5wCO_L8gviDnecqahDoW4zx3NobOmSXiDBew//3kdA_Dkk_gDe4Vwym7o2svHiNdkXLUa85gdvrUB7eJo
                'url' => 'https://esm.kingdone.com',
                "topcolor" => "#FF0000",
                'miniprogram'=>[
                    'appid'=>$miniAppId,
                    'pagepath'=>'/pages/index/index',
                ],
                'data' => [
                    'first' => ['value' => '临床试验'],
                    'thing5' => '随访项目',
                    'thing6' => '随访项目1',
                    'character_string4' => 16,
                    'thing3' => '请注意休息，保存最佳状态',
                    'time2' => ['value' => date('Y年m月d日 H:i'), 'color' => '#173177'],
                    'remark' => ['value' => '感谢您对临床项目的支持', 'color' => '#173177'],
                ],
            ]);
        }else{
            $senResult =$app->template_message->send([
                'touser' => $data['openid'],//'omKuM6bAzzU4N5knJobSuyAIWFHE',//$data['openid']
                'template_id' => 'Erv7e2y5wCO_L8gviDnecqahDoW4zx3Nob0mSXiDBew',//'omKuM6bAzzU4N5knJobSuyAIWFHE',//'h4ZKhOdjdflAGeJnpsD6cKzQLZ95kcbjNwVzOBTcEHE',
                'url' => $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['SERVER_NAME'],
                "topcolor" => "#FF0000",
                'miniprogram'=>[
                    'appid'=>$miniAppId,
                    'pagepath'=>'/pages/index/index',
                ],
                'data' => [
                    'first' => ['value' => '您好，您的临床试验随访将于 '.$data['booked_time'].' 开始'],
                    'keyword1' => ['value' => $data['item_name'], 'color' => '#173177'],         //随访项目
                    'keyword2' => ['value' => date('Y年m月d日'), 'color' => '#173177'],            //提醒时间
                    'keyword3' => ['value' => $data['content'], 'color' => '#173177'],                                //提醒内容
                    'keyword4' => ['value' => '请注意休息，保存最佳状态。'],                                 //注意事项
                    'remark' => ['value' => '感谢您对临床项目的支持'],                      //备注
                ],
            ]);
        }
        $success['data'] = $err['data'] = $data;
        $success['senResult'] = $err['senResult'] = $senResult;
        if ($senResult['errcode'] > 0){
            $redisData = json_encode($err);
            $result = $redis->set($keyErr,$redisData);
        }else if(empty($senResult['errcode'])){
            $redisData = json_encode($success);
            $result = $redis->set($keySuccess,$redisData);
        }
        return $senResult;
    }

}