<?php

namespace model\pro;


use model\file;
//use phpDocumentor\GraphViz\Exception;
use servers\image\image;

class pic extends \model
{
    /**
     * @var string
     */
    private $table = 'pro_pic';

    /**
     * 设置为主图
     * @var string[]
     */
    private $master = ['init','beautify'];

    /**
     * @var null
     */
    private $data = null;

    /**
     * @var null
     */
    private $typeData = null;

    /**
     * @var array
     */
    private $join;

    /**
     * @param $pId
     * @param $type
     * @return array|false
     */
    public function list($pId,$type)
    {
        $list = $this->db->select($this->table,['[><]files' => ['ppic_fileid' => 'fileid']],'*',['ppic_p_id' => $pId,'ppic_type' => $type]);

        return $list;
    }

    public function pictureSynthesis($where='',$page=0,$pagesize=0,$sidx='',$sord='asc',$orderby=''){

        $this->join = [];
        $where = $this->filter2medoo($where,function(&$field,&$op,&$data){
            switch($field){
                case 'init':
                case 'beautify':
                case 'tecdoc':
                case 'catalog_g':
                case 'catalog_gsp':
                case 'usa':
                case 'attach':
                case 'notcattle':
                case '360':
                case 'other':
                    $tmp = $field;
                    $field = 'ppic_type';
                    $op = $data == 1 ? 'eq' : 'not';
                    $data = [$tmp];
                    break;
                case 'init_examine':
                    if($data=='1'){
                        $op = 'sql';
                        $data = " ppic_fileid in (select ppic_fileid from pro_pic where ppic_type='init' and ppic_state=1)";
                    }else{
                        $op = 'sql';
                        $data = " ppic_fileid not in (select ppic_fileid from pro_pic where ppic_type='init' and ppic_state=1)";
                    }
                    break;
                case 'beautify_examine':
                    if($data=='1'){
                        $op = 'sql';
                        $data = " ppic_fileid in (select ppic_fileid from pro_pic where ppic_type='beautify' and ppic_state=1)";
                    }else{
                        $op = 'sql';
                        $data = " ppic_fileid not in (select ppic_fileid from pro_pic where ppic_type='beautify' and ppic_state=1)";
                    }
                    break;
                case 'create_time':
                case 'update_time':
                    $data = trim($data);
                    $field = 'pro_pic.'.$field;
                    break;
            }
        });
        switch($sidx){
            case 'create_time':
            case 'update_time':
                $sidx = 'pro_pic.'.$sidx;
                break;
            case 'init':
            case 'init_examine':
            case 'beautify':
            case 'beautify_examine':
            case 'attach':
            case 'notcattle':
            case '360':
            case 'other':
            case 'tecdoc':
            case 'catalog_gsp':
            case 'catalog_g':
                $sidx = '';
                break;
        }
        $where = $this->listWhere($where,$page,$pagesize,$sidx,$sord,$orderby);

        $this->join = [
            '[><]pro' => ['ppic_p_id' => 'p_id']
        ];
       $fields = '*';
        if($page>0 && $pagesize>0){
            if(empty($this->join)){
                $pages = $this->paging($this->table,$where,$page,$pagesize);
            }else{
                $pages = $this->paging($this->table,$this->join,$fields,$where,$page,$pagesize);
            }
            $where["LIMIT"] = [$pages['limit'],$pagesize];
        }
        //dd($this->db->last(),$where);

        $fields = ['p_innum','p_id','p_outnum','p_cate'];
        $where['GROUP'] = ['ppic_p_id'];
        if(empty($this->join)){
            $rows = $this->db->select($this->table,$fields,$where);
        }else{
            $rows = $this->db->select($this->table,$this->join,$fields,$where);
        }

        if(!empty($rows)){
            $typeList = [
                'init',
                'init_examine',
                'beautify',
                'beautify_examine',
                'tecdoc',
                'catalog_g',
                'catalog_gsp',
                'usa',
                'attach',
                'notcattle',
                '360',
                'other',
                'create_time',
                'update_time'
            ];
            $pIds = array_column($rows,'p_id');
            foreach ($rows as &$value)
            {
                foreach ($typeList as $type)
                {
                    $value[$type] = $this->getIsImage($pIds,$value['p_id'],$type);
                }
            }
            unset($pIds);
        }
        $data = [
            'page'=> $page,
            'total'=> $pages['total'],
            'records' => $pages['records'],
            'rows' => $rows
        ];
        return $data;
    }

