<?php

namespace Application\Service\DB\Item;

use Application\Service\DB\Dictionary\FormGroup;
use Application\Service\Exceptions\InvalidArgumentException;
use Application\Service\Extension\Laminas;
use Application\Service\Extension\Validator\ValidatorApplication;
use Interop\Container\ContainerInterface;
use Application\Form\item\patient\PatientFormModel;

/**
 * 表单申请解锁表
 */
class PatientFormUnlock extends \Application\Service\DB\AbstractDb
{
    /** @var int 正在申请 */
    public const STATUS_WAITING = 1;

    /** @var int 申请已确认 */
    public const STATUS_ENSURE = 2;

    /** @var int 无操作, 或者已回到初始状态 */
    public const STATUS_NONE = 0;

    public const APPLY_UNLOCK_TYPE_MAP_TXT = [
        1 => '解锁不重新识别',
        2 => '解锁重新识别'
    ];

    public function __construct($dbAdapter, ContainerInterface $container)
    {
        if (!$this->tableName) {
            $this->tableName = 'yikeen_item_patient_form_unlock';
        }

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

    private function getUnlockRow(int $contentId)
    {
        return $this->fetchOne([
            'where' => ['content_id' => $contentId]
        ]);
    }

    /**
     * 获取解锁状态
     * @param int $contentId
     * @return int|void
     */
    public function getStatus(int $contentId)
    {
        $query = $this->getUnlockRow($contentId);

        if (!$query) {
            return self::STATUS_NONE;
        }

        if ($query['is_del'] == 0) {
            return self::STATUS_WAITING;
        }

        if ($query['is_del'] == 1 && $query['is_confirm'] == 1) {
            return self::STATUS_ENSURE;
        }

        return null;
    }

    /**
     * 申请解锁
     */
    public function unlock($contentId, $note)
    {
        //获取表单信息
        //获取表单Group类型
        $formData = $this->LocalService()->itemForm->fetchOne([
            'where'=>['is_del'=>0,'id'=>Laminas::$serviceManager->request->getPost('form_id')],
            'columns'=>['group_id','gco_pool']
        ]);
        $formGcoPool = !empty($formData) ? $formData['gco_pool'] : '';
        $formGroupId = !empty($formData) ? $formData['group_id'] : 0;
        unset($formData);
        $contentIdArr = [$contentId];
        if($formGroupId == FormGroup::NORMAL_OCR && $formGcoPool != ''){
            $sharePoolForm = $this->LocalService()->itemForm->fetchCol('id',['is_del'=>0,'item_id'=>Laminas::$serviceManager->request->getPost('item_id'),'gco_pool'=>$formGcoPool]);
            $patientFormContentIdArr = $this->LocalService()->patientFormContent->fetchCol('id',['is_del'=>0,'patient_id'=>Laminas::$serviceManager->request->getPost('patient_id'),'checktime_id'=>Laminas::$serviceManager->request->getPost('checktime_id'),'form_id'=>array_values($sharePoolForm)]);
            $contentIdArr = !empty($patientFormContentIdArr) ? array_values($patientFormContentIdArr) : [];
            unset($patientFormContentIdArr);
            unset($sharePoolForm);
        }
        unset($formGcoPool);
        unset($formGroupId);
        $query_arr = $this->fetchAll([
            'where' => ['content_id' => $contentIdArr]
        ]);
        $unlock_type = empty(Laminas::$serviceManager->request->getPost('unlock_type')) ? 0 : Laminas::$serviceManager->request->getPost('unlock_type');
        $img_field_prop = empty(Laminas::$serviceManager->request->getPost('img_field_prop')) ? '' : Laminas::$serviceManager->request->getPost('img_field_prop');
        $unlock_img = empty(Laminas::$serviceManager->request->getPost('unlock_img')) ? json_encode([]) : Laminas::$serviceManager->request->getPost('unlock_img');

        if ($query_arr) {
            $id = 0;
            foreach($query_arr as $queryKey=>$query){
                if($query['content_id'] == $contentId){
                    $id = $query['id'];
                }
            }
            if (in_array(0,array_values(array_column($query_arr,'is_del')))) {//取消申请解锁
                $id = 0;
                $this->update(['is_del' => 1], ['content_id' => $contentIdArr,'is_del'=>0]);
            }else{//申请解锁
                /*if (in_array(0,array_values(array_column($query_arr,'is_confirm')))) {
                    throw new InvalidArgumentException('当前解锁已经确认, 无法取消。', 1001);
                }*/
                if(!empty($id)){
                    $this->update(['is_del' => 0, 'unlock_note' => $note, 'is_confirm' => 0, 'unlock_type' => $unlock_type,'img_field_prop'=>$img_field_prop,'unlock_img'=>$unlock_img], ['content_id' => $contentId]);
                }else{
                    $id = Laminas::$serviceManager->patientFormUnlock->save([
                        'content_id' => $contentId,
                        'unlock_note' => $note,
                        'unlock_type' => $unlock_type,
                        'img_field_prop' => $img_field_prop,
                        'unlock_img' => $unlock_img,
                    ]);
                }
            }
        } else {
            $id = Laminas::$serviceManager->patientFormUnlock->save([
                'content_id' => $contentId,
                'unlock_note' => $note,
                'unlock_type' => $unlock_type,
                'img_field_prop' => $img_field_prop,
                'unlock_img' => $unlock_img,
            ]);
        }
        unset($query_arr);
        unset($unlock_img);
        unset($img_field_prop);
        unset($unlock_type);

        $isUnlock = $id;
        Laminas::$serviceManager->itemPatientworkannex->update(['is_unlock' => $isUnlock], [
            'item_id' => Laminas::$serviceManager->request->getPost('item_id'),
            'itemsig_id' => Laminas::$serviceManager->request->getPost('itemsig_id'),
            'patient_id' => Laminas::$serviceManager->request->getPost('patient_id'),
            'checktime_id' => Laminas::$serviceManager->request->getPost('checktime_id'),
            'form_id' => Laminas::$serviceManager->request->getPost('form_id'),
        ]);
    }

    /**
     * 确认解锁
     */
    public function ensure($contentId)
    {
        $query = $this->getUnlockRow($contentId);

        if ($query['is_confirm'] == 1) {
            throw new InvalidArgumentException('已经确认解锁, 无法重复解锁。');
        }

        $this->update(['is_confirm' => 1, 'is_del' => 1], ['content_id' => $contentId]);
    }

    /**
     * 重置
     * @param $contentId
     */
    public function reset($contentId)
    {
        $this->update(['is_confirm' => 0, 'is_del' => 1], ['content_id' => $contentId]);
    }

    /**
     * Notes: 申请解锁 更新图片及表单内容信息
     * User: lltyy
     * DateTime: 2025/8/13 18:07
     *
     * @param $content_id
     * @return int
     */
    public function confirmApplyunlock($content_id){
        //获取该笔数据申请解锁信息
        $applyUnlock = $this->fetchOne([
            'where' => ['content_id' => $content_id,'is_del'=>0,'is_confirm'=>0]
        ]);
        if(empty($applyUnlock) || (!empty($applyUnlock) && (empty($applyUnlock['unlock_type']) || is_null($applyUnlock['unlock_type'])))){
            return 0;
        }

        //获取patientFormContent内容
        $content = Laminas::$serviceManager->patientFormContent->fetchOne([
            'where'=>['is_del'=>0,'id'=>$content_id],
            'columns'=>['id','item_id','itemsig_id','patient_id','checktime_id','form_id','data']
        ]);
        if(empty($content)){
            return 0;
        }

        $validator = new ValidatorApplication(json_decode($content['data'],true));
        //赋值表单内容信息
        $validator->attributes['item_id'] = isset($validator->attributes['item_id']) && !empty($validator->attributes['item_id']) ? $content['item_id'] : 0;
        $validator->attributes['itemsig_id'] = isset($validator->attributes['itemsig_id']) && !empty($validator->attributes['itemsig_id']) ? $content['itemsig_id'] : 0;
        $validator->attributes['patient_id'] = isset($validator->attributes['patient_id']) && !empty($validator->attributes['patient_id']) ? $content['patient_id'] : 0;
        $validator->attributes['checktime_id'] = isset($validator->attributes['checktime_id']) && !empty($validator->attributes['checktime_id']) ? $content['checktime_id'] : 0;
        $validator->attributes['form_id'] = isset($validator->attributes['form_id']) && !empty($validator->attributes['form_id']) ? $content['form_id'] : 0;
        $validator->attributes['id'] = $content_id;
        $validator->attributes[$applyUnlock['img_field_prop']] = isset($applyUnlock['unlock_img']) && !empty($applyUnlock['unlock_img']) ? $applyUnlock['unlock_img'] : json_encode([]);
        $validator->attributes['old_data_str'] = $content['data'];
        //更新图片调整信息
        $model = new PatientFormModel($validator);
        $model->setPostValues($validator->attributes);
        $model->handleApplyUnlockForm();

        //申请解锁确认【图片调整但不解锁识别】
        if($applyUnlock['unlock_type'] == 1){
            $formData = Laminas::$serviceManager->itemForm->fetchOne([
                'where'=>['is_del'=>0,'id'=>$validator->attributes['form_id']],
                'columns'=>['group_id','gco_pool']
            ]);
            //更新化验单 所有图片为锁定状态
            if($formData['group_id'] == FormGroup::CHECK_OCR){
                Laminas::$serviceManager->itemPatientworkannex->update(['is_unlock'=>0,'unlock_id'=>0,'lock_state'=>1],['is_del'=>0,'formcontent_id'=>$content_id]);
            }

            //更新常规类（识别）表单 信息
            if($formData['group_id'] == FormGroup::NORMAL_OCR){
                // 记录历史申请解锁原因
                $originReason = Laminas::$serviceManager->redisExtend->getRedisInstance()->hGet("UNLOCK_SHARE_FORM:{$validator->attributes['item_id']}", "{$validator->attributes['patient_id']}:{$validator->attributes['checktime_id']}:{$formData['gco_pool']}");
                // 历史申请过解锁的, 解锁了才存在历史解锁的原因中
                if ($originReason) {
                    Laminas::$serviceManager->redisExtend->getRedisInstance()->hSet("UNLOCK_SHARE_FORM_HISTORY:{$validator->attributes['item_id']}", "{$validator->attributes['patient_id']}:{$validator->attributes['checktime_id']}:{$formData['gco_pool']}", $originReason);
                }
                unset($originReason);
                // 删除申请解锁状态
                Laminas::$serviceManager->redisExtend->getRedisInstance()->hDel("UNLOCK_SHARE_FORM:{$validator->attributes['item_id']}", "{$validator->attributes['patient_id']}:{$validator->attributes['checktime_id']}:{$formData['gco_pool']}");

                // 设置解锁未更新的状态
                Laminas::$serviceManager->redisExtend->getRedisInstance()->hSet("SHARE_FORM_IS_UNLOCK_NOT_UPDATED:{$validator->attributes['item_id']}", "{$validator->attributes['patient_id']}:{$validator->attributes['checktime_id']}:{$formData['gco_pool']}", '1');

            }
            unset($formData);

            //更新申请解锁状态
            $this->ensure($content_id);

            //异步处理申请解锁工作信息
            Laminas::$serviceManager->swTaskClient->send([
                'svName' => 'projectPatientwork',
                'methodName' => 'updatePatientworkData',
                'params' => [
                    'item_id' => $validator->attributes['item_id'],
                    'itemsig_id' => $validator->attributes['itemsig_id'],
                    'patient_id' => $validator->attributes['patient_id'],
                    'checktime_id' => $validator->attributes['checktime_id'],
                    'form_id' => $validator->attributes['form_id'],
                    'user_id' => Laminas::$serviceManager->identity->getId(),
                    'content_id' => $content_id
                ]
            ]);
        }

        //释放空间
        unset($applyUnlock);
        unset($content);
    }
}
