<?php
namespace model;
use \model;
use servers\image\image;

/**
 * Class element
 * @package model
 */
class file extends model
{
    public $table = 'files';

    public $key = 'fileid';

    public function list($pId)
    {
        return $this->db->select('pro_pic',['[><]files' => ['ppic_fileid' => 'fileid']],'*',['ppic_p_id' => $pId]);
    }

    public function add($fileName,$fileRemark,$fileType)
    {
        $data = [
            'filename' => $fileName,
            'fileremark' => $fileRemark,
            'filetype' => $fileType
        ];
        $this->db->insert($this->table,$data);
        $id = $this->db->id();
        if($id <= 0)
        {
            $id = $this->db->get($this->table,'fileid',['ORDER' => ['fileid' => 'DESC']]);
        }
        return $id;
    }

    public function adds($data,$method,$pId)
    {
        $dirName = $data['dir_name'];
        $dir = $data['dir'];
        $pId = explode("-",$pId);
        unset($data['dir_name'],$data['dir']);
        $result = $this->db->insert($this->table,$data);
        if($result === false){
            return $result;
        }
        $id = $this->db->id();
        $pic = [
            'ppic_p_id' => $pId['1'],
            'ppic_fileid' => $id,
            'ppic_state' => in_array($pId['0'],['init','beautify']) ? 0 : 1,
            'ppic_type' => $pId['0'],
            'opuser' => $this->getOpuser(),
            'create_time' => $this->getDateTime(),
            'update_time' => $this->getDateTime(),
        ];
        $this->$method($pic);
        if($pic['ppic_type'] == 'init' || $pic['ppic_type'] == 'beautify')
        {
            //先根据产品ID判断
            $fileid = $this->db->get('pro_pic','ppic_fileid',['ppic_type' => $pic['ppic_type'],'ppic_p_id' => $pId['1']]);
            if($fileid > 0){
                $this->setMaster([
                    'id' => $pId['1'],
                    'image' => $fileid,
                ]);
            }
        }
        return true;
    }

    public function proPic($data)
    {
        $this->db->insert('pro_pic',$data);
        return true;
    }

    public function setMaster($param)
    {
        //首先删除原有的主图
        $list = $this->db->select('pro_pic',['[><]files' => ['ppic_fileid' => 'fileid']],'*',['ppic_p_id' => $param['id'],'ppic_type' => ['tecdoc','catalog_g','catalog_gsp','usa']]);
        $dir = $this->getDir();
        foreach ($list as $file){
            if(file_exists($dir.$file['filename'])){
                unlink($dir.$file['filename']);
            }
        }
        $fileIds = array_column($list,'fileid');
        if($fileIds){
            $this->db->delete('pro_pic',['ppic_fileid' => $fileIds,'ppic_p_id' => $param['id']]);
            $this->db->delete('files',['fileid' => $fileIds]);
        }

        //重新生成新的图片
        $dirName = $this->db->get('files','filename',['fileid' => $param['image']]);
        $dirName = $dir.$dirName;
        $pathInfo = pathinfo($dirName);
        $configs = $this->getImageConfig();
        $image = new image();
        $pic = [
            'ppic_p_id' => $param['id'],
            'ppic_state' => 0,
            'opuser' => $this->getOpuser(),
            'create_time' => $this->getDateTime(),
            'update_time' => $this->getDateTime(),
        ];
        foreach ($configs as $type => $config)
        {
            $dest = $pathInfo['dirname'].DIRECTORY_SEPARATOR.$type.'_'.$param['id'].'.'.$pathInfo['extension'];
            $image->resize($dirName,$dest,$config['width'],$config['height']);
            if($config['watermark']){
                $image->watermark($dest,$dest,$config['watermark']);
            }
            $this->db->insert($this->table,[
                'filename' => str_replace($dir,'',$dest),
                'filetype' => 'image'
            ]);
            if($type == 'g' || $type == 'gsp'){
                $type = 'catalog_'.$type;
            }
            $id = $this->db->id();
            $pic['ppic_fileid'] = $id;
            $pic['ppic_type'] = $type;
            $this->proPic($pic);
        }
        return true;
    }

    public function getDir()
    {
        return \mvc::$cfg['dir']['files'];
    }

    public function getImageConfig()
    {
        return \mvc::$cfg['siteCustom']['pro']['pic'];
    }

    /**
     * 删除产品图片
     * @param $pId
     * @param $fileIds
     * @param $type
     * @return bool|int
     */
    public function deleteRow($pId,$fileIds)
    {
        return $this->db->delete('pro_pic',['ppic_p_id' => $pId,'ppic_fileid' => $fileIds]);
    }


    /**
     * @param $fileids
     * @return bool
     */
    public function delete($fileids)
    {
        $fileNameList = $this->db->select($this->table,'filename',['fileid' => $fileids]);
        $result = $this->db->delete($this->table,['fileid' => $fileids]);
        $dir = $this->getDir();
        if($result !== false)
        {
            if(!empty($fileNameList))
            {
                foreach ($fileNameList as $file)
                {
                    if(file_exists($dir.$file))
                    {
                        unlink($dir.$file);
                    }
                }
            }
        }else{
            return false;
        }
        return true;
    }

    /**
     * @param $fileId
     * @return false|mixed
     */
    public function getDirNameByFileId($fileId)
    {
        return $this->db->get($this->table,'filename',['fileid' => $fileId]);
    }
}
