<?php

namespace Application\Service\DB\Item;

use Interop\Container\Containerinterface;
use Application\Service\Extension\Helper\DataHelper;
use Application\Service\Extension\Laminas;
use Application\Service\Extension\Helper\Edcloghelper;
use Laminas\Db\Sql\Predicate\Like;
use Laminas\Db\Sql\Predicate\Operator;
class PatientFormContentUpdated extends \Application\Service\DB\AbstractDb
{
    public function __construct($dbAdapter, ContainerInterface $container)
    {
        if (!$this->tableName) {
            $this->tableName = 'yikeen_item_patient_form_content_updated';
        }

        parent::__construct($dbAdapter, $container);
    }

    public function changeAeErrorId($ae_id,$changeAe_id,$patient_id,$form_id,$newData,$oldData)
    {
        if($ae_id != $changeAe_id){
            $errorData = $this->LocalService()->itemPatientFormLogicError->fetchCol('id',[
                'patient_id' => $patient_id,
                'checktime_id' => 0,
                'is_report' => 0,
                'multi_id' => $ae_id,
                'form_id' => $form_id,
            ]);
            if($errorData){
                $this->LocalService()->itemPatientFormLogicError->update(
                    [
                        'multi_id'=>$changeAe_id
                    ],
                    [
                        'id'=>$errorData,
                        'patient_id'=>$patient_id,
                        'checktime_id'=>0,
                        'is_report'=>0,
                        'multi_id'=>$ae_id,
                        'form_id'=>$form_id
                    ]
                );

                $errorData = $this->LocalService()->itemPatientFormLogicErrorPointer->update(['multi_id'=>$changeAe_id],['error_id'=>$errorData]);
            }
        }
        $newData = $newData;
        $oldData = json_decode($oldData,true);
        $updatedFields = [];
        $item_id = $newData['item_id'];
        foreach ($newData as $k => $data) {
            if (DataHelper::isField($k)) {
                // 有数据修改再解锁
                if (is_array($data)) {
                    sort($data);
                }

                if (is_array($oldData[$k])) {
                    sort($oldData[$k]);
                }
                if (!isset($oldData[$k]) || $data != $oldData[$k]) {
                    $updatedFields[$k] = $oldData[$k];
                }
            }
        }

        //*******************************
        $callable = function ($id, $autoReply = false, $pointer = null)  use($item_id){
            // 被关联的质疑自动关闭的时候要加一个自动回复
            if ($autoReply === true) {
                Laminas::$serviceManager->itemPatientFormLogicErrorQuery->save([
                    'content' => '上级菜单数据更新!',
                    'error_id' => $id,
                    'platform' => 1,
                    'is_reply' => 1,
                    'pointer_id' => $pointer,
                    'item_id' => $item_id,
                    'create_user_id' => 0 // 系统
                ]);
            }

            // 删除质疑
            Laminas::$serviceManager->itemPatientFormLogicError->update(['is_closed' => 1], ['id' => $id]);
            //Laminas::$serviceManager->itemPatientFormLogicErrorQuery->update(['is_del' => 1], ['error_id' => $id]);
            Laminas::$serviceManager->itemPatientFormLogicErrorLog->update(['is_closed' => 1], ['error_id' => $id]);
            //Laminas::$serviceManager->itemPatientFormLogicErrorPointer->update(['is_del' => 1], ['error_id' => $id]);
        };
        if ($updatedFields) {
            foreach ($updatedFields as $field => $v) {
                $childError = Laminas::$serviceManager->itemPatientFormLogicErrorPointer->fetchAll([
                    'where' => [
                        'patient_id' => $patient_id,
                        'checktime_id' => 0,
                        'form_id' => $form_id,
                        new Like('prop', "%{$field}%"),
                        new Operator('prop', Operator::OP_NE, $field),
                        'is_del' => 0
                    ]
                ]) ?: [];

                foreach ($childError as $error) {
                    $callable($error['error_id'], true, $error['id']);
                }
            }
        }
        //*******************************


        //判断是否操作过SDV或者REVIEW
        $sdv_review_where = [
            'is_del' => 0,
            'patient_id' => $patient_id,
            'form_id' => $form_id,
            'content_id' => $ae_id,
            [
                'or' => [
                    'is_sdv' => 1,
                    'is_review' => 1,
                ]
            ]
        ];
        $sdv_review_count = Laminas::$serviceManager->projectPatientworkinfo->getCount($sdv_review_where);
        unset($sdv_review_where);
        if (empty($sdv_review_count)) {
            return;
        }

        $has = Laminas::$serviceManager->patientFormContentUpdated->fetchOne([
            'where' => [
                'content_id' => $ae_id,
                'form_id' => $form_id
            ]
        ]);
        if($has){
            $update_fields = !empty($updatedFields) ? json_encode($updatedFields) : NULL;
            Laminas::$serviceManager->patientFormContentUpdated->update(['is_del'=>0,'fields' => $update_fields, 'content_id'=>$changeAe_id], ['id'=>$has['id']]);
            unset($update_fields);
        }else{
            if(!empty($updatedFields)){
                Laminas::$serviceManager->patientFormContentUpdated->insert([
                    'item_id' => $newData['item_id'],
                    'checktime_id' => 0,
                    'form_id' => $form_id,
                    'patient_id' => $patient_id,
                    'fields' => json_encode($updatedFields),
                    'content_id' => $changeAe_id,
                    'is_multi' => 1
                ]);
            }
        }

        return true;
    }


}