<?php

namespace Application\Service\DB\Project;

use Application\Common\StatusCode;
use Application\Service\Extension\Helper\StringHelper;
use Interop\Container\ContainerInterface;
use Application\Service\DB\Dictionary\FormField;
use Laminas\Db\Sql\Predicate\Operator;

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

    public function itemFormFieldType($newItemIdData = []){
        if (empty($newItemIdData)) return  [];
        $itemFormFieldType = $this->LocalService()->itemFormField->fetchAll([
            'where'=>[
                'is_del' => 0,
                'item_id' => $newItemIdData?:[],
                'type' => FormField::FORM_FIELD_TYPE_UPLOAD_SHARE_IMAGE
            ],
            'columns' => ['item_id','id','form_id','type'],
        ]);
        return  $itemFormFieldType;
        return  $itemFormFieldType?array_column($itemFormFieldType,null,'item_id'):[];
        echo '<pre>';print_r($itemFormFieldType);die;

    }


    //表单添加、编辑、删除字段
    public function saveFormFieldData($data =[]){

        $formFieldId = $data['id']?:0;//259067;//
        $item_id = $data['item_id']?:0;//220;//
        $operType = $data['oper_type']?:0;//1-新增 2-修改 3-删除//1;//
//        echo '<pre>';print_r($data);exit;

        if (empty($formFieldId) || empty($operType) || empty($item_id)) return false;
        $itemfId = $this->LocalService()->itemInfo->getOneFieldVal('fid',[
            'is_del' => 0,
            'id' => $item_id,
        ]);
        if (empty($itemfId)) return false;
        $itemSignatoryId = $this->LocalService()->itemSignatory->fetchCol('id',[
            'is_del' => 0,
            'item_id' => $itemfId,
        ]);
        if (empty($itemSignatoryId)) return false;

        $itemFormFieldWhere = [//is_del = 0 and
            'where'=> [
                'id' => $formFieldId,
                'item_id' => $item_id,
                new Operator('type', Operator::OP_NE, FormField::FORM_FIELD_TYPE_UPLOAD_SHARE_IMAGE)
            ],
            'columns'=>['form_field_id'=>'id','name','form_id','item_id','pid'=>'parent','info_order'=>'order','english','cut_pre','cut_after'],
        ];//'type',
        $itemFormFieldInfo = $this->LocalService()->itemFormField->fetchOne($itemFormFieldWhere)?:[];

        if (!empty($itemFormFieldInfo)){
            $itemFormrecognitionWhere = [
                'where'=> [
                    'is_del' => 0,
                    'item_id' => $item_id,
                    'form_field_id' => $itemFormFieldInfo['form_field_id'],
                    'form_id' => $itemFormFieldInfo['form_id'],
                ],
            ];
            $itemFormrecognitionData = $this->LocalService()->itemFormrecognition->fetchAll($itemFormrecognitionWhere);

            $itemFormrecognitionIsColor = [
                'is_del' => 0,
                'item_id' => $item_id,
                'form_id' => $itemFormFieldInfo['form_id'],
                'itemsig_id' => StringHelper::toArray($itemSignatoryId),
                'is_color' => 1,
            ];
            $itemFormrecognitionSigColor = $this->LocalService()->itemFormrecognition->fetchCol('itemsig_id',$itemFormrecognitionIsColor);
            if (empty($itemFormrecognitionData)){
                //没有就是新增
                if ($operType ==3) return true;

                foreach ($itemSignatoryId as $itemSignatoryIdKey=>&$itemSignatoryIdVal){
                    $itemFormFieldInfo['itemsig_id'] = $itemSignatoryIdVal;
                    $resultid = $this->LocalService()->itemFormrecognition->save($itemFormFieldInfo);
                    if (!empty($itemFormrecognitionSigColor) && in_array($itemSignatoryIdVal,$itemFormrecognitionSigColor)){
                        $recognitionUp = [
                            'is_del' => 0,
                            'item_id' => $item_id,
                            'form_id' => $itemFormFieldInfo['form_id'],
                            'itemsig_id' => $itemSignatoryIdVal,
                        ];
                        $this->LocalService()->itemFormrecognition->update(['is_color'=>0],$recognitionUp);
                    }
                    if (!empty($resultid)){
                        //日志
                        $log_remark = '选择表单识别配置-批量新增保存';
                        $this->LocalService()->log->saveFileLog($resultid,'itemFormrecognition',$itemFormFieldInfo,0,$log_remark,'',' ',[]);
                    }
                }

            }else{
                if ($operType == 1){
                    $itemFormrecognitionSig = array_unique(array_column($itemFormrecognitionData,'itemsig_id'));
                    $itemSignatoryIdDiff = array_diff($itemSignatoryId,$itemFormrecognitionSig);
                    if (!empty($itemSignatoryIdDiff)){
                        foreach ($itemSignatoryIdDiff as $itemSignatoryIdDiffKey=>$itemSignatoryIdDiffVal){
                            $itemFormFieldInfo['itemsig_id'] = $itemSignatoryIdDiffVal;
                            $resultid = $this->LocalService()->itemFormrecognition->save($itemFormFieldInfo);
                            if (!empty($itemFormrecognitionSigColor) && in_array($itemSignatoryIdDiffVal,$itemFormrecognitionSigColor)){
                                $recognitionUp = 'is_del=0 and item_id='.$item_id.' and form_id='.$itemFormFieldInfo['form_id'].' and itemsig_id='.$itemSignatoryIdDiffVal;
                                $this->LocalService()->itemFormrecognition->update(['is_color'=>0],$recognitionUp);
                            }
                            if (!empty($resultid)){
                                //日志
                                $log_remark = '选择表单识别配置-批量选择保存';
                                $this->LocalService()->log->saveFileLog($resultid,'itemFormrecognition',$itemFormFieldInfo,0,$log_remark,'',' ',[]);
                            }
                        }
                    }


                }else{
                    foreach ($itemFormrecognitionData as $itemFormrecognitionDataKey=>&$itemFormrecognitionDataVal){
                        if (($itemFormrecognitionDataVal['form_id'] == $itemFormFieldInfo['form_id']) && ($itemFormrecognitionDataVal['form_field_id'] == $itemFormFieldInfo['form_field_id']) && in_array($itemFormrecognitionDataVal['itemsig_id'],$itemSignatoryId)){
                            $itemFormFieldInfo['id'] = $itemFormrecognitionDataVal['id'];

                            if ($operType == 2){
                                if (!empty($itemFormrecognitionDataVal['is_save'])){
                                    //有保存只更新名称和pid
                                    $arr['id'] = $itemFormrecognitionDataVal['id'];
                                    $arr['name'] = $itemFormFieldInfo['name'];
                                    $arr['pid'] = $itemFormFieldInfo['pid'];
                                }else{
                                    $arr = $itemFormFieldInfo;
                                }
                                $resultid = $this->LocalService()->itemFormrecognition->save($arr);

                            }else{
                                $resultid = $this->LocalService()->itemFormrecognition->update(['is_del'=>1],'id='.$itemFormFieldInfo['id']);

                            }

                        }

                    }
                }

            }

        }
        return true;

    }

    //项目下新增中心
    public function newSigSaveFormFieldData($data =[]){

        $item_id = $data['item_id']?:0;
        $type = $data['type']?:1;//1-大项目 2-小项目
        $itemsig_id = $data['itemsig_id']?:0;

        if (empty($item_id)) return false;
        if (empty($type)) return false;
        if (empty($itemsig_id)) return false;

        $itemIdData = $this->LocalService()->itemInfo->fetchCol('id',[
            'is_del' => 0,
            'fid' => $item_id,
        ]);
        if (empty($itemIdData)) return false;
        $itemFormFieldType = $this->LocalService()->itemFormrecognition->itemFormFieldType($itemIdData);
        if (empty($itemFormFieldType)) return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, '暂无数据');

        $itemId = array_filter(array_unique(array_column($itemFormFieldType,'item_id')))?:[];
        $formId = array_filter(array_unique(array_column($itemFormFieldType,'form_id')))?:[];
        $itemFormFieldWhere = [
            'where'=> [
                'is_del' => 0,
                'item_id' => StringHelper::toArray($itemId),
                'form_id' => StringHelper::toArray($formId),
                new Operator('type', Operator::OP_NE, FormField::FORM_FIELD_TYPE_UPLOAD_SHARE_IMAGE)
            ],
            'columns'=>['form_field_id'=>'id','name','form_id','item_id','pid'=>'parent','info_order'=>'order','english','cut_pre','cut_after'],
        ];
        $itemFormFieldData = $this->LocalService()->itemFormField->fetchAll($itemFormFieldWhere)?:[];
        if (empty($itemFormFieldData)) return false;
        foreach ($itemFormFieldData as $itemFormFieldDataKey=>&$itemFormFieldDataVal){
            $itemFormFieldDataVal['itemsig_id'] = $itemsig_id;
            $resultid = $this->LocalService()->itemFormrecognition->save($itemFormFieldDataVal);
            if (!empty($resultid)){
                //日志
                $log_remark = '项目下新增中心-批量新增保存';
                $this->LocalService()->log->saveFileLog($resultid,'itemFormrecognition',$itemFormFieldDataVal,0,$log_remark,'',' ',[]);
            }
        }
        return true;

    }

    /**
     * Notes: 获取指定条件下的数据
     * User: lltyy
     * DateTime: 2024/5/20 10:59
     *
     * @param string $where
     * @param string[] $columns
     * @param string[] $order
     * @param string $key
     * @param int $is_more
     * @return array
     */
    public function fetchDataByKey($where='is_del = 0',$columns=['id'],$order=['id'],$key='id',$is_more=0){
        $datas = [];
        $cond = [
            'where'=>$where,
            'columns'=>$columns,
            'order'=>$order
        ];
        $infoDatas = $this->fetchAll($cond);
        if(!empty($infoDatas)){
            foreach($infoDatas as $infoData){
                $data_key = $infoData[$key];
                if($is_more == 1){
                    $datas[$data_key][] = $infoData;
                }else{
                    $datas[$data_key] = $infoData;
                }
            }
        }
        unset($cond);
        unset($infoDatas);
        return $datas;
    }



}