<?php
use DHL\Entity\GB\ShipmentResponse;
use DHL\Entity\GB\ShipmentRequest;
use DHL\Client\Web as WebserviceClient;
use DHL\Datatype\GB\Piece;
use DHL\Datatype\GB\SpecialService;

class Default_Index2Controller extends Ec_Controller_DefaultAction
{
    public $_loginSuccessUrl = '/';
    public $_authCode = 0; //是否用验证码

    public function preDispatch()
    {
        $this->view->authCode = $this->_authCode;
        $this->view->errMsg = '';
        $this->tplDirectory = "default/views/default/";
    }

    public function testAction(){
        echo 'sss';
        $str = "SAINT JOHN'S";
        echo addslashes($str);

        exit;
        Service_CityPost::doProcessAll();
        exit;
    }

    public function testdhlAction(){
        //echo 'ssssssss';

        //require_once("");
        //echo __DIR__;
        //echo APPLICATION_PATH;
        /*echo sys_get_temp_dir();
        exit;*/

        // You may use your own init script, as long as it takes care of autoloading
        require(APPLICATION_PATH .'/../libs/DHL-API-master/DHL-API-master'. '/init.php');

        // DHL settings
        $dhl = $config['dhl'];
        //print_r($dhl);exit;

        // Test a ShipmentRequest using DHL XML API
        $sample = new ShipmentRequest();

        // Assuming there is a config array variable with id and pass to DHL XML Service
        $sample->SiteID = $dhl['id'];
        $sample->Password = $dhl['pass'];

        // Set values of the request
        $sample->MessageTime = '2001-12-17T09:30:47-05:00';
        $sample->MessageReference = '1234567890123456789012345678901';
        $sample->RegionCode = 'AM';
        $sample->RequestedPickupTime = 'Y';
        $sample->NewShipper = 'Y';
        $sample->LanguageCode = 'en';
        $sample->PiecesEnabled = 'Y';
        $sample->Billing->ShipperAccountNumber = $dhl['shipperAccountNumber'];
        $sample->Billing->ShippingPaymentType = 'S';
        $sample->Billing->BillingAccountNumber = $dhl['billingAccountNumber'];
        $sample->Billing->DutyPaymentType = 'S';
        $sample->Billing->DutyAccountNumber = $dhl['dutyAccountNumber'];
        $sample->Consignee->CompanyName = 'Ssense';
        $sample->Consignee->addAddressLine('333 Chabanel West, #900');
        $sample->Consignee->City = 'Montreal';
        $sample->Consignee->PostalCode = 'H3E1G6';
        $sample->Consignee->CountryCode = 'CA';
        $sample->Consignee->CountryName = 'Canada';
        $sample->Consignee->Contact->PersonName = 'Bashar Al-Fallouji';
        $sample->Consignee->Contact->PhoneNumber = '0435 336 653';
        $sample->Consignee->Contact->PhoneExtension = '123';
        $sample->Consignee->Contact->FaxNumber = '506-851-7403';
        $sample->Consignee->Contact->Telex = '506-851-7121';
        $sample->Consignee->Contact->Email = 'bashar@alfallouji.com';
        $sample->Commodity->CommodityCode = 'cc';
        $sample->Commodity->CommodityName = 'cn';
        $sample->Dutiable->DeclaredValue = '200.00';
        $sample->Dutiable->DeclaredCurrency = 'USD';
        $sample->Dutiable->ScheduleB = '3002905110';
        $sample->Dutiable->ExportLicense = 'D123456';
        $sample->Dutiable->ShipperEIN = '112233445566';
        $sample->Dutiable->ShipperIDType = 'S';
        $sample->Dutiable->ImportLicense = 'ALFAL';
        $sample->Dutiable->ConsigneeEIN = 'ConEIN2123';
        $sample->Dutiable->TermsOfTrade = 'DTP';
        $sample->Reference->ReferenceID = 'AM international shipment';
        $sample->Reference->ReferenceType = 'St';
        $sample->ShipmentDetails->NumberOfPieces = 2;

        $piece = new Piece();
        $piece->PieceID = '1';
        $piece->PackageType = 'EE';
        $piece->Weight = '5.0';
        $piece->DimWeight = '600.0';
        $piece->Width = '50';
        $piece->Height = '100';
        $piece->Depth = '150';
        $sample->ShipmentDetails->addPiece($piece);

        $piece = new Piece();
        $piece->PieceID = '2';
        $piece->PackageType = 'EE';
        $piece->Weight = '5.0';
        $piece->DimWeight = '600.0';
        $piece->Width = '50';
        $piece->Height = '100';
        $piece->Depth = '150';
        $sample->ShipmentDetails->addPiece($piece);

        $sample->ShipmentDetails->Weight = '10.0';
        $sample->ShipmentDetails->WeightUnit = 'L';
        $sample->ShipmentDetails->GlobalProductCode = 'P';
        $sample->ShipmentDetails->LocalProductCode = 'P';
        $sample->ShipmentDetails->Date = date('Y-m-d');
        $sample->ShipmentDetails->Contents = 'AM international shipment contents';
        $sample->ShipmentDetails->DoorTo = 'DD';
        $sample->ShipmentDetails->DimensionUnit = 'I';
        $sample->ShipmentDetails->InsuredAmount = '1200.00';
        $sample->ShipmentDetails->PackageType = 'EE';
        $sample->ShipmentDetails->IsDutiable = 'Y';
        $sample->ShipmentDetails->CurrencyCode = 'USD';
        $sample->Shipper->ShipperID = '751008818';
        $sample->Shipper->CompanyName = 'IBM Corporation';
        $sample->Shipper->RegisteredAccount = '751008818';
        $sample->Shipper->addAddressLine('1 New Orchard Road');
        $sample->Shipper->addAddressLine('Armonk');
        $sample->Shipper->City = 'New York';
        $sample->Shipper->Division = 'ny';
        $sample->Shipper->DivisionCode = 'ny';
        $sample->Shipper->PostalCode = '10504';
        $sample->Shipper->CountryCode = 'US';
        $sample->Shipper->CountryName = 'United States Of America';
        $sample->Shipper->Contact->PersonName = 'Mr peter';
        $sample->Shipper->Contact->PhoneNumber = '1 905 8613402';
        $sample->Shipper->Contact->PhoneExtension = '3403';
        $sample->Shipper->Contact->FaxNumber = '1 905 8613411';
        $sample->Shipper->Contact->Telex = '1245';
        $sample->Shipper->Contact->Email = 'test@email.com';

        $specialService = new SpecialService();
        $specialService->SpecialServiceType = 'A';
        $sample->addSpecialService($specialService);

        $specialService = new SpecialService();
        $specialService->SpecialServiceType = 'I';
        $sample->addSpecialService($specialService);

        $sample->EProcShip = 'N';
        $sample->LabelImageFormat = 'PDF';

        // Call DHL XML API
        $start = microtime(true);

        // Display the XML that will be sent to DHL
        echo $sample->toXML();
        exit;

        // DHL webservice client using the staging environment
        $client = new WebserviceClient('staging');

        // Call the DHL service and display the XML result
        echo $client->call($sample);
        echo PHP_EOL . 'Executed in ' . (microtime(true) - $start) . ' seconds.' . PHP_EOL;

    }