    private function checkDataTime($date)
    {
        if(date('Y-m-d H:i:s',strtotime($date)) == $date){
            return true;
        }else{
            return false;
        }
    }
    /**
     * @param $pIds
     * @param $pId
     * @param $type
     * @return int|mixed
     */
    private function getIsImage($pIds,$pId,$type)
    {
        if(is_null($this->data)){
            $data = $this->db->select($this->table,['ppic_state','ppic_p_id','ppic_type','create_time','update_time'],['ppic_p_id' => $pIds]);
            if(!empty($data)){
                foreach ($data as $value)
                {
                    $this->data[$value['ppic_p_id']][] = $value;
                }
            }else{
                $this->data = [];
            }
            unset($data);
        }
        if(isset($this->data[$pId])){
            $rows = $this->data[$pId];
            switch ($type){
                case 'usa':
                case 'attach':
                case 'notcattle':
                case '360':
                case 'other':
                case 'catalog_gsp':
                case 'catalog_g':
                case 'tecdoc':
                case 'beautify':
                case 'init':
                    $tmp = array_column($rows,'ppic_type');
                    if(in_array($type,$tmp)){
                        return 1;
                    }
                    return 0;
                    break;
                case 'init_examine':
                case 'beautify_examine':
                    $type = str_replace('_examine','',$type);
                    foreach ($rows as $v){
                        if($v['ppic_type'] == $type && $v['ppic_state'] == 1){
                            return 1;
                        }
                    }
                    return 0;
                    break;
                case 'create_time':
                    return date('Y-m-d',strtotime(min(array_column($rows,'create_time'))));
                    break;
                case 'update_time':
                     return date('Y-m-d',strtotime(max(array_column($rows,'update_time'))));
                    break;
            }

        }else{
            return 0;
        }
    }

    /**
     * @param $data
     * @param $config
     * @return false|\PDOStatement
     * @throws Exception
     */
    public function save($data,$config)
    {
        if(isset($data['param']) && !empty($data['param']))
        {
            $data['param'] = json_decode($data['param'],true);
        }
        $tmp = [
            'ppic_fileid' => $data['file_id'],
            'ppic_p_id' => $data['param']['p_id'],
            'ppic_type' => $data['param']['ppic_type'],
            'ppic_state' => in_array($data['param']['ppic_type'],$this->master) ? 0 : 1,
            'opuser' => $this->getOpuser(),
            'create_time' => $this->getDateTime(),
            'update_time' => $this->getDateTime(),
        ];
        $result = $this->db->insert($this->table,$tmp);
        //两个类型需要生成主图
        if(in_array($tmp['ppic_type'],$this->master))
        {
            //判断它是否需要生成了主图
            $where['ppic_p_id'] = $tmp['ppic_p_id'];
            $where['ppic_type'] = $tmp['ppic_type'] == 'init' ? $this->master : $tmp['ppic_type'];
            $count = $this->db->count($this->table,'ppic_fileid',$where);
            if($count == 1) $this->setMasterPicture($tmp['ppic_p_id'],$tmp['ppic_fileid']);
        }
        return $result;
    }

