<?php
/**
 * @desc 获取DHL标签信息
 *
 */

require_once ('config.php');
$flag = APPLICATION_PATH . '/../data/log/getDHLLabel.lock';

if (@file_exists($flag)) {
    echo "Another process is running.\r\n";
    echo "{$flag}\r\n";
    exit();
}

$handler = fopen($flag, 'wb');
fclose($handler);

set_time_limit(300);
//header("Content-type: text/html; charset=utf-8");
$warehouse = Service_Warehouse::getByField('SZ01','warehouse_code');
if( !$warehouse ) {
    echo "仓库不存在\r\n";
    echo "[" . date('Y-m-d H:i:s') . "] End run\r\n";
    @unlink($flag);
    exit;
}

$shipMethod = array();
$shipRows = Service_ShippingMethod::getByCondition( array('sm_code'=>array('HKDHL','BH-HKDHL'),'warehouse_id_arr'=>array(0,$warehouse['warehouse_id'])));
foreach( $shipRows as $value) {
    $shipMethod[$value['sm_code']] = $value;
}

if( !isset($shipMethod['HKDHL']) || !isset($shipMethod['BH-HKDHL']) ) {
    echo "运输方式数据异常\r\n";
    echo "[" . date('Y-m-d H:i:s') . "] End run\r\n";
    @unlink($flag);
    exit;
}

$page = 1;
$pageSize = 100;
$condition = array(
    'sm_code_Arr'=>array('HKDHL','BH-HKDHL'),
    'customer_code'=>'E0693',//环球
    'order_status'=>4,
    'empty_ref_tracking_number'=>1,
    'warehouse_id'=>$warehouse['warehouse_id']
);
$orderColumns = array('order_id','order_code','sm_code','is_remote_city','warehouse_id','customer_code');
$detailColumns = array('sod_id','op_title','sod_length','sod_width','sod_height','sod_weight','sod_vol_weight','op_id','op_description');

$adapter = Common_Common::getAdapter();

