<?php
/**
 *
 * @author：llbjj
 * @DateTime：2024/7/31 20:39
 * @Description：
 *
 */

namespace Application\Controller;

use Application\Common\Com;
use Application\Common\StatusCode;
use Application\Mvc\Controller\BasicController;
use Application\Service\Exceptions\InvalidArgumentException;
use Application\Service\Extension\Helper\StringHelper;
use Exception;
use Laminas\Cache\Exception\ExceptionInterface;
use Laminas\Db\Sql\Predicate\Expression;
use Laminas\Mvc\MvcEvent;
use Laminas\View\Model\JsonModel;

class PatientH5Controller extends BasicController
{
    protected ?array $patientData;
    public function attachDefaultListeners()
    {
        parent::attachDefaultListeners(); // TODO: Change the autogenerated stub

        $event = $this->getEventManager();
        $event->attach(MvcEvent::EVENT_DISPATCH, [$this, 'checkPatientStatus'], 100);
    }

    /**
     * Notes: 检测当前登录账户对应的受试者的状态
     * User: llbjj
     * DateTime: 2024/8/1 9:26
     *
     * @throws ExceptionInterface
     */
    public function checkPatientStatus() {
        // 检测当前用户的状态
        $adminUser = $this->LocalService()->adminUser->fetchOne([
            'where' => ['id' => $this->LocalService()->identity->getId(), 'is_del' => 0],
            'columns' => ['patient_status', 'id', 'patient_openid']
        ]);
        if(empty($adminUser)) throw new InvalidArgumentException('账户不存在！');
        if($adminUser['patient_status']) throw new InvalidArgumentException('账户已禁用！');
        // 检测用户是否关注
        if(( $this->LocalService()->toolSys->getWechatUserStatus($adminUser['patient_openid'], 'patient')['userStatus'] ?? 'unsubscribe' ) === 'unsubscribe') {
            throw new InvalidArgumentException('尚未关注公众号！');
        }

        // 获取对应的受试者信息
        $patientData = $this->LocalService()->patient->fetchOne([
            'where' => ['patient_tel' => $this->LocalService()->identity->getMobile(), 'is_del' => 0],
            'columns' => [ 'id', 'item_id', 'itemsig_id', 'patient_name', 'patient_number' ]
        ]);

        if(empty($patientData)) throw new InvalidArgumentException('受试者不存在！');
        $this->patientData = $patientData;
    }

