<?php
namespace App\models\Logistic\Api\Custom\Client;
use App\models\Logistic\Api\Custom\AbstractClient;
use App\models\Logistic\Api\Custom\ClientConfig;
use Pheanstalk\Exception;

class Ftp extends AbstractClient{
    protected $xml;
    protected $client;
    protected $clientConfig;
    protected $filePath;
    public function __construct(ClientConfig $config){
        $this->clientConfig=$config;
    }
    public function get(){

    }
    public function send()
    {
        $client = $this->getClient();
        /*$fileHander = fopen($this->filePath,'r');
        $result = \ftp_fput($client,basename($this->filePath),$fileHander,FTP_ASCII);
        var_dump($result);
        return $result;*/

        $configInfo = $this->clientConfig->getConfig();
        //var_dump($configInfo);

        //本机试过不稳定老是出现发不出去情况换这个试试
        $param = array(
            'host' => $configInfo['host'],
            'user' => $configInfo['username'],
            'password' => $configInfo['password'],
            'port' => $configInfo['port'],
        );
        $remoteFile = $configInfo['path'].'/';

        $remoteFile = $remoteFile.basename($this->filePath);
        $ftpobj =  new \Common_CurlFtp($param);
        if ($ftpobj->upload_file($this->filePath, $remoteFile)) {
            // echo 'success';
            $result = true;
        } else {
            $result = false;
        }
        return $result;
    }
    protected function getClient(){
        if(empty($this->client)){
            $configInfo = $this->clientConfig->getConfig();
            $ftp = \ftp_connect($configInfo['host'],$configInfo['port'],90);
            if(!$ftp){
                throw new Exception('ftp connect error');
            }
            \ftp_login($ftp,$configInfo['username'],$configInfo['password']);
            //\ftp_pasv($ftp,true);
            if($configInfo['path']){
               \ftp_chdir($ftp,$configInfo['path']);
            }
            $this->client=$ftp;
            //var_dump($this->client);
        }
        return $this->client;
    }
    public function setSendInf(...$sendInf)
    {
        $filePath = $sendInf[0];
        $this->xml = $filePath;
        $this->filePath = $sendInf[0];
        return $this;
    }
    public function __destruct()
    {
        if($this->client) {
            \ftp_close($this->client);
        }
    }
}
