<?php
namespace model\pack;
use \model;
use model\collocation;

class attributes extends model
{
	public $table = 'pack_attributes';
    public $key = 'paa_id';

	public function __construct ()
    {
		parent::__construct();
	}

    function getDb(){
	    return $this->db;
	}

    public function saveDetail($params)
    {   
        
        $fileinfo = json_decode($params['paa_imgs'],true);
		if($fileinfo){
			$paa_imgs  = array_column($fileinfo,'fileid');
		}
        $data = [
            'paa_attcat'=>$params['paa_attcat']??0,
            'paa_pat_id'=>$params['paa_pat_id']??0,
            'paa_opuser'=>getOpuser(),
            'paa_update_time'=>getNowTime(),
            'paa_imgs'=>json_encode($paa_imgs??[]),
        ];
        $data = langGetVals($data,$params,['paa_'=>'paa_']);
        
        if($params['paa_id']){
            $id = $this->db->get('pack_attributes','paa_id',['paa_id'=>$params['paa_id']]);
        } 
		$this->db->Begin();
        if($id){
            $this->db->update('pack_attributes',$data,['paa_id'=>$id]);
        }else{
            $data['paa_create_time'] = getNowTime();
            $this->db->insert('pack_attributes',$data);
            $id = $this->db->id();
        }

		$this->db->End();
		return $id;
    }

    public function getList($params, $rules = [])
	{
		$filters = $params['filters'];
		$page = $params['page'];
		$pagesize = $params['rows'];
		$sidx = empty($params['sidx'])? '': $params['sidx'];
		$sord = empty($params['sord'])? 'asc': $params['sord'];
		$orderby = $params['orderby'];
		$this->joinWhere = [];
	
		$table = 'pack_attributes(paa)';
		$join = [
            '[>]pack_type(pat)'=>['paa.paa_pat_id'=>'pat_id'],
            '[>]adm_user(au)'=>['paa.paa_opuser'=>'au_id']
        ];
		
        $where = $this->filter2medoo($filters,function(&$field,&$op,&$data){
            switch ($field) {
                case 'pat_name':
                    $field = 'pat.pat_'.LG_NAME;
                    break;    
                case 'paa_imgs':
                    $op = 'RAW_'.$field;
                    if($data==1){
                        $data = raw("paa_imgs != '[]' AND JSON_VALID(CAST(paa_imgs AS JSON)) = 1 AND JSON_LENGTH(CAST(paa_imgs AS JSON)) > 0");
                    }else{
                        $data = raw("(paa_imgs = '[]' OR paa_imgs IS NULL OR JSON_VALID(CAST(paa_imgs AS JSON)) = 0 OR JSON_LENGTH(CAST(paa_imgs AS JSON)) = 0)");
                    }
                    break;
            }
        });
		
		if(!empty($params['keys'])) $where['paa_id'] = explode(',', $params['keys']);
		if(!empty($params['paa_id'])) $where['paa_id'] = $params['paa_id'];
		
		if(!empty($this->joinWhere)){
			$where = array_merge($where, $this->joinWhere);
		}
        
        $where = $this->listWhere($where,$page,$pagesize,$sidx,$sord,$orderby);
		if($page>0 && $pagesize>0){
			$fields = '*';
			$pages = $this->paging($table,$join,$fields,$where,$page,$pagesize);
			$where["LIMIT"] = [$pages['limit'],$pagesize];
		}
        
		$fields = ['paa.*','pat_'.LG_NAME.'(pat_name)','au_name'];
        $arr = $this->db->select($table,$join,$fields,$where);
        if($arr)
        {   
            $fileIds = array_filter(array_column($arr, 'paa_imgs'));
			$fileInfoArr = [];
			
			if (!empty($fileIds)) {
				// 展开所有JSON格式的文件ID数组
				$allFileIds = [];
				foreach ($fileIds as $fileIdJson) {
					$ids = json_decode($fileIdJson, true);
					if (is_array($ids) && !empty($ids)) {
						$allFileIds = array_merge($allFileIds, $ids);
					}
				}
				$allFileIds = array_unique($allFileIds);
				
				if (!empty($allFileIds)) {
					// 一次性获取所有文件信息
					$files = $this->db->select('files', 
						['fileid', 'filename', 'fileextname', 'filetype'], 
						['fileid' => $allFileIds]
					);
					$fileInfoArr = array_column($files, null, 'fileid');
				}
			}
            
            $collArr = $this->db->select('object', ['o_parent_id', 'o_id', LG_NAME], ['o_parent_id'=>1169]);
            $collArr = array_column($collArr, LG_NAME, 'o_id');
            
            foreach($arr as &$v){

                $fileinfo = [];
				if (!empty($v['paa_imgs'])) {
					$fileIds = json_decode($v['paa_imgs'], true);
					if (is_array($fileIds) && !empty($fileIds)) {
						foreach ($fileIds as $fileId) {
							if (isset($fileInfoArr[$fileId])) {
								$fileinfo[] = $fileInfoArr[$fileId];
							}
						}
					}
				}
                $v['captions']['paa_attcat'] = $collArr[$v['paa_attcat']]??'';
                $v['captions']['paa_opuser'] = $v['au_name']?:'';
                $v['captions']['paa_imgs'] = $fileinfo;
				$v['captions']['paa_pat_id'] = $v['pat_name']?:'';
            }
        }
		
		$data = [
			'page'=> $page,
			'total'=> $pages['total'],
			'records' => $pages['records'],
			'rows' => $arr
		];
		return $data;
	}