    public function editSendAction(): JsonModel
    {
        $date = $this->params()->fromPost('date', time());
        $date = $date ?: time();

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

        $itemMessageSendPatientWhere = [
            'where' => 'is_del=0 and item_id='.$this->patientData['item_id'].' and patient_id='.$this->patientData['id'].' and FROM_UNIXTIME(create_time ,"%Y-%m-%d")="'.date('Y-m-d', $date).'"',
            'columns'=>['item_id','content','itemsig_id','patient_id','id', 'is_write'],
        ];
        $itemMessageSendInfo = $this->LocalService()->itemMessageSendPatient->fetchOne($itemMessageSendPatientWhere);
        if (!empty($itemMessageSendInfo) && $itemMessageSendInfo['is_write'] == 1){
            return $this->RenderApiJson()->Success([
                'itemMessageSendInfo' => [
                    'is_write' => 1
                ]
            ]);
        }

        $com = new Com();

        $itemMessageSendInfo['itemInfoName'] = $this->LocalService()->itemInfo->getOneFieldVal('name','id='.$this->patientData['item_id'])?:'';
        $itemMessageSendInfo['patient_name'] = $this->patientData['patient_name'] ?: '';
        if($this->patientData['patient_number']) $itemMessageSendInfo['patient_name'] .=  "【{$this->patientData['patient_number']}】";


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

        $itemMessageFieldWhere = [
            'is_del' => 0,
            'item_id' => $this->patientData['item_id'],
        ];

        $itemMessageFieldData = $this->LocalService()->itemMessageField->fetchAll([
            'where' => $itemMessageFieldWhere,
            'order' => ['mess_order']
        ]);
        $relation = [];
        if(!empty($itemMessageFieldData)){
            $relationFieldData = [];
            $relationIdArr = [];
            $relationId = array_filter(array_column($itemMessageFieldData,'relation_id'));
            if (!empty($relationId)){
                $relationIds = implode(',',$relationId);
                $relationFieldData = $this->LocalService()->itemMessageField->fetchAll(['where' => [
                    'is_del' => 0,
                    'item_id' => $this->patientData['item_id'],
                    [
                        'or' => [
                            'id' => StringHelper::toArray($relationIds),
                            'parent' => StringHelper::toArray($relationIds)
                        ]
                    ]
                ],'order' => ['mess_order']]);

            }
            if(!empty($relationFieldData)){
                $relationFieldData = $com->getTree($relationFieldData,0,0,2,'parent');
                $relationIdArr = array_column($relationFieldData,'id');
            }
            $relationFieldDatas = $this->LocalService()->itemMessageSend->getPatientattrTemplate($relationFieldData);

            if(!empty($relationFieldDatas)) {
                foreach ($itemMessageFieldData as $itemMessageFieldDataK => $itemMessageFieldDataV){
                    if (!empty($itemMessageFieldDataV['relation_id'])){
                        $relationIdData = explode(',',$itemMessageFieldDataV['relation_id']);
                        foreach ($relationFieldDatas as $relationFieldDatasK=>$relationFieldDatasV) {
                            if (in_array($relationFieldDatasV['id'],$relationIdData)){
                                $relationFieldDatasV['prop'] = $relationFieldDatasV['id'];
                                $relation[$itemMessageFieldDataV['parent']][$itemMessageFieldDataV['id']][] = $relationFieldDatasV;
                            }

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

        }

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


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

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

    /**
     * @throws Exception
     */
    public function savePatientSendAction(): JsonModel
    {
        $newData['item_id'] = $this->patientData['item_id'] ?: 0;
        $newData['patient_id'] = $this->patientData['id'] ?: 0;
        $newData['itemsig_id'] = $this->patientData['itemsig_id'] ?: 0;
        $newData['id'] = $this->params()->fromPost('id', 0);
        $newData['content'] = $this->params()->fromPost('content', '');

        $date = $this->params()->fromPost('date', 0);
        $date = $date ?: time();

        $com = new Com();
        if (empty($newData['item_id']) || empty($newData['content']) || empty($newData['patient_id'])){
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, '参数不正确');
        }
        //验证链接
        if((strtotime(date('Y-m-d',$date)) != strtotime(date('Y-m-d'))) || empty($date)){
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, '信息已过期');
        }
        $itemMessageSendInfo = $this->LocalService()->itemMessageSend->fetchOne(['where'=> [
            'is_del' => 0,
            'item_id' => $newData['item_id'],
        ]]);
        if (empty($itemMessageSendInfo)){
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, '信息已过期');
        }

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

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

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

        $FormFileDatas = $this->LocalService()->itemMessageSend->getPatientattrTemplate($itemMessageFieldData);


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

            unset($contentField['content']);

        }

        $FormFileData =$this->Introduce('MessageSendPatient',['item_id'=>$newData['item_id'],'messageSend'=>$FormFileDatas]);

        empty($newData['id']) && $newData['id'] = $itemMessageSendPatientInfo['id'];
        $newData['write_time'] = time();

        $result = $this->LocalService()->itemMessageSendPatient->save($newData);
        unset($newData['write_time']);
        unset($newData['update_user_id']);

        $contentField['realname'] = $this->patientData['patient_name'];
        $contentField['data_type_flag'] = 1;
        if (!empty($result)) $this->LocalService()->log->saveFileLog($newData['id'],'MessageSendPatient',$contentField,0,'暂无说明',$newData['item_id'],'',['item_id'=>$newData['item_id'],'messageSend'=>$FormFileData]);

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