    /**
     * 设为主图
     * @param $pId
     * @param $fileId
     * @return bool
     * @throws Exception
     */
    public function setMasterPicture($pId,$fileId)
    {
        //首先删除原有的主图
        $list = $this->db->select($this->table,['[><]files' => ['ppic_fileid' => 'fileid']],'*',['ppic_p_id' => $pId,'ppic_type' => ['tecdoc','catalog_g','catalog_gsp','usa']]);
        $file = new file();
        if(!empty($list)){
            $fileIds = array_column($list,'fileid');
            if($fileIds){
                $file->delete($fileIds);
                $this->db->delete($this->table,['ppic_fileid' => $fileIds,'ppic_p_id' =>$pId]);
            }
        }
        if (empty($fileId)){
            return false;
        }
        $dir = $file->getDir();
        $dirName = $dir.$file->getDirNameByFileId($fileId);

        $pathInfo = pathinfo($dirName);

        $configs = $this->getImageConfig();

        $image = new image();
		$this->db->Begin();
        $pic = [
            'ppic_p_id' => $pId,
            'ppic_state' => 1,
            'opuser' => $this->getOpuser(),
            'create_time' => $this->getDateTime(),
            'update_time' => $this->getDateTime(),
        ];
        foreach ($configs as $type => $config)
        {
            $dest = $dir.DIRECTORY_SEPARATOR.'pro'.DIRECTORY_SEPARATOR.$type.DIRECTORY_SEPARATOR.($pId % 100).DIRECTORY_SEPARATOR;
            mkdirs($dest);
            $dest .= $pId.'.'.$pathInfo['extension'];
            $image->resize($dirName,$dest,$config['width'],$config['height']);
            if($config['watermark']){
                $image->watermark($dest,$dest,$config['watermark']);
            }
            $id = $file->add(str_replace($dir,'',$dest),'','image');
            if($type == 'g' || $type == 'gsp'){
                $type = 'catalog_'.$type;
            }
            $pic['ppic_fileid'] = $id;
            $pic['ppic_type'] = $type;
            $this->db->insert($this->table,$pic);
        }
        (new pro())->setValue($pId,'p_pic',$fileId);
		$this->db->End();
		$iocrm = new \model\iocrm();
		$iocrm->crmAddProApi($pId, 'U');
        return true;
    }

    /**
     * 审核接口
     * @param $pId
     * @param $fileId
     * @param $state
     * @return false|\PDOStatement
     */
    public function examine($pId,$fileId,$state)
    {
        return $this->db->update($this->table,[
            'ppic_state' => $state,
            'check_user' => $this->getOpuser(),
            'check_time' => $this->getDateTime()
        ],[
            'ppic_p_id' => $pId,
            'ppic_fileid' => $fileId
        ]
        );
    }

    /**
     * 删除产品图片
     * @param $ids
     * @param $pId
     * @return false|\PDOStatement
     */
    public function deleteRow($ids,$pId)
    {
        if(empty($pId) || empty($ids)) 
            return false;
        $file = new file();
        $file->delete($pId,$ids);
        $pro = new pro();
        $proFileId = $pro->getRowByKey($pId);
        $result = $this->db->delete($this->table,['ppic_p_id' => $pId,'ppic_fileid' => $ids]);
        if(in_array($proFileId['p_pic'],$ids)){
            //删除主图时重新设置主图
            $where = array(
                'ppic_type' => $this->master,
                'ppic_fileid[!]' => $proFileId['p_pic'],
                'ppic_p_id' => $pId,
                'ORDER' => ['ppic_type' => 'DESC','ppic_fileid' => 'DESC']
            );
            $fileId = $this->db->get($this->table,'ppic_fileid',$where);
            if(!$fileId){
                (new pro())->setValue($pId,'p_pic',0);
            }
            $this->setMasterPicture($pId,$fileId);
        }
        return $result;
    }

    /**
     * 获取图片配置
     * @return mixed
     * @throws Exception
     */
    private function getImageConfig()
    {
        if(!isset(\mvc::$cfg['siteCustom']['pro']['pic'])){
            throw new \Exception(lg('图片未配置'));
        }
        return \mvc::$cfg['siteCustom']['pro']['pic'];
    }
}