    public function delData($idArr)
    {
        if(!empty($idArr)){

			$join = [
				'[><]pack_material(pam)'=>['pma.pma_pam_id'=>'pam_id'],
				'[><]pack_attributes(paa)'=>['pma.pma_paa_id'=>'paa_id']
			];
			$exits = $this->db->select('pack_material_attributes(pma)',$join,'paa_cn_name',['pma_paa_id'=>$idArr,'GROUP'=>'paa_id']);
			if($exits){
				$exitsstr = implode(',',$exits);
                exitJson("包装物料属性已引用数据：{$exitsstr}，请先处理");
            }


			$this->db->Begin();

			$this->db->delete('pack_attributes', ['paa_id'=>$idArr]);
			
			$this->db->End();
		}
		return [];
    }


    public function getDetail($id)
    {
        $arr = [];
        $table = 'pack_attributes(paa)';
		$join = [
            '[>]pack_type(pat)'=>['paa.paa_pat_id'=>'pat_id'],
            '[>]object(o)'=>['paa.paa_attcat'=>'o_id'],
        ];
        $fields = ['paa.*','pat_'.LG_NAME.'(pat_name)',LG_NAME.'(o_name)'];

        $arr = $this->db->get($table,$join,$fields,['paa_id'=>$id]);
        if($arr){
            $arr['captions']['paa_attcat'] = $arr['o_name'];

            $fileids = json_decode($arr['paa_imgs'],true);
           
			if($arr['paa_imgs'] && $fileids){
				
				$filesArr = $this->db->select('files','*',['fileid'=>$fileids]);
				foreach ($filesArr as $val) {
					$arr['paa_imgsinfo'][] = [
						'fileid'=>$val['fileid'],
						'filename'=>$val['filename'],
						'orgname' => $val['fileremark'].'.'.$val['fileextname']
					];
				}
			}
        }

        return $arr;
    }

	public function getAllAttributes()
    {
        $arr = [];
        $table = 'pack_type(pat)';
        $join = [];
        $specArr = $this->db->select($table,$join,'pat_spec',['pat_spec[~]'=>'@A']);
        foreach ($specArr as $key => $val) {
            if(!$val) continue;
            $vArr = explode('@',$val);
            foreach ($vArr as $vv) {
                if(strpos($vv,'A')===0 && $vv){
                    $oidArr[] = substr($vv,1);
                }
            }
        }

        $fields = ['o.'.LG_NAME.'(o_name)','o.o_id'];
        $where = ['ORDER'=>['o.o_sort'=>'ASC'],'GROUP'=>'o.o_id','o_id'=>$oidArr];
        $result = $this->db->select('object(o)',$fields,$where);
 
        foreach ($result as $key => $val) {
            $arr[] = [
                'field'=>'attcat'.$val['o_id'],
                'o_name'=>$val['o_name'],
                'o_id'=>$val['o_id']
            ];
        }
        return $arr;
    }
}