$total = Service_Orders::getByCondition($condition,"count(*)");
$pageSize = 100;
$totalPage = ceil($total/$pageSize);
for($page=1;$page<=$totalPage;$page++){
    $rows = Service_Orders::getByCondition($condition, $orderColumns, $pageSize, $page, 'order_id desc' );
    foreach( $rows as $value ) {
        $adapter->beginTransaction();
        try{
            $shipOrderDetails = Service_ShipOrderDetail::getByCondition( array( 'order_code' => $value['order_code'] ), $detailColumns, 0, 0, 'sod_id' );
            if( empty( $shipOrderDetails )  )
                throw new Exception($value['order_code'].'缺少ship_order_detail信息');

            $totalPieces = count( $shipOrderDetails );
            $piecesDetail = array();
            $totalWeight = $totalVolWeight = 0;

            foreach( $shipOrderDetails as $v ) {
                $weight = sprintf('%0.2f',$v['sod_weight']);
                $volWeight = sprintf('%0.2f',$v['sod_vol_weight']);
                $piecesDetail[] = array(
                    'length' => (int)$v['sod_length'],
                    'width' => (int)$v['sod_width'],
                    'height' => (int)$v['sod_height'],
                    'weight' => $weight,
                    'op_description'=>$v['op_description'],
                    'op_id'=>$v['op_id'],
                );
                $totalWeight += $weight;
                $totalVolWeight += $volWeight;
            }
            $shipOrder = Service_ShipOrder::getByField($value['order_code'], 'order_code');
            switch( $value['sm_code'] ){
                case 'BH-HKDHL':
                    $dhlApiProcess = new Service_BHHKDHLApiProcess($value['order_code'], $shipOrder['so_code'], $piecesDetail,'1');
                    break;
                default :
                    $dhlApiProcess = new Service_DHLApiProcess2($value['order_code'], $shipOrder['so_code'], $piecesDetail,'PDF');
                    break;
            }
            $apiResult = $dhlApiProcess->runAPI();
            if ($apiResult['ask'] == '0')
                throw new Exception($apiResult['message']);

            $pdfPath = $apiResult['PDF'];
            $encodePath = base64_encode($pdfPath);
            $tracking_number = $apiResult['AirwayBillNumber']; //跟踪号
            $subTrackingNumber = $apiResult['LicensePlates'];

            if( $value['sm_code'] == 'BH-HKDHL') {
                $subTrackingNumber = array();
                for($i = 0; $i < $totalPieces; $i++) {
                    $subTrackingNumber[] = $tracking_number;
                }
            }

            $updateOrder = array(
                'update_time' => date('Y-m-d H:i:s'),
                'ref_tracking_number' => $tracking_number,
            );
            $result = Service_Orders::update($updateOrder, $value['order_code'], 'order_code');
            if( !$result )
                throw new Exception( '更新服务商单号失败' );

            if( $totalWeight > $totalVolWeight )
                $totalVolWeight = $totalWeight;

            $shipOrderRow = array(
                'so_weight' => $totalWeight,
                'so_vol_weight' => $totalVolWeight
            );
            $address = Service_OrderAddressBook::getByField($value['order_code'],'order_code');
            if(!$address)
                throw new Exception($value['order_code'].'缺少地址信息');

            $objCalculate = new Common_CalculateShipping();
            $keys = array(
                'warehouseId' => $value['warehouse_id'],
                'countryId' => $address['oab_country_id'],
                'smCode' => $value['sm_code'],
                'weight' => $totalVolWeight,
                'realWeight' => $totalVolWeight,
                'order_code' => $value['order_code'],
                'customerCode' => $value['customer_code'],
            );

            $objCalculate->setParams($keys);
            $aCalculate = $objCalculate->getRate();

            $shipOrderRow = array(
                'tracking_number' => $tracking_number,
                'file_path' => $pdfPath,
                'so_update_time' => date("Y-m-d H:i:s"),
            );
            $fee_weight = isset($aCalculate['data']['cost']['fee_weight']) ? $aCalculate['data']['cost']['fee_weight'] : 0;
            if (isset($fee_weight) && $fee_weight > 0) {
                $shipOrderRow['so_fee_weight'] = $fee_weight;
            } else {
                $shipOrderRow['so_fee_weight'] = $totalVolWeight;
            }

            $updateResult = Service_ShipOrder::update($shipOrderRow, $value['order_code'], 'order_code');
            if( !$updateResult )
                throw new Exception( '更新Ship_order失败' );

            if( $subTrackingNumber && is_array( $subTrackingNumber ) ) {
                foreach( $shipOrderDetails as $k=>$v ) {
                    $uResult = Service_ShipOrderDetail::update( array( 'sub_tracking_number'=>$subTrackingNumber[$k] ),$v['sod_id']);
                    if( !$uResult )
                        throw new Exception( '更新Ship_order_detail失败' );
                }
            }
            if($value['is_remote_city']==1){
                Service_Exception::addExceptionByCode('theGoodsInRemoteAreas' , $value['order_code']);
            }
            //发送发票
            $invoice = new Service_InvoiceProcess($value['order_code']);
            $invoiceResult = $invoice->getResult();
            $adapter->commit();
            echo $value['order_code']."获取单号成功\n\r";
        } catch(Exception $e) {
            $adapter->rollBack();
            $errorLog = array(
                'order_code' => $value['order_code'],
                'sm_code' => $value['sm_code'],
                'content' => $value['order_code'].$e->getMessage(),
            );
            Service_TrackingErrorLog::add($errorLog);
            echo $value['order_code'].$e->getMessage()."\n\r";

            if($e->getMessage()=="系统已经存在相同的订单号并且我司已确认收货，系统不会将这部分订单重新上传"&&$value['sm_code']=='BH-HKDHL'){
                $result = Service_BHHKDHLApiProcess::queryAwbCode($value['order_code']);
                $resultArr = json_decode($result);
                $result = Common_Common::objectToArray($resultArr);
                if(!isset($result['Data'][0]['AWB'])||$result['Data'][0]['AWB']=="") continue;

                $tracking_number = $result['Data'][0]['AWB'];

                $adapter->beginTransaction();
                try{
                    $shipOrderDetails = Service_ShipOrderDetail::getByCondition( array( 'order_code' => $value['order_code'] ), $detailColumns, 0, 0, 'sod_id' );
                    if( empty( $shipOrderDetails )  )
                        throw new Exception($value['order_code'].'缺少ship_order_detail信息');

                    $totalPieces = count( $shipOrderDetails );
                    $piecesDetail = array();
                    $totalWeight = $totalVolWeight = 0;

                    foreach( $shipOrderDetails as $v ) {
                        $weight = sprintf('%0.2f',$v['sod_weight']);
                        $volWeight = sprintf('%0.2f',$v['sod_vol_weight']);
                        $piecesDetail[] = array(
                            'length' => (int)$v['sod_length'],
                            'width' => (int)$v['sod_width'],
                            'height' => (int)$v['sod_height'],
                            'weight' => $weight,
                            'op_description'=>$v['op_description'],
                            'op_id'=>$v['op_id'],
                        );
                        $totalWeight += $weight;
                        $totalVolWeight += $volWeight;
                    }
                    $shipOrder = Service_ShipOrder::getByField($value['order_code'], 'order_code');

                    if( $value['sm_code'] == 'BH-HKDHL') {
                        $subTrackingNumber = array();
                        for($i = 0; $i < $totalPieces; $i++) {
                            $subTrackingNumber[] = $tracking_number;
                        }
                    }
                    $apiDhlRow = Service_ApiDhl::getByField($value['order_code'], 'order_code');
                    if(empty($apiDhlRow)) {
                        $insertRow['order_code'] = $value['order_code'];
                        $insertRow['so_code'] = $shipOrder['so_code'];
                        $insertRow['status'] = 1;
                        $insertRow['create_time'] = date('Y-m-d H:i:s');
                        Service_ApiDhl::add($insertRow);
                    }

                    $updateOrder = array(
                        'update_time' => date('Y-m-d H:i:s'),
                        'ref_tracking_number' => $result['Data'][0]['AWB'],
                    );
                    Service_Orders::update($updateOrder, $value['order_code'], 'order_code');
                    $address = Service_OrderAddressBook::getByField($value['order_code'],'order_code');
                    if(!$address)
                        throw new Exception($value['order_code'].'缺少地址信息');

                    $objCalculate = new Common_CalculateShipping();
                    $keys = array(
                        'warehouseId' => $value['warehouse_id'],
                        'countryId' => $address['oab_country_id'],
                        'smCode' => $value['sm_code'],
                        'weight' => $totalVolWeight,
                        'realWeight' => $totalVolWeight,
                        'order_code' => $value['order_code'],
                        'customerCode' => $value['customer_code'],
                    );

                    $objCalculate->setParams($keys);
                    $aCalculate = $objCalculate->getRate();

                    $pdfFile = Service_BHHKDHLApiProcess::reGetPdf($value['order_code'],$tracking_number);
                    if($pdfFile == false) throw new Exception( '获取标签失败' );
                    $shipOrderRow = array(
                        'tracking_number' => $tracking_number,
                        'file_path' => $pdfFile,
                        'so_update_time' => date("Y-m-d H:i:s"),
                    );
                    $fee_weight = isset($aCalculate['data']['cost']['fee_weight']) ? $aCalculate['data']['cost']['fee_weight'] : 0;
                    if (isset($fee_weight) && $fee_weight > 0) {
                        $shipOrderRow['so_fee_weight'] = $fee_weight;
                    } else {
                        $shipOrderRow['so_fee_weight'] = $totalVolWeight;
                    }

                    $updateResult = Service_ShipOrder::update($shipOrderRow, $value['order_code'], 'order_code');
                    if( !$updateResult )
                        throw new Exception( '更新Ship_order失败' );

                    if( $subTrackingNumber && is_array( $subTrackingNumber ) ) {
                        foreach( $shipOrderDetails as $k=>$v ) {
                            $uResult = Service_ShipOrderDetail::update( array( 'sub_tracking_number'=>$subTrackingNumber[$k] ),$v['sod_id']);
                            if( !$uResult )
                                throw new Exception( '更新Ship_order_detail失败' );
                        }
                    }

                    if($value['is_remote_city']==1){
                        Service_Exception::addExceptionByCode('theGoodsInRemoteAreas' , $value['order_code']);
                    }
                    //发送发票
                    $label = new Service_LabelSendProcess();
                    $getPdfFilePath = APPLICATION_PATH . '/../data/pdf/BHHKDHL/';
                    $label->sendLabel($getPdfFilePath,$value['order_code']);
                    $invoice = new Service_InvoiceProcess($value['order_code']);
                    $invoiceResult = $invoice->getResult();
                    $adapter->commit();
                }catch (Exception $e){
                    $adapter->rollBack();
                    echo $e->getMessage()."\n\r";
                }
            }
        }
    }
}