    public function indexAction()
    {
		phpinfo();
    }

    public function curlAction(){
        $this->apiurl = 'https://www.baidu.com/';
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $this->apiurl); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer

        //curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        /*if ($postData != ''){
            curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); // Post提交的数据包
        }*/
        //curl_setopt($curl, CURLOPT_POSTFIELDS, "postfield=".urlencode($jwtStr));
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        $tmpInfo = curl_exec($curl); // 执行操作
        var_dump($curl);
        //var_dump($tmpInfo);
        var_dump('sss');
        curl_close($curl); // 关闭CURL会话
    }


    public function loginAction()
    {
        $errMsg = '';
        if ($this->_request->isPost()) {
            setcookie('currentPage','',-1,'/');
            $param['userName'] = $this->_request->getParam('userName', '');
            $param['userPass'] = $this->_request->getParam('userPass', '');
            $param['authCode'] = $this->_request->getParam('authCode', '');
            $param['valid'] = $this->_authCode;
            $result = Service_User::login($param);
            if (isset($result['state']) && $result['state'] == '1') {
                $this->_redirect($this->_loginSuccessUrl);
            } else {
                $errMsg = isset($result['message']) ? $result['message'] : '';
            }
        }
        $this->view->errMsg = $errMsg;
        echo $this->view->render($this->tplDirectory . 'login.tpl');
    }

    public function logoutAction()
    {
        $session = new Zend_Session_Namespace('userAuthorization');
        $session->unsetAll();
        session_destroy();
        $errMsg = '';
		setcookie('currentPage','',-1,'/');
        $this->view->errMsg = $errMsg;
        echo $this->view->render($this->tplDirectory . 'login.tpl');
    }

	/**
	 * @todo code128
	 */
    public function barcodeAction()
    {
    	$drawText = $this->_request->getParam('drawText','1');
        Common_Barcode::barcode($this->_request->code,'code128',$drawText);
        exit;
    }
    public function barcode39Action()
    {
    	Common_Barcode::barcode($this->_request->code,'code39');
    	exit;
    }
    public function verifyCodeAction()
    {
        $verifyCode = new Common_Verifycode();
        $verifyCode->set_sess_name('AdminVerifyCode');
        echo $verifyCode->render();
    }

    public function printBarcodeAction(){
        $condition = array(
            'barcode'=>$this->_request->getParam('barcode',""),
            "type"=>$this->_request->getParam('type',""),
            "height"=>$this->_request->getParam('height',""),
            "width"=>$this->_request->getParam('width',""),
            "quality"=>$this->_request->getParam('quality',""),
            "format"=>$this->_request->getParam('format',""),
            "text"=>$this->_request->getParam('text',"")
        );
        Common_Barcode::outImage($condition);
    }
    /**
     * @author william-fan
     * @todo 签名
     */
    public function signatureAction(){
    	/* echo APPLICATION_PATH;
    	exit; */
    	$ttfPath = APPLICATION_PATH.'/../data/font/english111 .ttf';
    	$name = $this->_request->getParam('name','');
    	Header("Content-type: image/gif");
    	$im = imagecreate(150,20);
    	$black = ImageColorAllocate($im, 255,255,255);
    	$white = ImageColorAllocate($im, 0,0,0);
    	imagettftext($im, 20, 0, 10, 20, $white, $ttfPath, $name);
    	ImageGif($im);
    	ImageDestroy($im);
    }

    public function printOrderAction() {
        $code= trim($this->_request->getParam('code',''));
        $result=Service_PackProcess::getOrderInfo($code);
        /* echo "<pre>";
        print_r($result);
        echo "</pre>";*/
        if($result['state']!='1'){
            die($result['message']);
        }
        $this->view->data=$result['data'];
        $smCode=$result['data']['order']['sm_code'];
        $codetype = $this->_request->getParam('codeType','code128');
        $byurl = $this->_request->getParam('byurl','0'); //默认自动打印
        if($codetype=='code39'){
        	$action = 'barcode39';
        }elseif ($codetype=='code128'){
        	$action = 'barcode';
        }else{
        	$action = 'barcode';
        }
        //print_r($smCode);
        if(strlen($smCode)>2){
        	switch(strtoupper($smCode)){
        		case "HKEMS":
        		case "SWPR":
        		case "SWPT":	
        			$smCode='sw';
        			break;
        		case "CJ-DGMG":
                    //德国邮政小包挂号
                    $smCode = 'dem-p';
        			break;
                case "CJ-DGMP":
                    //德国邮政小包平邮
                    $smCode = 'dem';
                    break;
                case "SZY-EMS":
                	$smCode = 'SZY-EMS';
                	break;
                case "BH-SGG":
                case "BH-SGP":
                	$smCode = 'sg';	
                	break;
                case 'BH-MPPG':
                  $smCode = 'bh-mppg';
                  break;
        		default:
        			$smCode='F4';
        	}
            /*if(strtoupper($smCode)=='HKEMS'||strtoupper($smCode)=='SWPR'||strtoupper($smCode)=='SWPT'){
            	$smCode='sw';
            }else{
            	$smCode='F4';
            }*/
        }
        //$smCode = 'dem';
        //$smCode = 'dem-p';
        //echo $smCode;
        $this->view->action = $action;
        $this->view->byurl = $byurl;
        echo Ec::renderTpl("shipment/views/template/".$smCode.".tpl", 'layout');
    }

    /**
     * @desc 打印货架条码
     */
    public function printShelfAction()
    {
        $orderlist = isset($_POST['orderlist']) ? $_POST['orderlist'] : '';
        if (!$orderlist) {
            echo '<html><head><meta http-equiv="content-type" content="text/html;charset=utf-8"></head><body>';
            echo '注：将单号复制到输入框中，每个单号以换行区分；<br>格式：A4 * 5<form action="" method="post">
                <textarea rows="36" cols="70" name="orderlist"></textarea>
                <input type="submit" name="submit" value="submit">
            </form>';
            echo '</body></html>';
        } else {
            $orderlist = $_POST['orderlist'];
            $orderlist = preg_split('/\r\n/', $orderlist, -1, PREG_SPLIT_NO_EMPTY);
           // print_r($orderlist);die;
            $result = array_chunk($orderlist, 2);
            $this->view->results = $result;
            echo $this->view->render($this->tplDirectory . 'print_thermal_9X8.5x2.tpl');
        }
    }
	

	/*客人LOGO*/
    public function viewLogoImageAction(){        
		$customerCode = $this->_request->getParam('customerCode', "");
		if(empty($customerCode)){ exit;}
		$customer_array = Service_Customer::getByField($customerCode, 'customer_code');
		$fileName = $customer_array['customer_logo'];
        $path = APPLICATION_PATH . "/../data/images/register/" .$customerCode.'/'. $fileName;
   //echo $path;exit;
        if (file_exists($path)) {
            header('Content-Type: image/jpeg');
            echo file_get_contents($path);
    
        } else {
            //header("Location: /images/noimg.jpg");
        }
    
        exit();
    } 				

    /* 上传图片查看 */
    public function viewUploadImageAction ()
    {
        $fileName = $this->_request->getParam('fileName', "");
		$customerCode = $this->_request->getParam('customerCode', "");
        $path = APPLICATION_PATH . "/../data/images/register/" .$customerCode.'/'. $fileName;
    	
        if (file_exists($path)) {
            header('Content-Type: image/jpeg');
            echo file_get_contents($path);
    
        } else {
            header("Location: /images/noimg.jpg");
        }
    
        exit();
    }
    /**
     * @author william-fan
     * @todo 用于获取hkdhl打印的文档
     */
    public function printAction() {
    	$path = $this->_request->getParam('path','');
    	//$filename="E:/wamp/www/chukouwms/public/images/2143826683/epl2";
    	$decodePath = base64_decode($path);
    	/* echo $decodePath;
    	 exit; */
    	$str = '';
    	if($decodePath=='' || !file_exists($decodePath)){
    		$str = '文件不存在';
    		die($str);
    	}
    
    	/* header('Content-type: application/pdf');
    	 $fname = 'aaa';
    	header('filename='.$fname);
    	//readfile($filename); */
    	$str = file_get_contents($decodePath);
    	//$str = base64_decode($str);
    	//echo $str;
    	if(!empty($str)){
    		echo $str;
    		exit;
    	}else{
    		$str = '打印内容为空';
    		die($str);
    	}
    }

    public function taxRebateImageAction(){
        $trId = $this->_request->getParam("tr_id","");
        //$fileName = $this->_request->getParam('fileName',"");
        //$customerCode = $this->_request->getParam('customerCode', "");
        $trRow = Service_TaxRebate::getByField($trId,'tr_id',"*");
        $path = APPLICATION_PATH.'/../data/images/taxrebate/'.$trRow['customer_code']."/".$trRow['filename'] ;
        if(empty($trRow)||$trRow['filename']==""){
            header("Location: /images/noimg.jpg");
            exit();
        }
        if (file_exists($path)) {
            header('Content-Type: image/jpeg');
            echo file_get_contents($path);

        } else {
            header("Location: /images/noimg.jpg");
        }
        exit();
    }

    public function downloadTaxImageAction(){
        $trId = $this->_request->getParam("tr_id","");
        $trRow = Service_TaxRebate::getByField($trId,'tr_id',"*");
        //方法2
        $fullPath = APPLICATION_PATH.'/../data/images/taxrebate/'.$trRow['customer_code']."/".$trRow['filename'] ;

        if(empty($trRow)||$trRow['filename']==""){
            header('Content-Type: image/jpeg');
            header("Location: /images/noimg.jpg");
            //header($header );
            exit;
        }
        if(!file_exists($fullPath)){
            $noimageFile = APPLICATION_PATH.'/../data/images/taxrebate/noimg.jpg';
            header('Content-Type: image/jpeg');
            header("Content-Disposition: attachment; filename=noimg.jpg");
            echo file_get_contents($noimageFile);
            exit;
        }
        $fileArray = explode(".",$trRow['filename']);

        if($fileArray[1]=="pdf"){
            header('Content-Type: application/pdf; charset=utf-8');
            header("Content-Disposition:attachment; filename=".$trRow['taxrebate_code'].".pdf");
            echo file_get_contents($fullPath);
            exit;
        }else{
            header('Content-Type: image/'.$fileArray[1]);
            //Force the download
            $header="Content-Disposition: attachment; filename=".$trRow['taxrebate_code'].".".$fileArray[1];
            header($header );
            // 	header("Content-Transfer-Encoding: binary");
            // 	header("Content-Length: ".$len);
            echo file_get_contents($fullPath);
            exit;
        }

    }
    public function loadpianyuan3Action(){
        set_time_limit(0);
        @ini_set('memory_limit', '2018M');
        header("Content-type:text/html;charset=utf-8");
        global $path;
        //$path ='D:\svncode\export_wms\branches\william\data\remote';
        $path = APPLICATION_PATH.'/../data/remote/';
        //$file_name = 'dhlremoteareas.csv';
        $file_name = 'dhlremoteareas.xlsx';

        //分辨出邮编还是城市
        //$filecontent = file_get_contents($path.'/'.$file_name);
        //$pianyuanRow = explode("\r\n",$filecontent);

        /*switch($resultArray['file_ext']){
            case ".xls":
            case ".xlsx":

                break;
            case ".csv":
                $resultArray = Common_Upload::readCSV($full_path);
                break;
            default:
                $resultArray = array();
                break;
        }*/


        $db = Common_Common::getAdapter();
        //查询城市偏远
        $city_sql = "select * from remoteDate where model_type='c'";
        $cityrows = $db->fetchAll($city_sql);
        $citysql='';
        foreach($cityrows as $key=>$city){
            $city_name = $city['low'];
            $country_code = $city['country_code'];
            $country = Service_Country::getByField($country_code,'country_code');
            $sql = "select * from city where country_id='{$country['country_id']}' and city_name='$city_name'";
            $cityRow = $db->fetchRow($sql);
            if(!empty($cityRow)){
                $citysql.="update city set is_remote='1' where city_id={$cityRow['city_id']};\r\n";
            }else{
                $citysql.="insert into city(country_id,country_name,city_name,is_remote) value('{$country['country_id']}','{$country['country_name_en']}','{$city_name}','1');\r\n";
            }
        }
        file_put_contents($path.'citysql.sql',$citysql);
        $city_sql = "select * from remoteDate where model_type='p'";
        $postrows = $db->fetchAll($city_sql);


        $postsql='';
        foreach($postrows as $key=>$post){
            $low = $post['low'];
            $high = $post['high'];
            $country_code = $city['country_code'];
            $country = Service_Country::getByField($country_code,'country_code');
            $postsql = "select * from postcode where country_id='{$country['country_id']}' and postcode_no='{$low}' and postcode_no_end='{$high}'";
            //$postcode = $db->fetchRow($postsql);
            /*if(!empty($postcode)){
                $postsql.="update postcode set is_remote='1' where postcode_id={$postcode['postcode_id']};\r\n";
            }else{
                $postsql.="insert into postcode(country_id,city_id,postcode_no,is_remote) value('{$country['country_id']}',0,'$low','$high',1);\r\n";
            }*/
            $postsql.="insert into postcode(country_id,city_id,postcode_no,is_remote) value('{$country['country_id']}',0,'$low','$high',1);\r\n";
        }


        file_put_contents($path.'postsql.sql',$postsql);


        exit('game over');
        $title = 'LOW,HIGH,COUNTRY NAME,countryCode';
        $cityString=$title."\r\n";
        $postString=$title."\r\n";
        $post_code_preg = '/[0-9]+|[a-zA-Z]*[0-9]+/i';
        $city_preg = '/[a-zA-Z]/';
        foreach($pianyuanRow as $key=>$value){
            if($key>0){
                $arr = explode(',',$value);
                $low = $arr[0];
                $high = $arr[1];
                $countryCode = $arr[3];
                /*print_r($arr);
                exit;*/
                if(preg_match($post_code_preg,$low)){
                    $postString.=$value."\r\n";
                }else{
                    $cityString.=$value."\r\n";
                }
            }
        }
        file_put_contents($path.'postcode.csv',$postString);
        file_put_contents($path.'city.csv',$cityString);
        echo 'game over';
    }
    public function loadpianyuanAction(){
        set_time_limit(0);
        header("Content-type:text/html;charset=utf-8");
        global $path;
        //$path ='D:\svncode\export_wms\branches\william\data\remote';
        $path = APPLICATION_PATH.'/../data/remote';

        function getdir($path){
            $arr = array();
            $files1 = scandir($path);
            foreach($files1 as $key=>$value){
                if(strstr($value,'csv')){
                    $arr[] = $value;
                }
            }
            return $arr;
        }

        function dosql($file_name){
            global $path;
            //$file_name = $path.'\MOROCCO.csv';
            //echo $path.$file_name;exit;
            $fileArr = explode('.',$file_name);
            $sqlname = $fileArr[0].'.sql';
            if(file_exists($path.'/'.$sqlname)){
                return;
            }
            $filecontent = file_get_contents($path.'/'.$file_name);
            $pianyuanRow = explode("\r\n",$filecontent);
            //print_r($pianyuanRow);
            $db = Common_Common::getAdapter();
            $stringall = '';
            foreach($pianyuanRow as $key=>$value){
                //print_r($value);
                /*if($key==3){
                    exit;
                }*/
                $string = '';
                if($key==0){
                    //国家
                    $country = Service_Country::getByField($value,'country_name_en');
                    if(empty($country)){
                        exit("国家{$value}不存在");
                    }
                }else{
                    //
                    $value = trim($value);
                    //$arr = strpos($value,'-');
                    if(strpos($value,'-')===false){
                        //有横岗
                        $sql = "select * from postcode where country_id='{$country['country_id']}' and city_id='0' and postcode_no='$value'";
                        $row = $db->fetchRow($sql);
                        if(empty($row)){
                            $string.="insert into postcode(country_id,postcode_no,postcode_no_end,is_remote) values('{$country['country_id']}','$value','','1');\r\n";
                        }else{
                            $string.="##{$country['country_id']},postcode_no:$value,已存在\r\n";
                            $string.= "update postcode set is_remote='1' where country_id='{$country['country_id']}' and city_id='0' and postcode_no='$value' limit 1;\r\n";
                        }
                    }else{
                        $arr = explode('-',$value);
                        $post_start = $arr[0];
                        $post_end = $arr[1];
                        $post_start = trim($post_start);
                        $post_end = trim($post_end);

                        $sql = "select * from postcode where country_id='{$country['country_id']}' and city_id='0' and postcode_no='$post_start' and postcode_no_end='$post_end'";
                        $row = $db->fetchRow($sql);

                        if(empty($row)){
                            $string.="insert into postcode(country_id,postcode_no,postcode_no_end,is_remote) values('{$country['country_id']}','$post_start','$post_end','1');\r\n";
                        }else{
                            $string.="##{$country['country_id']},postcode_no:$value,已存在\r\n";
                            $string.= "update postcode set is_remote='1' where country_id='{$country['country_id']}'  and city_id='0' and postcode_no='$post_start' and postcode_no_end='$post_end' and city_id='0' limit 1;\r\n";
                        }
                    }
                }

                file_put_contents($path."/{$country['country_name_en']}.sql",$string,FILE_APPEND);

            }
            echo 'over';
        }


        $arr = getdir($path);
        print_r($arr);
        foreach($arr as $key=>$value){
            dosql($value);
        }

    }

    public function loadpianyuan2Action(){


        function dosql($file_name){
            global $path;
            //$file_name = $path.'\MOROCCO.csv';
            //echo $path.$file_name;exit;
            $fileArr = explode('.',$file_name);
            $sqlname = $fileArr[0].'.sql';
            if(file_exists($path.'/'.$sqlname)){
                return;
            }
            $filecontent = file_get_contents($path.'/'.$file_name);
            $pianyuanRow = explode("\r\n",$filecontent);
            //print_r($pianyuanRow);
            $db = Common_Common::getAdapter();
            $stringall = '';
            foreach($pianyuanRow as $key=>$value){
                //print_r($value);
                /*if($key==3){
                    exit;
                }*/
                $string = '';
                if($key==0){
                    //国家
                    $country = Service_Country::getByField($value,'country_name_en');
                    if(empty($country)){
                        exit("国家{$value}不存在");
                    }
                }else{
                    //
                    $value = trim($value);
                    //$arr = strpos($value,'-');
                    if(strpos($value,'-')===false){
                        //有横岗
                        $sql = "select * from postcode where country_id='{$country['country_id']}' and city_id='0' and postcode_no='$value'";
                        $row = $db->fetchRow($sql);
                        if(empty($row)){
                            $string.="insert into postcode(country_id,postcode_no,postcode_no_end,is_remote) values('{$country['country_id']}','$value','','1');\r\n";
                        }else{
                            $string.="##{$country['country_id']},postcode_no:$value,已存在\r\n";
                            $string.= "update postcode set is_remote='1' where country_id='{$country['country_id']}' and city_id='0' and postcode_no='$value' limit 1;\r\n";
                        }
                    }else{
                        $arr = explode('-',$value);
                        $post_start = $arr[0];
                        $post_end = $arr[1];
                        $post_start = trim($post_start);
                        $post_end = trim($post_end);

                        $sql = "select * from postcode where country_id='{$country['country_id']}' and city_id='0' and postcode_no='$post_start' and postcode_no_end='$post_end'";
                        $row = $db->fetchRow($sql);

                        if(empty($row)){
                            $string.="insert into postcode(country_id,postcode_no,postcode_no_end,is_remote) values('{$country['country_id']}','$post_start','$post_end','1');\r\n";
                        }else{
                            $string.="##{$country['country_id']},postcode_no:$value,已存在\r\n";
                            $string.= "update postcode set is_remote='1' where country_id='{$country['country_id']}'  and city_id='0' and postcode_no='$post_start' and postcode_no_end='$post_end' and city_id='0' limit 1;\r\n";
                        }
                    }
                }

                file_put_contents($path."/{$country['country_name_en']}.sql",$string,FILE_APPEND);

            }
            echo 'over';
        }
    }


    public function pianyuan2Action(){
        $db = Common_Common::getAdapter();
        $sql = 'select * from country';
        $rows = $db->fetchAll($sql);

        $country_name = array(
            'ALGERIA',
            'ANDORRA',
            'ARGENTINA',
            'AUSTRALIA',
            'BANGLADESH',
            'BELARUS',
            'BOSNIA AND HERZEGOVINA',
            'BRAZIL',
            'BRUNEI',
            'BULGARIA',
            "CANARY ISLANDS, THE",
            'CHINA',
            'CROATIA',
            'CYPRUS',
            'CzechRepublic',
            'DENMARK',
            'ECUADOR',
            'ESTONIA',
            'Faeroe Islands',
            'FINLAND',
            'FRANCE',
            'French Guiana',
            'GERMANY',
            'GREECE',
            'GREENLAND',
            'GUADELOUPE',
            'GUATEMALA',
            'GUERNSEY',
            'HUNGARY',
            'ICELAND',
            'INDIA',
            'INDONESIA',
            'ISRAEL',
            'ITALY',
            'LATVIA',
            'LESOTHO',
            'MACEDONIA',
            'MALAYSIA',
            'MALDIVES',
            'MEXICO',
            'MOROCCO',
            'NEW CALEDONIA',
            'NEW ZEALAND',
            'NORWAY',
            'PAKISTAN',
            'PAPUA NEW GUINEA',
            'PHILIPPINES',
            'PORTUGAL',
            'PUERTO RICO',
            'REUNION',
            'ROMANIA',
            'Russia',
            'SERBIA',
            'SLOVAKIA',
            'SLOVENIA',
            'SOUTH AFRICA',
            'SPAIN',
            'SWEDEN',
            'SWITZERLAND',
            'TAIWAN',
            'TAJIKISTAN',
            'THAILAND',
            'TUNISIA',
            'TURKEY',
            'UNITED KINGDOM',
            'URUGUAY',
            'UZBEKISTAN'
            );

            foreach($country_name as $key=>$name){
                $country = Service_Country::getByField($name,'country_name_en');
                if(empty($country)){
                    echo $name." not exist<br/>";
                }else{
                    $sql2 = "select * from postcode where country_id='{$country['country_id']}' and is_remote='1' limit 1";
                    $remoteRow = $db->fetchAll($sql2);
                    if(empty($remoteRow)){
                        echo $sql2."<br/>";
                        echo $name." not add \r\n<br/>";
                    }
                }
            }


        /*foreach($rows as $key=>$row){
            $sql2 = "select * from postcode where country_id='{$row['country_id']}' and is_remote='1' limit 1";
            $remoteRow = $db->fetchAll($sql2);
            if(empty($remoteRow)){
                echo $sql2."<br/>";
                echo $row['country_name_en']."\r\n";
            }
        }*/
    }

    public function testfeeAction(){
        header("content-type:text/html;charset=utf-8");
        echo "<pre>";
        $order_code = 'LO1505280000383';
        $weight = 0.363;

        $order_code='SOE05640047437';
        $weight=0.05;

        //$order_code = 'SOE02130001604';


        $aOrder                     = Service_Orders::getByField($order_code, 'order_code');
        $aShipOrder                 = Service_ShipOrder::getByField($order_code, 'order_code');
        $aAddress                   = Service_OrderAddressBook::getByField($order_code, 'order_code');
        $countryArr                 = Service_Country::getByField($aAddress['oab_country_id'],'country_id');
        $customerArr                = Service_Customer::getByField($aOrder['customer_code'],'customer_code',array('customer_saler_user_id','customer_currency'));
        $customerCurrencyRow        = Service_Currency::getByField($customerArr['customer_currency'],'currency_code',array('currency_code','currency_rate','currency_batch_number'));
        $shippingMethodArr          = Service_ShippingMethod::getByField($aOrder['sm_code'],'sm_code',array('sm_vol_rate','sm_is_volume'));



        $keys           = array(
            'warehouseId'               => $aOrder['warehouse_id'],
            'countryId'                 => $aAddress['oab_country_id'],
            'smCode'                    => $aOrder['sm_code'],
            'weight'                    => $aShipOrder['so_weight'],
            'order_code'                => $order_code,
            'realWeight'                => 0.1180,
            'customerCode'              => $aOrder['customer_code'],
        );
        print_r($keys);
        if($aAddress['oab_country_id']=='253'){
            //美国的要加入城市
            $conditionCity = array(
                'country_id'=>$aAddress['oab_country_id'],
                'city_name'=>$aAddress['oab_city']
            );
            $citys = Service_City::getByCondition($conditionCity,'*');
            print_r($citys);
            if(!empty($citys)){
                $keys['cityId'] = $citys[0]['city_id'];
            }
        }
        //print_r($keys);
        //exit;
        $objCalculate   = new Common_CalculateShipping2();
        $objCalculate->setParams($keys);
        $aCalculate = $objCalculate->getRate();
        echo $order_code;

        print_r($aCalculate);
        exit;


        /*$orderRow       = Service_LogisticsOrder::getByField($order_code, 'logistics_code');
        $addressRow     = Service_LogisticsOrderAddress::getByField($order_code, 'logistics_code');
        $orderHsRow     = Service_LogisticsOrderHs::getByField($order_code, 'logistics_code');
        $orderDetailRow = Service_ReceivingBatchOrder::getByField($order_code, 'logistics_code');*/

        $objCalculate   = new Common_CalculateShipping2();
        $keys = array(
            'warehouseId'   => $orderRow['warehouse_id'],
            'countryId'     => $addressRow['loa_country'],
            'smCode'        => $orderRow['sm_code'],
            'weight'        => $weight,
            'customerCode'  => $orderRow['customer_code'],
        );

        $objCalculate->setParams($keys);
        $aCalculate = $objCalculate->getRate();

        print_r($aCalculate);

        /*$data = Process_CustomerBill::getBillDetailData('B1505290001');
        print_r($data);*/


    }

    public function invoiceAction(){
        $invoice = new Service_InvoiceProcess('SOE02070002586');
        $result = $invoice->getResult();
        print_r($result);




        }

    public function getinfoAction(){

        $apiUrl = "http://www.qhwftpa.com:8002/InterfaceSerivce/CmblCustomService.svc?wsdl";
        $companyid = 'SZBH';
        $token = '61B78DAC-336E-4BBF-9104-D3CE03E12936';
        /*private $testUser = array(
            'E0110',
            'E0207'
        );*/
        $goodsRow['goods_code'] = 'JKL000491';
        $requestHead = array(
            'companyid' => $companyid,
            'token' => $token
        );

        echo "<pre>";

        $request['requestHead'] = $requestHead;

        $request['goodsId'] = $goodsRow['goods_code'];

        $request['goodsId'] = $goodsRow['goods_code'];

        $url = $apiUrl;
        $client = new SoapClient($url);
        //echo "</pre>";
        //print_r($client->__getFunctions());

        $goodsinfo = $client->GetGoodsInfo($request);

        print_r($goodsinfo);



    }


    public function splitAction(){

        function separateAsn($receivingCode){
            $receiving = Service_Receiving::getByField($receivingCode,'receiving_code',"*");
            if($receiving['trade_mode']=="9610"){
                if($receiving['receive_model_type']=="1"){
                    $goodsIdArr = Service_OrderProduct::getGoodsId($receiving['receiving_code']);
                    $sumNetWeight = Service_OrderProduct::calNetWeightByCondition(array('receiving_code'=>$receiving['receiving_code']));
                }else{
                    $goodsIdArr = Service_ReceivingDetail::getGoodsId($receiving['receiving_code']);
                    $sumNetWeight = Service_ReceivingDetail::sumNetWeight($receiving['receiving_code']);
                }
                $goodsIdArr = array_chunk($goodsIdArr,35);
                $subIndex = 1;
                $gross_wt = ($receiving['roughweight']-$sumNetWeight)/count($goodsIdArr);
                foreach($goodsIdArr as $gk=>$gv){
                    if($subIndex<10){
                        $sub_receiving_code = $receiving['receiving_code']."-0".$subIndex;
                    }else{
                        $sub_receiving_code = $receiving['receiving_code']."-".$subIndex;
                    }
                    $subIndex++;
                    $receivingXml = array(
                        'receiving_code'=>$receiving['receiving_code'],
                        'sub_receiving_code'=>$sub_receiving_code,
                        'gross_wt'=>'0',
                        'net_wt'=>'0',
                        'pack_no'=>'0',
                        'refercence_form_id'=>'',
                        'rx_add_time'=>date("Y-m-d H:i:s"),
                        'receiving_xml_status'=>'3',
                    );
                    echo "<pre>";
                    print_r($receivingXml);
                    //Service_ReceivingXml::add($receivingXml);
                    $RXdbObj = new Table_ReceivingXml();
                    $rxId = $RXdbObj->getAdapter()->lastInsertId();
                    $net_wt = 0;
                    $pack_no = 0;
                    $G_NO_index = 1;
                    foreach($gv as $goods_id){
                        if($receiving['receive_model_type']=="1"){
                            $productList = Service_OrderProduct::getJoinProductByCondition(array('goods_id'=>$goods_id,'receiving_code'=>$receiving['receiving_code']));
                        }else{
                            $productList = Service_ReceivingDetail::getJoinProductByCondition(array('goods_id'=>$goods_id,'receiving_code'=>$receiving['receiving_code']));
                        }
                        $productRow = Service_Product::getByField($productList[0]['product_id'],'product_id',"*");
                        $currencyRow = Service_Currency::getByField($productRow['currency_code'],'currency_code',"*");
                        $receivingXmlDetail = array(
                            'rx_id'=>$rxId,
                            'from_id'=>$receiving['receiving_code'],
                            'sub_receiving_code'=>$sub_receiving_code,
                            'g_no'=>$G_NO_index,
                            'goods_id'=>$productList[0]['goods_id'],
                            'merger_g_no'=>$G_NO_index,
                            'code_ts'=>$productList[0]['hs_code'],
                            'g_name_cn'=>$productList[0]['hs_goods_name'],
                            //'decl_price'=>"",
                            'curr'=>$currencyRow['currency_hs_code'],
                            'qty_1'=>0,
                            'unit_1'=>'',
                            'qty_2'=>'',
                            'unit_2'=>'',
                        );

                        $g_qty = 0;
                        $decl_total = 0;
                        $decl_price = 0;
                        foreach($productList as $p){
                            if($receiving['receive_model_type']=="1"){
                                $quantity = $p['op_quantity'];
                                $g_qty+=$p['op_quantity'];
                            }else{
                                $quantity = $p['rd_receiving_qty'];
                                $g_qty+=$p['rd_receiving_qty'];
                            }

                            $hemList = Service_HsElementMap::getByCondition(array('product_id'=>$p['product_id']), 'hem_detail');
                            $elements = array();

                            foreach($hemList as $hemRow) $elements[] = $hemRow['hem_detail'];
                            $receivingXmlDetail['g_model'] = implode('|',$elements);
                            $hs_uom_map = Service_HsUomMap::getByField($p['product_id'],'product_id',"*");
                            $quantitylaw1 = isset($hs_uom_map['hum_quantity_law'])?$hs_uom_map['hum_quantity_law']:'0';
                            $receivingXmlDetail['qty_1'] += $quantitylaw1*$quantity;
                            $quantitylaw2 = isset($hs_uom_map['hum_quantity_second'])?$hs_uom_map['hum_quantity_second']:"0";
                            $receivingXmlDetail['qty_2'] += $quantitylaw2*$quantity;
                            if(!empty($hs_uom_map)) $hs_uom = Service_HsUom::getByField($hs_uom_map['hu_id'],'hu_id',"*");
                            $receivingXmlDetail['unit_1'] = isset($hs_uom['pu_code_law'])?$hs_uom['pu_code_law']:"";
                            $receivingXmlDetail['unit_2'] = isset($hs_uom['pu_code_second'])?$hs_uom['pu_code_second']:"";
                            $product = Service_Product::getByField($p['product_id'],"product_id","*");
                            $decl_total += $product['product_declared_value']*$quantity;
                            $receivingXmlDetail['g_unit'] = $product['pu_code'];

                        }
                        $pack_no+=$g_qty;
                        if($receiving['receive_model_type']=="1"){
                            $ntWeight = Service_OrderProduct::calNetWeightByCondition(array('goods_id'=>$goods_id,'receiving_code'=>$receiving['receiving_code']));
                        }else{
                            $ntWeight = Service_ReceivingDetail::calNetWeightByCondition(array('goods_id'=>$goods_id,'receiving_code'=>$receiving['receiving_code']));
                        }
                        $net_wt+= $ntWeight;
                        $decl_price = sprintf("%.4f",$decl_total/$g_qty);
                        $receivingXmlDetail['decl_price'] = $decl_price;
                        $receivingXmlDetail['g_qty'] = $g_qty;
                        $receivingXmlDetail['decl_total'] = $decl_total;
                        print_r($receivingXmlDetail);

                        //Service_ReceivingXmlDetail::add($receivingXmlDetail);
                        $G_NO_index++;
                    }
                    $updateReceivingXml = array(
                        'gross_wt'=>$net_wt+$gross_wt,
                        'net_wt'=>$net_wt,
                        'pack_no'=>$pack_no,
                    );
                    //Service_ReceivingXml::update($updateReceivingXml,$sub_receiving_code,'sub_receiving_code');

                    /*$aMessage['fmt_code'] = 'MRK';
                    $aMessage['fmt_type'] = 'BSG011';
                    $aMessage['refercence_no'] = $sub_receiving_code;
                    $aMessage['fml_status'] = 1;
                    $aMessage['fml_add_time'] = date('Y-m-d H:i:s');
                    Service_FtpMessageSendlist::add($aMessage);*/

                }
            }
        }

        separateAsn('BHR160006460');
    }



}