<?php

namespace Application\Service\DB\Item;

use Interop\Container\Containerinterface;
use Application\Service\Extension\Helper\StringHelper;

class PatientFormLogic extends \Application\Service\DB\AbstractDb
{
    public function __construct($dbAdapter, ContainerInterface $container)
    {
        if (!$this->tableName) {
            $this->tableName = 'yikeen_item_patient_form_logic';
        }

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

    public function CopyLogic($old_item_id,$new_item_id,$checktimeMap,$formMap,$fieldMap)
    {
        $data = $this->fetchAll([
            'where'=> [
                'is_del' => 0,
                'item_id' => $old_item_id,
            ]
        ]);
        if(empty($data)) return true;
        foreach($data as $k=>$v){
            $arr = [];
            $arr['expression'] = $v['expression'];
            $arr['item_id'] = $new_item_id;
            $array = explode("'",$v['generate_expression']);
            foreach($array as $key=>$value){
                if(is_numeric($value)){
                    if(isset($checktimeMap[$value])){
                        $v['generate_expression'] = str_replace($value, $checktimeMap[$value], $v['generate_expression']);
                    }
                }
            }

            $arr['generate_expression'] = $v['generate_expression'];
            $arr['expression_hash'] = StringHelper::generateHashValue();;
            $arr['note'] = $v['note'];
            $generator = unserialize($v['generator']);
            $generator->expression = $v['generate_expression'];
            $generator->itemId = $new_item_id;
            $generator->expressHash = $arr['expression_hash'];

            foreach($generator->allusings as $kk=>$vv){
                $tmpArr = explode('_',$vv);
                if(isset($checktimeMap[$tmpArr[0]])){
                    $tmpArr[0] = $checktimeMap[$tmpArr[0]];
                }
                if(isset($checktimeMap[$formMap[1]])){
                    $tmpArr[1] = $checktimeMap[$tmpArr[1]];
                }
                if(isset($checktimeMap[$fieldMap[2]])){
                    $tmpArr[2] = $checktimeMap[$tmpArr[2]];
                }
                $generator->allusings[$kk] = implode('_',$tmpArr);
            }
            $arr['generator'] = serialize($generator);
            $this->insert($arr);
        }
        return true;
    }
}