/*
while ( $rows = Service_Orders::getByCondition($condition, $orderColumns, $pageSize, $page, 'order_id' )  ) {
    $condition['order_id_gt'] = $rows[count($rows)-1]['order_id'];
    foreach( $rows as $value ) {
        $adapter->beginTransaction();
        try{
            $shipOrderDetails = Service_ShipOrderDetail::getByCondition( array( 'order_code' => $value['order_code'] ), $detailColumns, 0, 0, 'sod_id' );
            if( empty( $shipOrderDetails )  )
                throw new Exception($value['order_code'].'缺少ship_order_detail信息');

            $totalPieces = count( $shipOrderDetails );
            $piecesDetail = array();
            $totalWeight = $totalVolWeight = 0;

            foreach( $shipOrderDetails as $v ) {
                $weight = sprintf('%0.2f',$v['sod_weight']);
                $volWeight = sprintf('%0.2f',$v['sod_vol_weight']);
                $piecesDetail[] = array(
                    'length' => (int)$v['sod_length'],
                    'width' => (int)$v['sod_width'],
                    'height' => (int)$v['sod_height'],
                    'weight' => $weight,
                    'op_description'=>$v['op_description'],
                    'op_id'=>$v['op_id'],
                );
                $totalWeight += $weight;
                $totalVolWeight += $volWeight;
            }
            $shipOrder = Service_ShipOrder::getByField($value['order_code'], 'order_code');
            switch( $value['sm_code'] ){
                case 'BH-HKDHL':
                    $dhlApiProcess = new Service_BHHKDHLApiProcess($value['order_code'], $shipOrder['so_code'], $piecesDetail,'1');
                    break;
                default :
                    $dhlApiProcess = new Service_DHLApiProcess2($value['order_code'], $shipOrder['so_code'], $piecesDetail,'PDF');
                    break;
            }
            $apiResult = $dhlApiProcess->runAPI();
            if ($apiResult['ask'] == '0')
                throw new Exception($apiResult['message']);

            $pdfPath = $apiResult['PDF'];
            $encodePath = base64_encode($pdfPath);
            $tracking_number = $apiResult['AirwayBillNumber']; //跟踪号
            $subTrackingNumber = $apiResult['LicensePlates'];

            if( $value['sm_code'] == 'BH-HKDHL') {
                $subTrackingNumber = array();
                for($i = 0; $i < $totalPieces; $i++) {
                    $subTrackingNumber[] = $tracking_number;
                }
            }

            $updateOrder = array(
                'update_time' => date('Y-m-d H:i:s'),
                'ref_tracking_number' => $tracking_number,
            );
            $result = Service_Orders::update($updateOrder, $value['order_code'], 'order_code');
            if( !$result )
                throw new Exception( '更新服务商单号失败' );

            if( $totalWeight > $totalVolWeight )
                $totalVolWeight = $totalWeight;

            $shipOrderRow = array(
                'so_weight' => $totalWeight,
                'so_vol_weight' => $totalVolWeight
            );
            $address = Service_OrderAddressBook::getByField($value['order_code'],'order_code');
            if(!$address)
                throw new Exception($value['order_code'].'缺少地址信息');

            $objCalculate = new Common_CalculateShipping();
            $keys = array(
                'warehouseId' => $value['warehouse_id'],
                'countryId' => $address['oab_country_id'],
                'smCode' => $value['sm_code'],
                'weight' => $totalVolWeight,
                'realWeight' => $totalVolWeight,
                'order_code' => $value['order_code'],
                'customerCode' => $value['customer_code'],
            );

            $objCalculate->setParams($keys);
            $aCalculate = $objCalculate->getRate();

            $shipOrderRow = array(
                'tracking_number' => $tracking_number,
                'file_path' => $pdfPath,
                'so_update_time' => date("Y-m-d H:i:s"),
            );
            $fee_weight = isset($aCalculate['data']['cost']['fee_weight']) ? $aCalculate['data']['cost']['fee_weight'] : 0;
            if (isset($fee_weight) && $fee_weight > 0) {
                $shipOrderRow['so_fee_weight'] = $fee_weight;
            } else {
                $shipOrderRow['so_fee_weight'] = $totalVolWeight;
            }

            $updateResult = Service_ShipOrder::update($shipOrderRow, $value['order_code'], 'order_code');
            if( !$updateResult )
                throw new Exception( '更新Ship_order失败' );

            if( $subTrackingNumber && is_array( $subTrackingNumber ) ) {
                foreach( $shipOrderDetails as $k=>$v ) {
                    $uResult = Service_ShipOrderDetail::update( array( 'sub_tracking_number'=>$subTrackingNumber[$k] ),$v['sod_id']);
                    if( !$uResult )
                        throw new Exception( '更新Ship_order_detail失败' );
                }
            }
            if($value['is_remote_city']==1){
                Service_Exception::addExceptionByCode('theGoodsInRemoteAreas' , $value['order_code']);
            }
            //发送发票
            $invoice = new Service_InvoiceProcess($value['order_code']);
            $invoiceResult = $invoice->getResult();
            $adapter->commit();
            echo $value['order_code']."获取单号成功\n\r";
        } catch(Exception $e) {
            $adapter->rollBack();
            $errorLog = array(
                'order_code' => $value['order_code'],
                'sm_code' => $value['sm_code'],
                'content' => $value['order_code'].$e->getMessage(),
            );
            Service_TrackingErrorLog::add($errorLog);
            echo $value['order_code'].$e->getMessage()."\n\r";
        }
    }
}*/
echo "[" . date('Y-m-d H:i:s') . "] End run\r\n";
@unlink($flag);
exit;