<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Administrator
 * Date: 18-1-22
 * Time: 下午4:59
 * To change this template use File | Settings | File Templates.
 */
class Service_EportLogisticsXmlProcess
{
    /**
     * 报文类型
     */
    const TYPE_CEB501 = 0; // 物流运单报文
    const TYPE_CEB503 = 1; // 运单状态报文
    const TYPE_CEB301 = 2; // 电子订单报文
    const TYPE_CEB601 = 3; // 出境清单状态报文
    const TYPE_CEB303 = 303; // 订单报文
    const TYPE_CEB403 = 403; // 收款单报文
    const TYPE_CEB505 = 505; // 运单报文
    const TYPE_CEB507 = 507; // 运抵单报文
    const TYPE_CEB603 = 603; // 出口清单报文
    const TYPE_CEB605 = 605; // 撤销申请单报文
    const TYPE_CEB509 = 509; // 离境单报文
    const TYPE_CEB607 = 607; // 清单总分单报文
    const TYPE_CEB701 = 701; // 汇总申请报文
    const TYPE_CEB792 = 792; // 汇总结果单报文

    /**
     * 订单模式
     */
    const MODE_STOCK      = 0; // 网购保税（备货）
    const MODE_COLLECTION = 1; // 直购进口（集货）

    /**
     * 状态
     */
    const STATUS_PENDING   = 0; // 待发送
    const STATUS_AUDITING  = 1; // 待审核
    const STATUS_DECLARING = 2; // 电子口岸申报中
    const STATUS_SUCCESS   = 3; // 发送海关成功
    const STATUS_FAILURE   = 4; // 发送海关失败
    const STATUS_REJECTION = 5; // 海关退单
    const STATUS_ACCEPTED  = 6; // 海关入库
    const STATUS_EXCEPTION = 7; // 申报异常

    /**
     * 报文头部信息
     */
    const ORG_CODE            = '081862509'; // 组织机构代码
    const COP_CODE            = '4403660028'; // 传输企业代码
    const COP_NAME            = '深圳市招海国际货运代理有限公司'; // 传输企业名称
    const SENDER_ID           = 'DXPENT0000012142'; // 企业客户端ID号
    const RECEIVER_ID         = 'EPORT'; // 接收方
    const RECEIVER_DEPARTMENT = 'Q'; // 报文发送监管单位：C海关、Q检验检疫
    const VERSION             = '1.0'; // 版本号
    const appUid              = "8930001000818";
    const appUname            = "李昱桦";

    /**
     * 获取队列状态信息
     *
     * @return array
     */
    public static function getStatus() {
        return array(
            self::STATUS_PENDING   => '待发送',
            self::STATUS_AUDITING  => '待审核',
            self::STATUS_DECLARING => '电子口岸申报中',
            self::STATUS_SUCCESS   => '发送海关成功',
            self::STATUS_FAILURE   => '发送海关失败',
            self::STATUS_REJECTION => '海关退单',
            self::STATUS_ACCEPTED  => '海关入库',
            self::STATUS_EXCEPTION => '申报异常',
        );
    }

    /**
     * 入队列
     *
     * @param array   $data
     * @param integer $type
     * @return array
     */
    public static function push(array $data, $type = self::TYPE_CEB501) {
        $response = array(
            'status'  => 0,
            'message' => '',
        );

        try {
            $operationTime = date('Y-m-d H:i:s');

            if (self::TYPE_CEB503 === $type) {
                $requiredField = array(
                    'order_code',
                    'signed_time',
                );

                foreach ($requiredField as $field) {
                    if (!isset($data[$field])) {
                        throw new Exception('添加运单状态CEB503队列信息需要字段：' . implode('|', $requiredField));
                    }
                }

                $orderXml = Service_EportLogisticsXml::getByCondition(array(
                    'order_code' => $data['order_code'],
                    'xml_type'   => $type,
                ));

                if ($orderXml) {
                    throw new Exception('运单状态CEB503队列信息已存在', 200);
                }

                $orderXml = Service_EportLogisticsXml::getByCondition(array(
                    'order_code' => $data['order_code'],
                    'xml_type'   => self::TYPE_CEB503,
                ));

                if (empty($orderXml)) {
                    throw new Exception('缺乏物流运单CEB503队列信息');
                }

                if (count($orderXml) > 1) {
                    throw new Exception('存在多条物流运单CEB503队列信息');
                }

                $orderXml = $orderXml[0];

                Service_EportLogisticsXml::insert(array(
                    'order_code'         => $orderXml['order_code'],
                    'tracking_number'    => $orderXml['tracking_number'],
                    'sm_code'            => $orderXml['sm_code'],
                    'warehouse_id'       => $orderXml['warehouse_id'],
                    'order_mode'         => $orderXml['order_mode'],
                    'customer_code'      => $orderXml['customer_code'],
                    'order_created_time' => $orderXml['order_created_time'],
                    'created_time'       => $operationTime,
                    'signed_time'        => $data['signed_time'],
                    'updated_time'       => $operationTime,
                    'xml_type'           => $type,
                    'xml_status'         => 0,
                ));

                /*Service_EportXmlLog::insert(array(
                    'order_code'      => $orderXml['order_code'],
                    'tracking_number' => $orderXml['tracking_number'],
                    'xml_type'        => $type,
                    'xml_path'        => '',
                    'created_time'    => $operationTime,
                    'return_info'     => '已加入发送队列',
                ));*/

                $response['status']  = 1;
                $response['message'] = '运单状态CEB503队列信息已添加';
            }else if(self::TYPE_CEB301 === $type){
                $requiredField = array(
                    'order_code',
                    'tracking_number',
                    'sm_code',
                    'warehouse_id',
                    'order_mode',
                    'customer_code',
                    'order_created_time',
                    'xml_type',
                    'xml_status',
                );

                foreach ($requiredField as $field) {
                    if (!isset($data[$field])) {
                        throw new Exception('添加订单CEB301队列信息需要字段：' . implode('|', $requiredField)."miss ".$field);
                    }
                }

                $orderXml = Service_EportLogisticsXml::getByCondition(array(
                    'order_code' => $data['order_code'],
                    'xml_type'   => $type,
                ));

                if ($orderXml) {
                    throw new Exception('物流运单CEB301队列信息已存在', 200);
                }

                Service_EportLogisticsXml::insert(array(
                    'order_code'         => $data['order_code'],
                    'tracking_number'    => $data['tracking_number'],
                    'sm_code'            => $data['sm_code'],
                    'warehouse_id'       => $data['warehouse_id'],
                    'order_mode'         => $data['order_mode'],
                    'customer_code'      => $data['customer_code'],
                    'order_created_time' => $data['order_created_time'],
                    'created_time'       => $operationTime,
                    'updated_time'       => $operationTime,
                    'xml_type'           => $type,
                    'xml_status'         => 0,
                ));

                /*Service_EportXmlLog::insert(array(
                    'order_code'      => $data['order_code'],
                    'tracking_number' => $data['tracking_number'],
                    'xml_type'        => $type,
                    'xml_path'        => '',
                    'created_time'    => $operationTime,
                    'return_info'     => '已加入发送队列',
                ));*/

                $response['status']  = 1;
                $response['message'] = '物流运单CEB301队列信息已添加';
            }else {
                $requiredField = array(
                    'order_code',
                    'tracking_number',
                    'sm_code',
                    'warehouse_id',
                    'order_mode',
                    'customer_code',
                    'order_created_time',
                    'xml_type',
                    'xml_status',
                );

                foreach ($requiredField as $field) {
                    if (!isset($data[$field])) {
                        throw new Exception('添加物流运单CEB501队列信息需要字段：' . implode('|', $requiredField));
                    }
                }

                $orderXml = Service_EportLogisticsXml::getByCondition(array(
                    'order_code' => $data['order_code'],
                    'xml_type'   => $type,
                ));

                if ($orderXml) {
                    throw new Exception('物流运单CEB501队列信息已存在', 200);
                }

                Service_EportLogisticsXml::insert(array(
                    'order_code'         => $data['order_code'],
                    'tracking_number'    => $data['tracking_number'],
                    'sm_code'            => $data['sm_code'],
                    'warehouse_id'       => $data['warehouse_id'],
                    'order_mode'         => $data['order_mode'],
                    'customer_code'      => $data['customer_code'],
                    'order_created_time' => $data['order_created_time'],
                    'created_time'       => $operationTime,
                    'updated_time'       => $operationTime,
                    'xml_type'           => $type,
                    'xml_status'         => 0,
                ));

                /*Service_EportXmlLog::insert(array(
                    'order_code'      => $data['order_code'],
                    'tracking_number' => $data['tracking_number'],
                    'xml_type'        => $type,
                    'xml_path'        => '',
                    'created_time'    => $operationTime,
                    'return_info'     => '已加入发送队列',
                ));*/

                $response['status']  = 1;
                $response['message'] = '物流运单CEB501队列信息已添加';
            }
        }
        catch (Exception $e) {
            $response['message'] = $e->getMessage();

            /*if (200 === $e->getCode()) {
                $response['status'] = 1;
            }*/
        }

        return $response;
    }

    /**
     * 渲染报文
     *
     * @param string $eport
     * @return array
     */
    public static function renderXml(array $eport) {
        $response = array(
            'status'  => 0,
            'message' => '报文类型[' . $eport['xml_type'] . ']不受支持',
        );

        switch ((int) $eport['xml_type']) {
            case self::TYPE_CEB501:
                $response = self::renderCEB501Xml($eport);
                break ;
            case self::TYPE_CEB503:
                $response = self::renderCEB503Xml($eport);
                break ;
            case self::TYPE_CEB301:
                $response = self::renderCEB301Xml($eport);
                break;
            case self::TYPE_CEB601:
                $response = self::renderCEB601Xml($eport);
                break;
            case self::TYPE_CEB303:
                $response = self::renderCEB303Xml($eport);
                break;
            case self::TYPE_CEB403:
                $response = self::renderCEB403Xml($eport);
                break;
            case self::TYPE_CEB505:
                $response = self::renderCEB505Xml($eport);
                break;
            case self::TYPE_CEB507:
                $response = self::renderCEB507Xml($eport);
                break;
            case self::TYPE_CEB509:
                $response = self::renderCEB509Xml($eport);
                break;
            case self::TYPE_CEB603:
                $response = self::renderCEB603Xml($eport);
                break;
            case self::TYPE_CEB607:
                $response = self::renderCEB607Xml($eport);
                break;
            default:
                break ;
        }

        return $response;
    }

    public static function  renderCEB303Xml(array $eport){
        $guid = self::generateGuid(self::TYPE_CEB303, self::COP_CODE);
        $date = self::getDatetime();
        $name = 'SZCPORTCEB303Message_EDI4403660028_E002_' . self::SENDER_ID . '_' . self::RECEIVER_ID . '_' . $date['micro_date'] . mt_rand(1001, 9999);
        $response = array(
            'status'       => 0,
            'message'      => '',
            'guid'         => $guid,
            'message_id'   => $guid,
            'logistics_no' => '',
            'xml_suffix'   => '.xml',
            'xml_name'     => $name,
            'xml_content'  => '',
        );
        try {

            $order = Service_Orders::getByField($eport['order_code'], 'order_code');
            $customerRow = Service_Customer::getByField($order['customer_code'],"customer_code","*");
            $orderProduct = Service_OrderProduct::getByCondition(array('order_code'=>$eport['order_code']),"*");
            $orderList = array();
            $totalValue = 0;
            foreach($orderProduct as $key=>$op){
                $totalValue+=$op['op_quantity']*$op['op_declared_value'];
                $product = Service_Product::getByField($op['product_id'],"product_id","*");
                $hemList = Service_HsElementMap::getByCondition(array('product_id'=>$op['product_id']), 'hem_detail');
                $elements = array();

                foreach($hemList as $hemRow) $elements[] = $hemRow['hem_detail'];
                $gmodel = implode('|',$elements);
                $barCode = strlen($op['product_barcode'])>13?substr($op['product_barcode'],0,13):$op['product_barcode'];
                $ol = array(
                    'gnum'=>$key+1,
                    'itemNo'=>$product['goods_id'],
                    'itemName'=>$product['hs_goods_name'],
                    'itemDescribe'=>$gmodel,
                    'barCode'=>$product['product_barcode'],
                    'unit'=>$product['pu_code'],
                    'currency'=>'502',
                    'qty'=>$op['op_quantity'],
                    'price'=>$op['op_declared_value'],
                    'totalPrice'=>$op['op_quantity']*$op['op_declared_value'],
                    'note'=>'',
                );
                $orderList[] = $ol;
            }

            /*if (empty($order)) {
                throw new Exception('单号[' . $eport['order_code'] . ']不存在');
            }

            $address = Service_OrderAddressBook::getByCondition(array(
                'order_code' => $order['order_code'],'oab_type'=>'0',
            ));

            if (empty($address)) {
                throw new Exception('缺乏地址数据信息');
            }*/
            //$country = Service_Country::getByField($address[0]['oab_country_id'],"country_id","*");

            $CEB303Message = array(

                // 报文体信息
                'Order' => array(
                    // 运单信息
                    'OrderHead' => array(
                        'guid'               => $guid, // 系统唯一序号
                        'appType'            => $eport['app_type'], // 报送类型：1新增、2修改、3删除
                        'appTime'            => $date['normal_date'], // 报送时间，格式：YYYYMMDDhhmmss
                        'appStatus'          => 2, // 业务状态：1暂存、2申报
                        'orderType'        => 'E', // 物流运单编号
                        'orderNo'        => $eport['order_code'],
                        //'orderNo'             =>$order['reference_no'], // 提运单号，直购进口为海运提单、空运总单或汽车载货清单
                        'ebpCode'            => $customerRow['trade_co'], // 运费，无则填0
                        'ebpName'         => $customerRow['trade_name'], // 保价费，无则填0
                        'ebcCode'           => $customerRow['trade_co'], // 币制代码，限定为人民币142
                        'ebcName'             => $customerRow['trade_name'], // 毛重KG
                        'goodsValue'          => $totalValue, // 收件人名称
                        'freight'   => 0, // 运杂费
                        'currency' => 502, // 收件人电话
                        'note'               => '', // 备注
                    ),
                    'OrderList'=>$orderList,
                ),
            );
            $BaseTransfer = array(
                'copCode'=>$customerRow['trade_co'],
                'copName'=>$customerRow['trade_name'],
                'dxpMode'=>'DXP',
                'dxpId'=>'DXPENT0000019508',
                'note'=>'',
            );

            $xml  = '<?xml version="1.0" encoding="UTF-8" ?>' . self::putCrlf();
            $xml .= '<CEB303Message xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.chinaport.gov.cn/ceb" version="1.0" guid="' . $guid . '">' . self::putCrlf();

            $xml .= self::putTab(1) . '<Order>' . self::putCrlf();
            $xml .= self::putTab(2) . '<OrderHead>' . self::putCrlf();
            foreach ($CEB303Message['Order']['OrderHead'] as $node => $value) {
                $xml .= self::putTab(3) . "<{$node}>{$value}</{$node}>" . self::putCrlf();
            }
            $xml .= self::putTab(2) . '</OrderHead>' . self::putCrlf();

            foreach ($CEB303Message['Order']['OrderList'] as $k => $v) {
                $xml .= self::putTab(2) . '<OrderList>' . self::putCrlf();
                foreach($v as $node => $value){
                    $xml .= self::putTab(3) . "<{$node}>{$value}</{$node}>" . self::putCrlf();
                }
                $xml .= self::putTab(2) . '</OrderList>' . self::putCrlf();
            }

            $xml .= self::putTab(1) . '</Order>' . self::putCrlf();
            $xml .= self::putTab(1) . '<BaseTransfer>' . self::putCrlf();
            foreach($BaseTransfer as $node=>$value){
                $xml .= self::putTab(2) . "<{$node}>{$value}</{$node}>" . self::putCrlf();
            }
            $xml .= self::putTab(1) . '</BaseTransfer>' . self::putCrlf();
            $xml .= '</CEB303Message>' . self::putCrlf();

            $response['status']      = 1;
            $response['message']     = '订单报文CEB303Message已生成';
            $response['xml_content'] = $xml;
        }
        catch (Exception $e) {
            $response['message'] = $e->getMessage();
        }

        return $response;
    }

    public static function renderCEB403Xml(array $eport){
        $guid = self::generateGuid(self::TYPE_CEB403, self::COP_CODE);
        $date = self::getDatetime();
        $name = 'SZCPORTCEB403Message_EDI4403660028_E002_' . self::SENDER_ID . '_' . self::RECEIVER_ID . '_' . $date['micro_date'] . mt_rand(1001, 9999);
        $response = array(
            'status'       => 0,
            'message'      => '',
            'guid'         => $guid,
            'message_id'   => $guid,
            'logistics_no' => '',
            'xml_suffix'   => '.xml',
            'xml_name'     => $name,
            'xml_content'  => '',
        );
        try {
            $order = Service_Orders::getByField($eport['order_code'], 'order_code');
            $customerRow = Service_Customer::getByField($order['customer_code'],"customer_code","*");
            $orderProduct = Service_OrderProduct::getByCondition(array('order_code'=>$eport['order_code']),"*");
            //$orderCustomerInfo = Service_OrderCustomInfo::getByField($eport['order_code'], 'order_code',"*");
            $totalValue = 0;
            foreach($orderProduct as $key=>$op){
                $totalValue+=$op['op_quantity']*$op['op_declared_value'];

            }
            $CEB403Message = array(
                'guid'               => $guid,
                'appType'            => $eport['app_type'],
                'appTime'            => $date['normal_date'],
                'appStatus'          => 2,
                'ebpCode'        => $customerRow['trade_co'],
                'ebpName'         => $customerRow['trade_name'],
                'ebcCode'           => $customerRow['trade_co'],
                'ebcName'             => $customerRow['trade_name'],
                'orderNo'        => $eport['order_code'],
                'ebpCode'            => $customerRow['trade_co'],
                'payCode'        => '',
                'payName'        => '现金支付',
                'payNo'          => '',
                'charge'          => $totalValue, // 收件人名称
                'currency'   => 502, // 运杂费
                'accountingDate' => date("YmdHis"), // 收件人电话
                'note'=>'',
            );
            $BaseTransfer = array(
                'copCode'=>$customerRow['trade_co'],
                'copName'=>$customerRow['trade_name'],
                'dxpMode'=>'DXP',
                'dxpId'=>'DXPENT0000019508',
                'note'=>'',
            );

            $xml  = '<?xml version="1.0" encoding="UTF-8" ?>' . self::putCrlf();
            $xml .= '<CEB403Message xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.chinaport.gov.cn/ceb" version="1.0" guid="' . $guid . '">' . self::putCrlf();


            $xml .= self::putTab(1) . '<Receipts>' . self::putCrlf();
            foreach ($CEB403Message as $node => $value) {
                $xml .= self::putTab(2) . "<{$node}>{$value}</{$node}>" . self::putCrlf();
            }
            $xml .= self::putTab(1) . '</Receipts>' . self::putCrlf();

            $xml .= self::putTab(1) . '<BaseTransfer>' . self::putCrlf();
            foreach($BaseTransfer as $node=>$value){
                $xml .= self::putTab(2) . "<{$node}>{$value}</{$node}>" . self::putCrlf();
            }
            $xml .= self::putTab(1) . '</BaseTransfer>' . self::putCrlf();
            $xml .= '</CEB403Message>' . self::putCrlf();

            $response['status']      = 1;
            $response['message']     = '收款单报文CEB403Message已生成';
            $response['xml_content'] = $xml;
        }
        catch (Exception $e) {
            $response['message'] = $e->getMessage();
        }

        return $response;
    }

    public static function renderCEB505Xml(array $eport){
        $guid = self::generateGuid(self::TYPE_CEB505, self::COP_CODE);
        $date = self::getDatetime();
        $name = 'SZCPORTCEB505Message_EDI4403660028_E002_' . self::SENDER_ID . '_' . self::RECEIVER_ID . '_' . $date['micro_date'] . mt_rand(1001, 9999);

        $response = array(
            'status'       => 0,
            'message'      => '',
            'guid'         => $guid,
            'message_id'   => $guid,
            'logistics_no' => '',
            'xml_suffix'   => '.xml',
            'xml_name'     => $name,
            'xml_content'  => '',
        );

        try {

            $order = Service_Orders::getByField($eport['order_code'], 'order_code');
            $shipOrder = Service_ShipOrder::getByField($eport['order_code'], 'order_code',"*");

            if (empty($order)) {
                throw new Exception('单号[' . $eport['order_code'] . ']不存在');
            }

            $address = Service_OrderAddressBook::getByCondition(array(
                'order_code' => $order['order_code'],
            ));

            if (empty($address)) {
                throw new Exception('缺乏地址数据信息');
            }

            //$weight   = $order['grossWt'];
            $address  = $address[0];
            //$country = Service_Country::getByField($address['oab_country_id'],"country_id","*");
            $customerRow = Service_Customer::getByField($order['customer_id'],"customer_id","*");

            $CEB505Message = array(
                'guid'=>$guid,
                'appType'=> $eport['app_type'],
                'appTime'=> $date['normal_date'],
                'appStatus'=>'2',
                'logisticsCode'=>self::COP_CODE,
                'logisticsName'=>self::COP_NAME,
                'logisticsNo'=>$shipOrder['tracking_number'],
                'freight'=>0,
                'insuredFee'=>$order['insurance'],
                'currency'=>'502',
                'grossWeight'=>$shipOrder['so_weight'],
                'packNo'=>1,
                'goodsInfo'=>'包裹',
                //'ebcCode'=>'',
                //'ebcName'=>'',
                'ebcCode'=> $customerRow['trade_co'],
                'ebcName'=> $customerRow['trade_name'],
                'ebcTelephone'=>$customerRow['customer_telephone'],
                'note'=>'',
            );

            $BaseTransfer = array(
                'copCode'=>self::COP_CODE,
                'copName'=>self::COP_NAME,
                'dxpMode'=>'DXP',
                'dxpId'=>'DXPENT0000019508',
                'note'=>'',
            );

            $xml  = '<?xml version="1.0" encoding="UTF-8" ?>' . self::putCrlf();
            $xml .= '<CEB505Message xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.chinaport.gov.cn/ceb" version="1.0" guid="' . $guid . '">' . self::putCrlf();
            $xml .= self::putTab(1) . '<Logistics>' . self::putCrlf();
            foreach ($CEB505Message as $node => $value) {
                $xml .= self::putTab(2) . "<{$node}>{$value}</{$node}>" . self::putCrlf();
            }
            $xml .= self::putTab(1) . '</Logistics>' . self::putCrlf();

            $xml .= self::putTab(1) . '<BaseTransfer>' . self::putCrlf();
            foreach($BaseTransfer as $node=>$value){
                $xml .= self::putTab(2) . "<{$node}>{$value}</{$node}>" . self::putCrlf();
            }
            $xml .= self::putTab(1) . '</BaseTransfer>' . self::putCrlf();

            $xml .= '</CEB505Message>' . self::putCrlf();

            $response['status']      = 1;
            $response['message']     = '物流运单报文CEB505已生成';
            $response['xml_content'] = $xml;
        }
        catch (Exception $e) {
            $response['message'] = $e->getMessage();
        }

        return $response;
    }

    public static function renderCEB507Xml(array $eport){
        $guid = self::generateGuid(self::TYPE_CEB507, self::COP_CODE);
        $date = self::getDatetime();
        $name = 'SZCPORTCEB507Message_EDI4403660028_E002_' . self::SENDER_ID . '_' . self::RECEIVER_ID . '_' . $date['micro_date'] . mt_rand(1001, 9999);

        $response = array(
            'status'       => 0,
            'message'      => '',
            'guid'         => $guid,
            'message_id'   => $guid,
            'logistics_no' => '',
            'xml_suffix'   => '.xml',
            'xml_name'     => $name,
            'xml_content'  => '',
        );

        try {
            /*$receivingRow = Service_Receiving::getByField($eport['receiving_code'],"receiving_code","*");

            if (empty($address)) {
                throw new Exception('缺乏地址数据信息');
            }*/

            //$weight   = $order['grossWt'];
            //$address  = $address[0];
            //$country = Service_Country::getByField($address['oab_country_id'],"country_id","*");
            //$customerRow = Service_Customer::getByField($receivingRow['customer_id'],"customer_id","*");
            $obd = Service_OutboundBagDetail::getByField($eport['order_code'],"order_code","*");
            $shipBatchDetail = Service_ShipBatchDetail::getByField($obd['ob_no'],"ob_no","*");
            $shipBatchAttribute = Service_ShipBatchAttribute::getByField($shipBatchDetail['sb_code'],"sb_code","*");

            $CEB507Message = array(
                'guid'=>$guid,
                'appType'=> $eport['app_type'],
                'appTime'=> $date['normal_date'],
                'appStatus'=>'2',
                'customsCode'=>$shipBatchAttribute['ie_port'],
                'copNo'=>"YD".$eport['order_code'],
                'operatorCode'=>'440366K002',
                'operatorName'=>'深圳市前海湾仓储服务有限公司',
                'loctNo'=>'',
                'ieFlag'=>'E',
                'trafMode'=>'4',
                'billNo'=>'BN'.$eport['order_code'],
                'domesticTrafNo'=>$shipBatchAttribute['voyage_no'],
                'logisticsCode'=>self::COP_CODE,
                'logisticsName'=>self::COP_NAME,
                'msgCount'=>'1',
                'msgSeqNo'=>'1',
                'note'=>'',
            );

            $shipOrder = Service_ShipOrder::getByField($eport['order_code'],"order_code");
            $Avl = array(
                'gnum'=>1,
                'logisticsNo'=>$shipOrder['tracking_number'],
                'totalPackageNo'=>'1',
                'note'=>'',
            );
            /*$Arrivallist = array(
                'gnum'=>1,
                'logisticsNo'=>'',
                'totalPackageNo'=>'',
                'note'=>'',
            );*/

            $BaseTransfer = array(
                'copCode'=>'440366K002',
                'copName'=>'深圳市前海湾仓储服务有限公司',
                'dxpMode'=>'DXP',
                'dxpId'=>'DXPENT0000019508',
                'note'=>'',
            );

            $xml  = '<?xml version="1.0" encoding="UTF-8" ?>' . self::putCrlf();
            $xml .= '<CEB507Message xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.chinaport.gov.cn/ceb" version="1.0" guid="' . $guid . '">' . self::putCrlf();
            $xml .= self::putTab(1) . '<Arrival>' . self::putCrlf();
            $xml .= self::putTab(2) . '<ArrivalHead>' . self::putCrlf();
            foreach ($CEB507Message as $node => $value) {
                $xml .= self::putTab(3) . "<{$node}>{$value}</{$node}>" . self::putCrlf();
            }
            $xml .= self::putTab(2) . '</ArrivalHead>' . self::putCrlf();
            $xml .= self::putTab(2) . '<ArrivalList>' . self::putCrlf();
            foreach ($Avl as $node => $value) {
                $xml .= self::putTab(3) . "<{$node}>{$value}</{$node}>" . self::putCrlf();
            }
            $xml .= self::putTab(2) . '</ArrivalList>' . self::putCrlf();
            $xml .= self::putTab(1) . '</Arrival>' . self::putCrlf();

            $xml .= self::putTab(1) . '<BaseTransfer>' . self::putCrlf();
            foreach($BaseTransfer as $node=>$value){
                $xml .= self::putTab(2) . "<{$node}>{$value}</{$node}>" . self::putCrlf();
            }
            $xml .= self::putTab(1) . '</BaseTransfer>' . self::putCrlf();

            $xml .= '</CEB507Message>' . self::putCrlf();

            $response['status']      = 1;
            $response['message']     = '运抵单报文CEB507已生成';
            $response['xml_content'] = $xml;
        }
        catch (Exception $e) {
            $response['message'] = $e->getMessage();
        }

        return $response;
    }

    public static function renderCEB509Xml(array $eport){
        $guid = self::generateGuid(self::TYPE_CEB509, self::COP_CODE);
        $date = self::getDatetime();
        $name = 'SZCPORTCEB509Message_EDI4403660028_E002_' . self::SENDER_ID . '_' . self::RECEIVER_ID . '_' . $date['micro_date'] . mt_rand(1001, 9999);
        $response = array(
            'status'       => 0,
            'message'      => '',
            'guid'         => $guid,
            'message_id'   => $guid,
            'logistics_no' => '',
            'xml_suffix'   => '.xml',
            'xml_name'     => $name,
            'xml_content'  => '',
        );

        try {

            $order = Service_Orders::getByField($eport['order_code'], 'order_code');
            $shipOrder = Service_ShipOrder::getByField($eport['order_code'], 'order_code',"*");
            $obd = Service_OutboundBagDetail::getByField($eport['order_code'], 'order_code',"*");
            $shipBatchDetail = Service_ShipBatchDetail::getByField($obd['ob_no'],'ob_no',"*");
            $shipBatchAttribute = Service_ShipBatchAttribute::getByField($shipBatchDetail['sb_code'],"sb_code","*");
            $orderCustomerInfo = Service_OrderCustomInfo::getByField($eport['order_code'], 'order_code',"*");


            $xml = '<?xml version="1.0" encoding="UTF-8"?>'.
'<CEB509Message guid="' . $guid . '" version="1.0"  xmlns="http://www.chinaport.gov.cn/ceb" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'.
	'<Departure>'.
		'<DepartureHead>'.
			'<guid>'.$guid.'</guid>'.
			'<appType>'.$eport['app_type'].'</appType>'.
			'<appTime>'.$date['normal_date'].'</appTime>'.
			'<appStatus>2</appStatus>'.
			'<customsCode>5349</customsCode>'.
			'<copNo>'.$orderCustomerInfo['l_cop_no'].'</copNo>'.
			'<logisticsCode>'.self::COP_CODE.'</logisticsCode>'.
			'<logisticsName>'.self::COP_NAME.'</logisticsName>'.
			'<trafMode>4</trafMode>'.
			'<trafName>4</trafName>'.
			'<voyageNo>ZGG66</voyageNo>'.
			'<billNo>BH'.$eport['order_code'].'</billNo>'.
			'<leaveTime>'.$date['normal_date'].'</leaveTime>'.
			'<msgCount>1</msgCount>'.
			'<msgSeqNo>1</msgSeqNo>'.
			'<note></note>'.
		'</DepartureHead>'.
		'<DepartureList>'.
			'<gnum>1</gnum>'.
			'<totalPackageNo>1</totalPackageNo>'.
			'<logisticsNo>'.$shipOrder['tracking_number'].'</logisticsNo>'.
			'<note></note>'.
		'</DepartureList>'.
	'</Departure>'.
	'<BaseTransfer>'.
		'<copCode>'.self::COP_CODE.'</copCode>'.
		'<copName>'.self::COP_NAME.'</copName>'.
		'<dxpMode>DXP</dxpMode>'.
		'<dxpId>DXPENT0000019508</dxpId>'.
		'<note></note>'.
	'</BaseTransfer>'.
'</CEB509Message>';

            $response['status']      = 1;
            $response['message']     = '离境单报文CEB509已生成';
            $response['xml_content'] = $xml;
        }
        catch (Exception $e) {
            $response['message'] = $e->getMessage();
        }

        return $response;

    }

    public static function renderCEB603Xml(array $eport){
        $guid = self::generateGuid(self::TYPE_CEB603, self::COP_CODE);
        $date = self::getDatetime();
        $name = 'SZCPORTCEB603Message_EDI4403660028_E002_' . self::SENDER_ID . '_' . self::RECEIVER_ID . '_' . $date['micro_date'] . mt_rand(1001, 9999);
        $response = array(
            'status'       => 0,
            'message'      => '',
            'guid'         => $guid,
            'message_id'   => $guid,
            'logistics_no' => '',
            'xml_suffix'   => '.xml',
            'xml_name'     => $name,
            'xml_content'  => '',
        );

        try {

            $order = Service_Orders::getByField($eport['order_code'], 'order_code',"*");
            $shipOrder = Service_ShipOrder::getByField($eport['order_code'], 'order_code',"*");
            //$netWeight = Service_OrderProduct::calNetWeightByCondition(array('order_code'=>$eport['order_code']));
            $obd = Service_OutboundBagDetail::getByField($eport['order_code'], 'order_code',"*");
            $shipBatchDetail = Service_ShipBatchDetail::getByField($obd['ob_no'],'ob_no',"*");
            $shipBatchAttribute = Service_ShipBatchAttribute::getByField($shipBatchDetail['sb_code'],"sb_code","*");
            $orderCustomerInfo = Service_OrderCustomInfo::getByField($eport['order_code'], 'order_code',"*");
            //$shipBatch = Service_ShipBatch::getByField($eport['order_code'],'sb_code',"*");

            /*if (empty($order)) {
                throw new Exception('单号[' . $eport['order_code'] . ']不存在');
            }

            if (empty($address)) {
                throw new Exception('缺乏地址数据信息');
            }*/

            //$weight   = $order['grossWt'];
            $address = Service_OrderAddressBook::getByCondition(array(
                'order_code' => $order['order_code'],
                'oab_type'=>0,
            ));
            $address  = $address[0];
            $country = Service_Country::getByField($address['oab_country_id'],"country_id","*");
            $customerRow = Service_Customer::getByField($order['customer_id'],"customer_id","*");

            $InventoryList = array(

            );
            $netWeight = 0;
            $orderProduct = Service_OrderProduct::getByCondition(array('order_code'=>$eport['order_code']),"*");
            $index = 1;
            foreach($orderProduct as $key=>$op){
                $product = Service_Product::getByField($op['product_id'],"product_id","*");
                $netWeight+=$product['product_weight']*$op['op_quantity'];
                $hemList = Service_HsElementMap::getByCondition(array('product_id'=>$op['product_id']), 'hem_detail');
                $hsUomMap = Service_HsUomMap::getByField($op['product_id'],"product_id","*");
                $hsUom = Service_HsUom::getByField($product['hs_code'],'hs_code','*');
                $elements = array();
                foreach($hemList as $hemRow) {
                    $hem_detail = trim($hemRow['hem_detail']);
                    if($hem_detail===""){
                        $elements[] = "";
                    }else{
                        $elements[] = $hem_detail ;
                    }
                    //$elements[] = $hem_detail ? $hem_detail : '';
                }
                $qty2 = $hsUomMap['hum_quantity_second']*$op['op_quantity'];
                if($qty2==0){
                    $qty2 = "";
                }
                if($hsUom['pu_code_second']==""){
                    $Ivl = array(
                        'gnum'=>$index,
                        'itemNo'=>$product['goods_id'],
                        'itemRecordNo'=>$product['goods_id'],
                        'itemName'=>$product['hs_goods_name'],
                        'gcode'=>$product['hs_code'],
                        'gname'=>$product['hs_goods_name'],
                        'gmodel'=>implode('|',$elements),
                        'barCode'=>$product['product_barcode'],
                        'country'=>$country['trade_country'],
                        'currency'=>'502',
                        'qty'=>$op['op_quantity'],
                        'qty1'=>$hsUomMap['hum_quantity_law']*$op['op_quantity'],
                        //'qty2'=>$qty2,
                        'unit'=>$product['pu_code'],
                        'unit1'=>$hsUom['pu_code_law'],
                        //'unit2'=>$hsUom['pu_code_second'],
                        'price'=>$op['op_declared_value'],
                        'totalPrice'=>$op['op_declared_value']*$op['op_quantity'],
                        'note'=>''
                    );
                }else{
                    $Ivl = array(
                        'gnum'=>$index,
                        'itemNo'=>$product['goods_id'],
                        'itemRecordNo'=>$product['goods_id'],
                        'itemName'=>$product['hs_goods_name'],
                        'gcode'=>$product['hs_code'],
                        'gname'=>$product['hs_goods_name'],
                        'gmodel'=>implode('|',$elements),
                        'barCode'=>$product['product_barcode'],
                        'country'=>$country['trade_country'],
                        'currency'=>'502',
                        'qty'=>$op['op_quantity'],
                        'qty1'=>$hsUomMap['hum_quantity_law']*$op['op_quantity'],
                        'qty2'=>$qty2,
                        'unit'=>$product['pu_code'],
                        'unit1'=>$hsUom['pu_code_law'],
                        'unit2'=>$hsUom['pu_code_second'],
                        'price'=>$op['op_declared_value'],
                        'totalPrice'=>$op['op_declared_value']*$op['op_quantity'],
                        'note'=>''
                    );
                }

                $InventoryList[] = $Ivl;
                $index++;
            }
            /*if($netWeight>=$shipOrder['so_weight']){
                //$swapWeight = $netWeight;
                $netWeight = $shipOrder['so_weight']- 0.02;
                //$shipOrder['so_weight'] = $swapWeight;
            }*/

            $CEB603Message = array(
                'guid'=>$guid,
                'appType'=> $eport['app_type'],
                'appTime'=> $date['normal_date'],
                'appStatus'=>'2',
                'customsCode'=>5349,
                'ebpCode'=> $customerRow['trade_co'],
                'ebpName'=> $customerRow['trade_name'],
                'orderNo'=>$eport['order_code'],
                'logisticsCode'=>self::COP_CODE,
                'logisticsName'=>self::COP_NAME,
                'logisticsNo'=>$shipOrder['tracking_number'],
                'copNo'=>$orderCustomerInfo['qd_cop_no'],
                'ieFlag'=>'E',
                'portCode'=>$shipBatchAttribute['ie_port'],
                'ieDate'=>date("Ymd"),
                'statisticsFlag'=>'B',
                'agentCode'=> $customerRow['trade_co'],
                'agentName'=> $customerRow['trade_name'],
                'ebcCode'=> $customerRow['trade_co'],
                'ebcName'=> $customerRow['trade_name'],
                'ownerCode'=> $customerRow['trade_co'],
                'ownerName'=> $customerRow['trade_name'],
                'iacCode'=>'',
                'iacName'=>'',
                'emsNo'=>'T5349W000118',
                'tradeMode'=>'1210',
                'trafMode'=>'4',
                'trafName'=>'',
                'voyageNo'=>'',
                'billNo'=>'',
                'totalPackageNo'=>'',
                'loctNo'=>'',
                'licenseNo'=>'',
                'country'=>$country['trade_country'],
                'POD'=>$country['trade_country'],
                'freight'=>$shipOrder['so_shipping_fee'],
                'fCurrency'=>'142',
                'fFlag'=>'3',
                'insuredFee'=>'0',
                'iCurrency'=>'142',
                'iFlag'=>'3',
                'wrapType'=>'7',
                'packNo'=>1,
                'grossWeight'=>$shipOrder['so_weight'],
                'netWeight'=>$netWeight,
                'note'=>'',
            );


            $BaseTransfer = array(
                'copCode'=>$customerRow['trade_co'],
                'copName'=>$customerRow['trade_name'],
                'dxpMode'=>'DXP',
                'dxpId'=>'DXPENT0000019508',
                'note'=>'',
            );

            $xml  = '<?xml version="1.0" encoding="UTF-8" ?>' . self::putCrlf();
            $xml .= '<CEB603Message xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.chinaport.gov.cn/ceb" version="1.0" guid="' . $guid . '">' . self::putCrlf();
            $xml .= self::putTab(1) . '<Inventory>' . self::putCrlf();
            $xml .= self::putTab(2) . '<InventoryHead>' . self::putCrlf();
            foreach ($CEB603Message as $node => $value) {
                $xml .= self::putTab(2) . "<{$node}>{$value}</{$node}>" . self::putCrlf();
            }
            $xml .= self::putTab(2) . '</InventoryHead>' . self::putCrlf();

            foreach ($InventoryList as $key => $list) {
                $xml .= self::putTab(2) . '<InventoryList>' . self::putCrlf();
                foreach($list as $node=>$value){
                    $xml .= self::putTab(3) . "<{$node}>{$value}</{$node}>" . self::putCrlf();
                }
                $xml .= self::putTab(2) . '</InventoryList>' . self::putCrlf();
            }
            $xml .= self::putTab(1) . '</Inventory>' . self::putCrlf();

            $xml .= self::putTab(1) . '<BaseTransfer>' . self::putCrlf();
            foreach($BaseTransfer as $node=>$value){
                $xml .= self::putTab(2) . "<{$node}>{$value}</{$node}>" . self::putCrlf();
            }
            $xml .= self::putTab(1) . '</BaseTransfer>' . self::putCrlf();

            $xml .= '</CEB603Message>' . self::putCrlf();

            $response['status']      = 1;
            $response['message']     = '出口清单报文CEB603已生成';
            $response['xml_content'] = $xml;
        }
        catch (Exception $e) {
            $response['message'] = $e->getMessage();
        }

        return $response;

    }

    public static function renderCEB607Xml(array $eport){
        $guid = self::generateGuid(self::TYPE_CEB607, self::COP_CODE);
        $date = self::getDatetime();
        $name = 'SZCPORTCEB607Message_EDI4403660028_E002_' . self::SENDER_ID . '_' . self::RECEIVER_ID . '_' . $date['micro_date'] . mt_rand(1001, 9999);

        $response = array(
            'status'       => 0,
            'message'      => '',
            'guid'         => $guid,
            'message_id'   => $guid,
            'logistics_no' => '',
            'xml_suffix'   => '.xml',
            'xml_name'     => $name,
            'xml_content'  => '',
        );

        try {

            $obd = Service_OutboundBagDetail::getByField($eport['order_code'],"order_code","*");
            $shipBatchDetail = Service_ShipBatchDetail::getByField($obd['ob_no'],"ob_no","*");
            $shipBatchAttribute = Service_ShipBatchAttribute::getByField($shipBatchDetail['sb_code'],"sb_code","*");
            $order = Service_Orders::getByField($eport['order_code'], 'order_code');
            $customerRow = Service_Customer::getByField($order['customer_id'],"customer_id","*");
            $shipOrder = Service_ShipOrder::getByField($eport['order_code'], 'order_code',"*");
            $orderCustomerInfo = Service_OrderCustomInfo::getByField($eport['order_code'], 'order_code',"*");

            $xml = '<?xml version="1.0" encoding="UTF-8"?>'.
'<CEB607Message guid="' . $guid . '" version="1.0"  xmlns="http://www.chinaport.gov.cn/ceb" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'.
	'<WayBill>'.
		'<WayBillHead>'.
			'<guid>' . $guid . '</guid>'.
			'<appType>'.$eport['app_type'].'</appType>'.
			'<appTime>'.$date['normal_date'].'</appTime>'.
			'<appStatus>2</appStatus>'.
			'<customsCode>5349</customsCode>'.
			'<copNo>'.$orderCustomerInfo['zfd_cop_no'].'</copNo>'.
			'<agentCode>'.$customerRow['trade_co'].'</agentCode>'.
			'<agentName>'.$customerRow['trade_name'].'</agentName>'.
			'<loctNo></loctNo>'.
			'<trafMode>4</trafMode>'.
			'<trafName>4</trafName>'.
			'<voyageNo>'.$shipBatchAttribute['voyage_no'].'</voyageNo>'.
			'<billNo>BH'.$eport['order_code'].'</billNo>'.
			//'<domesticTrafNo></domesticTrafNo>'.
			'<grossWeight>'.$shipOrder['so_weight'].'</grossWeight>'.
			'<logisticsCode>'.self::COP_CODE.'</logisticsCode>'.
			'<logisticsName>'.self::COP_NAME.'</logisticsName>'.
			'<msgCount>1</msgCount>'.
			'<msgSeqNo>1</msgSeqNo>'.
			'<note></note>'.
		'</WayBillHead>'.
		'<WayBillList>'.
			'<gnum>1</gnum>'.
			'<totalPackageNo>1</totalPackageNo>'.
			'<logisticsNo>'.$shipOrder['tracking_number'].'</logisticsNo>'.
			'<note></note>'.
		'</WayBillList>'.
	'</WayBill>'.
	'<BaseTransfer>'.
		'<copCode>'.$customerRow['trade_co'].'</copCode>'.
		'<copName>'.$customerRow['trade_name'].'</copName>'.
		'<dxpMode>DXP</dxpMode>'.
		'<dxpId>DXPENT0000019508</dxpId>'.
		'<note></note>'.
	'</BaseTransfer>'.
'</CEB607Message>';

            $response['status']      = 1;
            $response['message']     = '清单总分单报文CEB607已生成';
            $response['xml_content'] = $xml;
        }
        catch (Exception $e) {
            $response['message'] = $e->getMessage();
        }

        return $response;
    }

    /**
     * 渲染物流运单报文CEB511
     *
     * @param string $eport
     * @return array
     */
    public static function renderCEB501Xml(array $eport) {
        $guid = self::generateGuid(self::TYPE_CEB501, self::COP_CODE);
        $date = self::getDatetime();
        $name = 'CEE_CEB501_' . self::SENDER_ID . '_' . self::RECEIVER_ID . '_' . $date['micro_date'] . mt_rand(1001, 9999);

        $response = array(
            'status'       => 0,
            'message'      => '',
            'guid'         => $guid,
            'message_id'   => $guid,
            'logistics_no' => '',
            'xml_suffix'   => '.xml',
            'xml_name'     => $name,
            'xml_content'  => '',
        );

        try {

            $order = Service_Orders::getByField($eport['order_code'], 'order_code');
            $shipOrder = Service_ShipOrder::getByField($eport['order_code'], 'order_code',"*");

            if (empty($order)) {
                throw new Exception('单号[' . $eport['order_code'] . ']不存在');
            }

            $address = Service_OrderAddressBook::getByCondition(array(
                'order_code' => $order['order_code'],
            ));

            if (empty($address)) {
                throw new Exception('缺乏地址数据信息');
            }

            $weight   = $order['grossWt'];
            $address  = $address[0];
            $country = Service_Country::getByField($address['oab_country_id'],"country_id","*");
            $customerRow = Service_Customer::getByField($order['customer_id'],"customer_id","*");

            if (0 === (int) $order['order_mode_type']) { // 网购保税按产品重量计算
                $weight = number_format(Service_OrderProduct::getOrderNetWeight($eport['order_code']), 4, '.', '') + 0.15;
            }

            $CEB511Message = array(
                // 报文头信息
                'MessageHead' => array(
                    'MessageID'          => $guid, // 报文唯一编号
                    'MessageType'        => 'CEB501', // 报文类型：CEB511物流运单
                    'OrgCode'            => self::ORG_CODE, // 企业组织机构代码或统一社会信用代码
                    'CopCode'            => self::COP_CODE, // $shippingMethod['logistics_code'], // 传输企业代码
                    'CopName'            => self::COP_NAME, // $shippingMethod['logistics_name'], // 传输企业名称
                    'SenderID'           => self::SENDER_ID, // 发送方企业客户端ID号
                    'ReceiverID'         => self::RECEIVER_ID, // 接收方
                    'ReceiverDepartment' => self::RECEIVER_DEPARTMENT, // 报文发送的监管单位：C海关、Q检验检疫
                    'SendTime'           => $date['micro_date'], // 发送时间，格式：yyyyMMddHHmmssSSS
                    'Version'            => self::VERSION, // 默认：1.0
                ),

                // 报文体信息
                'Logistics' => array(
                    // 运单信息
                    'LogisticsHead' => array(
                        'guid'               => $guid, // 系统唯一序号
                        'customsCode'       =>"",
                        'appType'            => $eport['app_type'], // 报送类型：1新增、2修改、3删除
                        'appTime'            => $date['normal_date'], // 报送时间，格式：YYYYMMDDhhmmss
                        'appStatus'          => 2, // 业务状态：1暂存、2申报
                        'appUid'              =>self::appUid,
                        'appUname'           =>self::appUname,
                        'orderNo'            =>$order['reference_no'],
                        'ebpCode'            =>$customerRow['trade_co'],
                        'ebpName'            =>$customerRow['trade_name'],
                        'logisticsCode'      => self::COP_CODE, // $shippingMethod['logistics_code'], // 物流企业代码
                        'logisticsName'      => self::COP_NAME, // $shippingMethod['logistics_name'], // 物流企业名称
                        'logisticsNo'        => $eport['tracking_number'], // 物流运单编号
                        'ieFlag'             =>'E',
                        'trafMode'           =>'4',
                        'trafName'           =>'1210',
                        'voyageNo'           =>'',
                        'billNo'             => $shipOrder['tracking_number'], // 货物提单或运单的编号；同报关单填制规范。
                        'freight'            => 0, // 运费，无则填0
                        'insuredFee'         => 0, // 保价费，无则填0
                        'currency'           => 502, // 币制代码，限定为人民币142
                        'weight'             => $shipOrder['so_weight'], // 毛重KG
                        'netWt'              =>$weight,
                        'packNo'             => 1, // 件数
                        'parcelInfo'        =>mb_substr(trim(str_replace(array('<br/>', '&', '<', '>', '"', '\''), '', $order['parcel_contents'])), 0, 100, 'UTF-8'),
                        'goodsInfo'          => mb_substr(trim(str_replace(array('<br/>', '&', '<', '>', '"', '\''), '', $order['parcel_contents'])), 0, 100, 'UTF-8'), // 主要货物信息，包括商品名称、数量等
                        'consignee'          => trim($address['oab_lastname']) . $address['oab_firstname'], // 收件人名称
                        'consigneeAddress'   => $address['oab_street_address1'] . trim($address['oab_street_address2']), // 收件人住址
                        'consigneeTelephone' => $address['oab_phone'], // 收件人电话
                        'consigneeCountry'   => $country['trade_country'], // 收件人所在国
                        'shipper'  => trim($customerRow['customer_lastname'].$customerRow['customer_firstname']), // 收件人省份，行政区划代码
                        'shipperAddress'      => trim($customerRow['customer_address']), // 收件人城市，行政区划代码
                        'shipperTelephone'  => trim($customerRow['customer_telephone']), // 收件人县区，行政区划代码
                        'shipperCountry'     =>142,
                        'note'               => '', // 备注
                    ),
                ),
            );

            $xml  = '<?xml version="1.0" encoding="UTF-8" ?>' . self::putCrlf();
            $xml .= '<CEB501Message xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.chinaport.gov.cn/ceb" version="1.0" guid="' . $guid . '">' . self::putCrlf();
            $xml .= self::putTab(1) . '<MessageHead>' . self::putCrlf();

            foreach ($CEB511Message['MessageHead'] as $node => $value) {
                $xml .= self::putTab(2) . "<{$node}>{$value}</{$node}>" . self::putCrlf();
            }

            $xml .= self::putTab(1) . '</MessageHead>' . self::putCrlf();
            //$xml .= self::putTab(1) . '<Logistics>' . self::putCrlf();
            $xml .= self::putTab(1) . '<LogisticsHead>' . self::putCrlf();

            foreach ($CEB511Message['Logistics']['LogisticsHead'] as $node => $value) {
                $xml .= self::putTab(2) . "<{$node}>{$value}</{$node}>" . self::putCrlf();
            }

            $xml .= self::putTab(1) . '</LogisticsHead>' . self::putCrlf();
            //$xml .= self::putTab(1) . '</Logistics>' . self::putCrlf();
            $xml .= '</CEB501Message>' . self::putCrlf();

            $response['status']      = 1;
            $response['message']     = '物流运单报文CEB501已生成';
            $response['xml_content'] = $xml;
        }
        catch (Exception $e) {
            $response['message'] = $e->getMessage();
        }

        return $response;
    }

    /**
     * 渲染运单状态报文CEB513
     *
     * @param array $eport
     * @return array
     */
    public static function renderCEB503Xml(array $eport) {
        $guid = self::generateGuid(self::TYPE_CEB503, self::COP_CODE);
        $date = self::getDatetime();
        $name = 'CEE_CEB503_' . self::SENDER_ID . '_' . self::RECEIVER_ID . '_' . $date['micro_date'] . mt_rand(1001, 9999);

        $response = array(
            'status'       => 0,
            'message'      => '',
            'guid'         => $guid,
            'message_id'   => $guid,
            'logistics_no' => $eport['tracking_number'],
            'xml_suffix'   => '.xml',
            'xml_name'     => $name,
            'xml_content'  => '',
        );

        try {
            /*$shippingMethod = Service_ShippingMethod::getByField($eport['sm_code'], 'sm_code');

            if (empty($shippingMethod)) {
              throw new Exception('运输代码[' . $eport['sm_code'] . ']缺乏数据信息');
            }*/

            $CEB503Message = array(
                // 报文头信息
                'MessageHead' => array(
                    'MessageID'          => $guid, // 报文唯一编号
                    'MessageType'        => 'CEB503', // 报文类型：CEB513运单状态
                    'OrgCode'            => self::ORG_CODE, // 企业组织机构代码或统一社会信用代码
                    'CopCode'            => self::COP_CODE, // $shippingMethod['logistics_code'], // 传输企业代码
                    'CopName'            => self::COP_NAME, // $shippingMethod['logistics_name'], // 传输企业名称
                    'SenderID'           => self::SENDER_ID, // 发送方企业客户端ID号
                    'ReceiverID'         => self::RECEIVER_ID, // 接收方
                    'ReceiverDepartment' => self::RECEIVER_DEPARTMENT, // 报文发送的监管单位：C海关
                    'SendTime'           => $date['micro_date'], // 发送时间，格式：yyyyMMddHHmmssSSS
                    'Version'            => self::VERSION, // 默认：1.0
                ),

                // 运单状态信息
                'LogisticsStatus' => array(
                    'guid'            => $guid, // 系统唯一序号
                    'appType'         => $eport['app_type'], // 报送类型：1新增、2修改、3删除
                    'appTime'         => $date['normal_date'], // 报送时间，格式：YYYYMMDDhhmmss
                    'appStatus'       => 2, // 业务状态：1暂存、2申报
                    'logisticsCode'   => self::COP_CODE, // $shippingMethod['logistics_code'], // 物流企业代码
                    'logisticsName'   => self::COP_NAME, // $shippingMethod['logistics_name'], // 物流企业名称
                    'logisticsNo'     => $eport['tracking_number'], // 物流运单编号
                    'logisticsStatus' => 'S', // 物流签收状态，限定S
                    'logisticsTime'   => str_replace(array('-', ':', ' '), '', $eport['signed_time']), // 物流状态发生的实际时间，格式：YYYYMMDDhhmmss
                    'note'            => '', // 备注
                ),
            );

            $xml  = '<?xml version="1.0" encoding="UTF-8" ?>' . self::putCrlf();
            $xml .= '<CEB503Message xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.chinaport.gov.cn/ceb" version="1.0" guid="' . $guid . '">' . self::putCrlf();
            $xml .= self::putTab(1) . '<MessageHead>' . self::putCrlf();

            foreach ($CEB503Message['MessageHead'] as $node => $value) {
                $xml .= self::putTab(2) . "<{$node}>{$value}</{$node}>" . self::putCrlf();
            }

            $xml .= self::putTab(1) . '</MessageHead>' . self::putCrlf();
            $xml .= self::putTab(1) . '<LogisticsStatus>' . self::putCrlf();

            foreach ($CEB503Message['LogisticsStatus'] as $node => $value) {
                $xml .= self::putTab(2) . "<{$node}>{$value}</{$node}>" . self::putCrlf();
            }

            $xml .= self::putTab(1) . '</LogisticsStatus>' . self::putCrlf();
            $xml .= '</CEB503Message>' . self::putCrlf();

            $response['status']      = 1;
            $response['message']     = '运单状态报文CEB503已生成';
            $response['xml_content'] = $xml;
        }
        catch (Exception $e) {
            $response['message'] = $e->getMessage();
        }

        return $response;
    }

    public static function renderCEB301Xml(array $eport){
        $guid = self::generateGuid(self::TYPE_CEB301, self::COP_CODE);
        $date = self::getDatetime();
        $name = 'CEE_CEB301_' . self::SENDER_ID . '_' . self::RECEIVER_ID . '_' . $date['micro_date'] . mt_rand(1001, 9999);

        $response = array(
            'status'       => 0,
            'message'      => '',
            'guid'         => $guid,
            'message_id'   => $guid,
            'logistics_no' => '',
            'xml_suffix'   => '.xml',
            'xml_name'     => $name,
            'xml_content'  => '',
        );

        try {
            /*$shippingMethod = Service_ShippingMethod::getByField($eport['sm_code'], 'sm_code');

            if (empty($shippingMethod)) {
              throw new Exception('运输代码[' . $eport['sm_code'] . ']缺乏数据信息');
            }*/

            $order = Service_Orders::getByField($eport['order_code'], 'order_code');
            $customerRow = Service_Customer::getByField($order['customer_code'],"customer_code","*");
            $orderProduct = Service_OrderProduct::getByCondition(array('order_code'=>$eport['order_code']),"*");
            $orderList = array();
            $totalValue = 0;
            foreach($orderProduct as $key=>$op){
                $totalValue+=$op['op_quantity']*$op['op_declared_value'];
                $product = Service_Product::getByField($op['product_id'],"product_id","*");
                $hemList = Service_HsElementMap::getByCondition(array('product_id'=>$op['product_id']), 'hem_detail');
                $elements = array();

                foreach($hemList as $hemRow) $elements[] = $hemRow['hem_detail'];
                $gmodel = implode('|',$elements);
                $barCode = strlen($op['product_barcode'])>13?substr($op['product_barcode'],0,13):$op['product_barcode'];
                $ol = array(
                    'gnum'=>$key+1,
                    'itemNo'=>$product['product_sku'],
                    'gno'=>'N',
                    'gcode'=>$product['hs_code'],
                    'gname'=>$product['hs_goods_name'],
                    'gmodel'=>$gmodel,
                    'barCode'=>$barCode,
                    'brand'=>'无',
                    'unit'=>$product['pu_code'],
                    'currency'=>'502',
                    'qty'=>$op['op_quantity'],
                    'price'=>$op['op_declared_value'],
                    'total'=>$op['op_quantity']*$op['op_declared_value'],
                    'giftFlag'=>'0',
                    'note'=>'',
                );
                $orderList[] = $ol;
            }

            if (empty($order)) {
                throw new Exception('单号[' . $eport['order_code'] . ']不存在');
            }

            $address = Service_OrderAddressBook::getByCondition(array(
                'order_code' => $order['order_code'],'oab_type'=>'0',
            ));

            if (empty($address)) {
                throw new Exception('缺乏地址数据信息');
            }
            $country = Service_Country::getByField($address[0]['oab_country_id'],"country_id","*");

            $CEB511Message = array(
                // 报文头信息
                'MessageHead' => array(
                    'MessageID'          => $guid, // 报文唯一编号
                    'MessageType'        => 'CEB301', // 报文类型：CEB511物流运单
                    'OrgCode'            => self::ORG_CODE, // 企业组织机构代码或统一社会信用代码
                    'CopCode'            => self::COP_CODE, // $shippingMethod['logistics_code'], // 传输企业代码
                    'CopName'            => self::COP_NAME, // $shippingMethod['logistics_name'], // 传输企业名称
                    'SenderID'           => self::SENDER_ID, // 发送方企业客户端ID号
                    'ReceiverID'         => self::RECEIVER_ID, // 接收方
                    'ReceiverDepartment' => self::RECEIVER_DEPARTMENT, // 报文发送的监管单位：C海关、Q检验检疫
                    'SendTime'           => $date['micro_date'], // 发送时间，格式：yyyyMMddHHmmssSSS
                    'Version'            => self::VERSION, // 默认：1.0
                ),

                // 报文体信息
                'Order' => array(
                    // 运单信息
                    'OrderHead' => array(
                        'guid'               => $guid, // 系统唯一序号
                        'appType'            => $eport['app_type'], // 报送类型：1新增、2修改、3删除
                        'appTime'            => $date['normal_date'], // 报送时间，格式：YYYYMMDDhhmmss
                        'appStatus'          => 2, // 业务状态：1暂存、2申报
                        'appUid'      => self::appUid, // $shippingMethod['logistics_code'], // 物流企业代码
                        'appUname'      => self::appUname, // $shippingMethod['logistics_name'], // 物流企业名称
                        'orderType'        => 'E', // 物流运单编号
                        'orderNo'             =>$order['reference_no'], // 提运单号，直购进口为海运提单、空运总单或汽车载货清单
                        'ebpCode'            => $customerRow['trade_co'], // 运费，无则填0
                        'ebpName'         => $customerRow['trade_name'], // 保价费，无则填0
                        'ebcCode'           => $customerRow['trade_co'], // 币制代码，限定为人民币142
                        'ebcName'             => $customerRow['customer_company_name'], // 毛重KG
                        'agentCode'             => self::COP_CODE, // 件数
                        'agentName'          => self::COP_NAME, // 主要货物信息，包括商品名称、数量等
                        'goodsValue'          => $totalValue, // 收件人名称
                        'freight'   => 0, // 收件人住址
                        'currency' => 502, // 收件人电话
                        'consignee'   =>trim($address[0]['oab_firstname']." ".$address[0]['oab_lastname']), // 收件人所在国
                        'consigneeAddress'  => trim($address[0]['oab_street_address1']." ".$address[0]['oab_street_address2']), // 收件人省份，行政区划代码
                        'consigneeTelephone'      => trim($address[0]['oab_phone']), // 收件人城市，行政区划代码
                        'consigneeCountry'  => trim($country['trade_country']), // 收件人县区，行政区划代码
                        'note'               => '', // 备注
                    ),
                    'OrderList'=>$orderList,
                ),
            );

            $xml  = '<?xml version="1.0" encoding="UTF-8" ?>' . self::putCrlf();
            $xml .= '<CEB301Message xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.chinaport.gov.cn/ceb" version="1.0" guid="' . $guid . '">' . self::putCrlf();
            $xml .= self::putTab(1) . '<MessageHead>' . self::putCrlf();

            foreach ($CEB511Message['MessageHead'] as $node => $value) {
                $xml .= self::putTab(2) . "<{$node}>{$value}</{$node}>" . self::putCrlf();
            }

            $xml .= self::putTab(1) . '</MessageHead>' . self::putCrlf();
            //$xml .= self::putTab(1) . '<Order>' . self::putCrlf();

            $xml .= self::putTab(1) . '<OrderHead>' . self::putCrlf();
            foreach ($CEB511Message['Order']['OrderHead'] as $node => $value) {
                $xml .= self::putTab(2) . "<{$node}>{$value}</{$node}>" . self::putCrlf();
            }
            $xml .= self::putTab(1) . '</OrderHead>' . self::putCrlf();

            foreach ($CEB511Message['Order']['OrderList'] as $k => $v) {
                $xml .= self::putTab(1) . '<OrderList>' . self::putCrlf();
                foreach($v as $node => $value){
                    $xml .= self::putTab(2) . "<{$node}>{$value}</{$node}>" . self::putCrlf();
                }
                $xml .= self::putTab(1) . '</OrderList>' . self::putCrlf();
            }

            //$xml .= self::putTab(1) . '</Order>' . self::putCrlf();
            $xml .= '</CEB301Message>' . self::putCrlf();

            $response['status']      = 1;
            $response['message']     = '物流运单报文CEB301已生成';
            $response['xml_content'] = $xml;
        }
        catch (Exception $e) {
            $response['message'] = $e->getMessage();
        }

        return $response;
    }

    public static function renderCEB601Xml(array $eport){
        $guid = self::generateGuid(self::TYPE_CEB601, self::COP_CODE);
        $date = self::getDatetime();
        $name = 'CEE_CEB601_' . self::SENDER_ID . '_' . self::RECEIVER_ID . '_' . $date['micro_date'] . mt_rand(1001, 9999);
        $response = array(
            'status'       => 0,
            'message'      => '',
            'guid'         => $guid,
            'message_id'   => $guid,
            'logistics_no' => '',
            'xml_suffix'   => '.xml',
            'xml_name'     => $name,
            'xml_content'  => '',
        );

        try {
            /*$shippingMethod = Service_ShippingMethod::getByField($eport['sm_code'], 'sm_code');

            if (empty($shippingMethod)) {
              throw new Exception('运输代码[' . $eport['sm_code'] . ']缺乏数据信息');
            }*/

            $order = Service_Orders::getByField($eport['order_code'], 'order_code');
            $customerRow = Service_Customer::getByField($order['customer_code'],"customer_code","*");
            $orderProduct = Service_OrderProduct::getByCondition(array('order_code'=>$eport['order_code']),"*");
            $shipOrder = Service_ShipOrder::getByField($eport['order_code'], 'order_code',"*");
            $outBoundBagDetail = Service_OutboundBagDetail::getByField($eport['order_code'], 'order_code',"*");
            $shipBatchDetail = Service_ShipBatchDetail::getByField($outBoundBagDetail['ob_no'],'ob_no',"*");
            $shipBatchAttribute = Service_ShipBatchAttribute::getByField($shipBatchDetail['sb_code'],"sb_code","*");

            $address = Service_OrderAddressBook::getByCondition(array(
                'order_code' => $order['order_code'],
            ));

            if (empty($address)) {
                throw new Exception('缺乏地址数据信息');
            }

            //$weight   = $order['grossWt'];
            $address  = $address[0];
            $country = Service_Country::getByField($address['oab_country_id'],"country_id","*");

            $orderList = array();
            $totalValue = 0;
            $netWeight = 0;
            foreach($orderProduct as $key=>$op){
                $totalValue+=$op['op_quantity']*$op['op_declared_value'];
                $product = Service_Product::getByField($op['product_id'],"product_id","*");
                $netWeight+=$op['op_quantity']*$product['product_weight'];
                $hemList = Service_HsElementMap::getByCondition(array('product_id'=>$op['product_id']), 'hem_detail');
                $hsUom = Service_HsUom::getByField($product['hs_code'],"hs_code","*");
                $hsUomMap = Service_HsUomMap::getByField($op['product_id'],"product_id","*");
                $elements = array();

                foreach($hemList as $hemRow) $elements[] = $hemRow['hem_detail'];
                $gmodel = implode('|',$elements);
                $barCode = strlen($op['product_barcode'])>13?substr($op['product_barcode'],0,13):$op['product_barcode'];
                if($hsUomMap['hu_quantiy_second']!=0){
                    $qty2 = $hsUomMap['hu_quantiy_second']*$op['op_quantity'];
                }else{
                    $qty2 = "";
                }
                $ol = array(
                    'gnum'=>$key+1,
                    'itemNo'=>$product['product_sku'],
                    'gno'=>'N',
                    'gcode'=>$product['hs_code'],
                    'gname'=>$product['hs_goods_name'],
                    'gmodel'=>$gmodel,
                    'barCode'=>$barCode,
                    'country'=>$country['trade_country'],
                    'currency'=>'502',
                    //'brand'=>'无',
                    'qty'=>$op['op_quantity'],
                    'unit'=>$product['pu_code'],
                    'qty1'=>$hsUomMap['hu_quantiy_law']*$op['op_quantity'],
                    'unit1'=>$hsUom['pu_code_law'],
                    'qty2'=>$qty2,
                    'unit2'=>$hsUom['pu_code_second']!=""?$hsUom['pu_code_second']:"",
                    'price'=>$op['op_declared_value'],
                    'total'=>$op['op_quantity']*$op['op_declared_value'],
                    //'giftFlag'=>'0',
                    //'note'=>'',
                );
                $orderList[] = $ol;
            }

            if (empty($order)) {
                throw new Exception('单号[' . $eport['order_code'] . ']不存在');
            }

            $address = Service_OrderAddressBook::getByCondition(array(
                'order_code' => $order['order_code'],'oab_type'=>'0',
            ));

            if (empty($address)) {
                throw new Exception('缺乏地址数据信息');
            }
            $country = Service_Country::getByField($address[0]['oab_country_id'],"country_id","*");

            $CEB511Message = array(
                // 报文头信息
                'MessageHead' => array(
                    'MessageID'          => $guid, // 报文唯一编号
                    'MessageType'        => 'CEB601', // 报文类型：CEB511物流运单
                    'OrgCode'            => self::ORG_CODE, // 企业组织机构代码或统一社会信用代码
                    'CopCode'            => self::COP_CODE, // $shippingMethod['logistics_code'], // 传输企业代码
                    'CopName'            => self::COP_NAME, // $shippingMethod['logistics_name'], // 传输企业名称
                    'SenderID'           => self::SENDER_ID, // 发送方企业客户端ID号
                    'ReceiverID'         => self::RECEIVER_ID, // 接收方
                    'ReceiverDepartment' => 'Q', // 报文发送的监管单位：C海关、Q检验检疫
                    'SendTime'           => $date['micro_date'], // 发送时间，格式：yyyyMMddHHmmssSSS
                    'Version'            => self::VERSION, // 默认：1.0
                ),

                // 报文体信息
                'Inventory' => array(
                    // 运单信息
                    'InventoryHead' => array(
                        'guid'               => $guid, // 系统唯一序号
                        'customsCode'      =>'5349',
                        'appType'            => $eport['app_type'], // 报送类型：1新增、2修改、3删除
                        'appTime'            => $date['normal_date'], // 报送时间，格式：YYYYMMDDhhmmss
                        'appStatus'          => 2, // 业务状态：1暂存、2申报
                        'appUid'      => self::appUid, // $shippingMethod['logistics_code'], // 物流企业代码
                        'appUname'      => self::appUname, // $shippingMethod['logistics_name'], // 物流企业名称
                        'copNo'         => $order['reference_no'],
                        'preNo'         => '',//非必填
                        'orderNo'             =>$order['reference_no'], // 提运单号，直购进口为海运提单、空运总单或汽车载货清单
                        'ebpCode'            => $customerRow['trade_co'], // 运费，无则填0
                        'ebpName'         => $customerRow['trade_name'], // 保价费，无则填0
                        'logisticsNo'     => $shipOrder['tracking_number'],
                        'logisticsCode'   => self::COP_CODE,
                        'logisticsName'   => self::COP_NAME,
                        'invtNo'           =>'',//非必填
                        'ieFlag'           => 'E',
                        'portCode'        => $shipBatchAttribute['ie_port'],
                        'ieDate'          =>date("YmdHis",strtotime($order['update_time'])) ,
                        'ownerCode'      => $customerRow['trade_co'],
                        'ownerName'      => $customerRow['trade_name'],
                        'tradeCode'      => self::COP_CODE,
                        'tradeName'      => self::COP_NAME,
                        'agentCode'             => self::COP_CODE,
                        'agentName'          => self::COP_NAME,
                        'tradeMode'     => $shipBatchAttribute['trade_mode'],
                        'trafMode'      => $shipBatchAttribute['traf_mode'],
                        'voyageNo'      => $shipBatchAttribute['voyage_no'],
                        'billNo'        => $shipOrder['tracking_number'],
                        'loctNo'        => '5349',//监管场所代码 必填
                        'licenseNo'    =>$shipBatchAttribute['sb_code'],
                        'country'      =>$country['trade_country'],
                        'destinationPort' =>$country['trade_country'],
                        'freight'           =>$shipOrder['so_shipping_fee'],
                        'freightCurr'           =>'142',
                        'freightMark'           =>'3',
                        'insuredFee'            =>$order['insurance'],
                        'insuredFeeCurr'       =>'142',
                        'insuredFeeMark'       =>'1',
                        'wrapType'              =>$shipBatchAttribute['wrap_type'],
                        'packNo'                =>$shipOrder['so_piece'],
                        'weight'                =>$shipOrder['so_piece'],
                        'netWeight'             =>$netWeight,
                        'note'                  =>'',
                        //'goodsValue'          => $totalValue, // 收件人名称
                        //'freight'   => 0, // 收件人住址
                        //'currency' => 502, // 收件人电话
                        //'consignee'   =>trim($address[0]['oab_firstname']." ".$address[0]['oab_lastname']), // 收件人所在国
                        //'consigneeAddress'  => trim($address[0]['oab_street_address1']." ".$address[0]['oab_street_address2']), // 收件人省份，行政区划代码
                        //'consigneeTelephone'      => trim($address[0]['oab_phone']), // 收件人城市，行政区划代码
                        //'consigneeCountry'  => trim($country['trade_country']), // 收件人县区，行政区划代码
                        //'note'               => '', // 备注
                    ),
                    'InventoryList'=>$orderList,
                ),
            );

            $xml  = '<?xml version="1.0" encoding="UTF-8" ?>' . self::putCrlf();
            $xml .= '<CEB601Message xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.chinaport.gov.cn/ceb" version="1.0" guid="' . $guid . '">' . self::putCrlf();
            $xml .= self::putTab(1) . '<MessageHead>' . self::putCrlf();

            foreach ($CEB511Message['MessageHead'] as $node => $value) {
                $xml .= self::putTab(2) . "<{$node}>{$value}</{$node}>" . self::putCrlf();
            }

            $xml .= self::putTab(1) . '</MessageHead>' . self::putCrlf();
            //$xml .= self::putTab(1) . '<Order>' . self::putCrlf();

            $xml .= self::putTab(1) . '<InventoryHead>' . self::putCrlf();
            foreach ($CEB511Message['Inventory']['InventoryHead'] as $node => $value) {
                $xml .= self::putTab(2) . "<{$node}>{$value}</{$node}>" . self::putCrlf();
            }
            $xml .= self::putTab(1) . '</InventoryHead>' . self::putCrlf();

            foreach ($CEB511Message['Inventory']['InventoryList'] as $k => $v) {
                $xml .= self::putTab(1) . '<InventoryList>' . self::putCrlf();
                foreach($v as $node => $value){
                    $xml .= self::putTab(2) . "<{$node}>{$value}</{$node}>" . self::putCrlf();
                }
                $xml .= self::putTab(1) . '</InventoryList>' . self::putCrlf();
            }

            //$xml .= self::putTab(1) . '</Order>' . self::putCrlf();
            $xml .= '</CEB601Message>' . self::putCrlf();

            $response['status']      = 1;
            $response['message']     = '出境清单报文CEB601已生成';
            $response['xml_content'] = $xml;
        }
        catch (Exception $e) {
            $response['message'] = $e->getMessage();
        }

        return $response;

    }

    /**
     * 解析报文回执
     *
     * @param string $filename    回执文件名
     * @return array
     */
    public static function interpret($filename) {
        error_reporting(E_ALL);
        $currentTime   = time();
        $operationDate = date('Y/m/d', $currentTime);
        $operationTime = date('Y-m-d H:i:s', $currentTime);
        $receivePath   = '/home/sgt_xml/receive/'; // 回执保存路径
        $backupPath    = '/home/sgt_xml/receive_backup/' . $operationDate . '/'; // 回执备份路径
        $backupFile    = '/' . $operationDate . '/' . $filename;
        $errorPath     = '/home/eportxml/logistics/error/'; // 回执解析失败保存路径
        $messageId     = '';
        $feedbackTag   = '';
        $logisticsNo   = '';
        $returnStatus  = '';
        $returnTime    = '';
        $returnInfo    = '';
        $response      = array(
            'status'  => 0,
            'message' => '',
        );

        umask(0);

        try {
            if (!@is_file($receivePath . $filename)) {
                throw new Exception('文件[' . $filename . ']不存在');
            }

            $xmlObj = @simplexml_load_file($receivePath . $filename);

            if (FALSE === $xmlObj) {
                throw new Exception('文件[' . $filename . ']解析失败', 500);
            }

            $feedbackType = substr($filename, 0, 13);

            switch ($feedbackType) {
                case 'SZCPORTCEB304': // 检验检疫物流运单回执
                    $cebData      = array();
                    foreach($xmlObj->OrderReturn as $item){
                        $cebData = array(
                            'guid'=>$item->guid,
                            'ebp_code'=>$item->ebpCode,
                            'ebc_code'=>$item->ebpCode,
                            'order_no'=>$item->orderNo,
                            'return_status'=>$item->returnStatus,
                            'return_time'=>$item->returnTime,
                            'return_info'=>$item->returnInfo,
                        );
                    }
                    $orderSendRow = Service_OrderSendList::getByCondition(array('order_code'=>$cebData['order_no'],'send_type'=>'303'),"*");
                    $orderCustomerInfo = Service_OrderCustomInfo::getByField($cebData['order_no'],'order_code',"*");
                    if(!empty($orderSendRow)){
                        $updateRow = array(
                            //'guid'=>$cebData['guid'],
                            'ebp_code'=>$cebData['ebp_code'],
                            'ebc_code'=>$cebData['ebc_code'],
                            'return_status'=>$cebData['return_status'],
                            'return_time'=>$cebData['return_time'],
                            'return_info'=>$cebData['return_info'],
                            'send_status'=>3,
                        );
                        Service_OrderSendList::update($updateRow,$orderSendRow[0]['osl_id'],'osl_id');
                        $orderReceiveSgtlog = array(
                            'osl_id'=>$orderSendRow[0]['osl_id'],
                            'add_time'=>date("Y-m-d H:i:s"),
                            'return_status'=>$cebData['return_status'],
                            'return_time'=>$cebData['return_time'],
                            'return_info'=>$cebData['return_info'],
                            'file_name'=>$backupPath . $filename,
                        );
                        Service_OrderReceiveSgtlog::add($orderReceiveSgtlog);
                        $exist403 = Service_OrderSendList::getByCondition(array('order_code'=>$cebData['order_no'],'send_type'=>'403'),"count(*)");
                        if(!$exist403){
                            $addRow = array(
                                'guid'=>'',
                                'order_code'=>$orderCustomerInfo['order_code'],
                                'refercence_no'=>$orderCustomerInfo['pay_no'],
                                'send_type'=>'403',
                                'send_status'=>1,
                                'agent_code'=>'',
                                'cop_no'=>'',
                                'pre_no'=>'',
                                'invt_no'=>'',
                                'ebc_code'=>'',
                                'ebp_code'=>'',
                                'bill_no'=>'',
                                'statistics_flag'=>'',
                                'msg_seq_no'=>'',
                                'return_status'=>'',
                                'return_time'=>'',
                                'return_info'=>'',
                                'add_time'=>date("Y-m-d H:i:s")
                            );
                            $id = Service_OrderSendList::add($addRow);
                        }
                    }

                    break ;

                case 'SZCPORTCEB404':
                    $cebData      = array();
                    foreach($xmlObj->ReceiptsReturn as $item){
                        $cebData = array(
                            'guid'=>$item->guid,
                            'ebc_code'=>$item->ebpCode,
                            'order_no'=>$item->orderNo,
                            'pay_no'=>$item->payNo,
                            'return_status'=>$item->returnStatus,
                            'return_time'=>$item->returnTime,
                            'return_info'=>$item->returnInfo,
                        );
                    }
                    $orderSendRow = Service_OrderSendList::getByCondition(array('order_code'=>$cebData['order_no'],'send_type'=>'403'),"*");
                    $orderCustomerInfo = Service_OrderCustomInfo::getByField($cebData['order_no'],'order_code',"*");
                    if(!empty($orderSendRow)){
                        $updateRow = array(
                            //'guid'=>$cebData['guid'],
                            'ebc_code'=>$cebData['ebc_code'],
                            'refercence_no'=>$cebData['pay_no'],
                            'return_status'=>$cebData['return_status'],
                            'return_time'=>$cebData['return_time'],
                            'return_info'=>$cebData['return_info'],
                            'send_status'=>3,
                        );
                        Service_OrderSendList::update($updateRow,$orderSendRow[0]['osl_id'],'osl_id');
                        $orderReceiveSgtlog = array(
                            'osl_id'=>$orderSendRow[0]['osl_id'],
                            'add_time'=>date("Y-m-d H:i:s"),
                            'return_status'=>$cebData['return_status'],
                            'return_time'=>$cebData['return_time'],
                            'return_info'=>$cebData['return_info'],
                            'file_name'=>$backupPath . $filename,
                        );
                        Service_OrderReceiveSgtlog::add($orderReceiveSgtlog);
                        /*if($orderSendRow[0]['send_status']=='2'&&in_array($cebData['return_status'],array(2,120,399,899))){
                            $addRow = array(
                                'guid'=>'',
                                'order_code'=>$orderCustomerInfo['order_code'],
                                'refercence_no'=>$orderCustomerInfo['logistics_no'],
                                'send_type'=>'505',
                                'send_status'=>1,
                                'agent_code'=>'',
                                'cop_no'=>'',
                                'pre_no'=>'',
                                'invt_no'=>'',
                                'ebc_code'=>'',
                                'ebp_code'=>'',
                                'bill_no'=>'',
                                'statistics_flag'=>'',
                                'msg_seq_no'=>'',
                                'return_status'=>'',
                                'return_time'=>'',
                                'return_info'=>'',
                            );
                            Service_OrderSendList::add($addRow);
                        }*/
                        $exist505 = Service_OrderSendList::getByCondition(array('order_code'=>$cebData['order_no'],'send_type'=>'505'),"count(*)");
                        if(!$exist505){
                            $addRow = array(
                                'guid'=>'',
                                'order_code'=>$orderCustomerInfo['order_code'],
                                'refercence_no'=>$orderCustomerInfo['logistics_no'],
                                'send_type'=>'505',
                                'send_status'=>1,
                                'agent_code'=>'',
                                'cop_no'=>'',
                                'pre_no'=>'',
                                'invt_no'=>'',
                                'ebc_code'=>'',
                                'ebp_code'=>'',
                                'bill_no'=>'',
                                'statistics_flag'=>'',
                                'msg_seq_no'=>'',
                                'return_status'=>'',
                                'return_time'=>'',
                                'return_info'=>'',
                                'add_time'=>date("Y-m-d H:i:s")
                            );
                            Service_OrderSendList::add($addRow);
                        }
                    }
                    break;
                case 'SZCPORTCEB506':
                    $cebData      = array();
                    foreach($xmlObj->LogisticsReturn as $item){
                        $cebData = array(
                            'guid'=>$item->guid,
                            'logistics_code'=>$item->logisticsCode,
                            'logistics_no'=>$item->logisticsNo,
                            'return_status'=>$item->returnStatus,
                            'return_time'=>$item->returnTime,
                            'return_info'=>$item->returnInfo,
                        );
                    }
                    $orderSendRow = Service_OrderSendList::getByField($cebData['logistics_no'],'refercence_no',"*");
                    if(!empty($orderSendRow)){
                        $updateRow = array(
                            'return_status'=>$cebData['return_status'],
                            'return_time'=>$cebData['return_time'],
                            'return_info'=>$cebData['return_info'],
                            'send_status'=>3,
                        );
                        $orderCustomerInfo = Service_OrderCustomInfo::getByField($orderSendRow['order_code'],'order_code',"*");
                        Service_OrderSendList::update($updateRow,$orderSendRow['osl_id'],'osl_id');
                        $orderReceiveSgtlog = array(
                            'osl_id'=>$orderSendRow['osl_id'],
                            'add_time'=>date("Y-m-d H:i:s"),
                            'return_status'=>$cebData['return_status'],
                            'return_time'=>$cebData['return_time'],
                            'return_info'=>$cebData['return_info'],
                            'file_name'=>$backupPath . $filename,
                        );
                        Service_OrderReceiveSgtlog::add($orderReceiveSgtlog);
                        /*if($orderSendRow['send_status']=='2'&&$cebData['return_status']=="2"){
                            $addRow = array(
                                'guid'=>'',
                                'order_code'=>$orderSendRow['order_code'],
                                'refercence_no'=>$orderCustomerInfo['qd_cop_no'],
                                'send_type'=>'603',
                                'send_status'=>1,
                                'agent_code'=>'',
                                'cop_no'=>'',
                                'pre_no'=>'',
                                'invt_no'=>'',
                                'ebc_code'=>'',
                                'ebp_code'=>'',
                                'bill_no'=>'',
                                'statistics_flag'=>'',
                                'msg_seq_no'=>'',
                                'return_status'=>'',
                                'return_time'=>'',
                                'return_info'=>'',
                            );
                            Service_OrderSendList::add($addRow);
                        }*/
                        $exist603 = Service_OrderSendList::getByCondition(array('order_code'=>$orderSendRow['order_code'],'send_type'=>'603'),"count(*)");
                        if(!$exist603){
                            $addRow = array(
                                'guid'=>'',
                                'order_code'=>$orderCustomerInfo['order_code'],
                                'refercence_no'=>$orderCustomerInfo['qd_cop_no'],
                                'send_type'=>'603',
                                'send_status'=>1,
                                'agent_code'=>'',
                                'cop_no'=>'',
                                'pre_no'=>'',
                                'invt_no'=>'',
                                'ebc_code'=>'',
                                'ebp_code'=>'',
                                'bill_no'=>'',
                                'statistics_flag'=>'',
                                'msg_seq_no'=>'',
                                'return_status'=>'',
                                'return_time'=>'',
                                'return_info'=>'',
                                'add_time'=>date("Y-m-d H:i:s")
                            );
                            Service_OrderSendList::add($addRow);
                        }
                    }
                    break;
                case 'SZCPORTCEB604':
                    $cebData      = array();
                    foreach($xmlObj->InventoryReturn as $item){
                        $cebData = array(
                            'guid'=>$item->guid,
                            'agent_code'=>$item->agentCode,
                            'cop_no'=>$item->copNo,
                            'pre_no'=>$item->preNo,
                            'invt_no'=>$item->invtNo,
                            'ebc_code'=>$item->ebcCode,
                            'ebp_code'=>$item->ebpCode,
                            'order_no'=>$item->orderNo,
                            'statistics_flag'=>$item->statisticsFlag,
                            'return_status'=>$item->returnStatus,
                            'return_time'=>$item->returnTime,
                            'return_info'=>$item->returnInfo,
                        );
                    }
                    //var_dump($cebData);
                    $orderSendRow = Service_OrderSendList::getByField($cebData['cop_no'],'refercence_no',"*");
                    if(!empty($orderSendRow)){
                        $updateRow = array(
                            'guid'=>$cebData['guid'],
                            'agent_code'=>$cebData['agent_code'],
                            'cop_no'=>$cebData['cop_no'],
                            'pre_no'=>$cebData['pre_no'],
                            'invt_no'=>$cebData['invt_no'],
                            'ebc_code'=>$cebData['ebc_code'],
                            'ebp_code'=>$cebData['ebp_code'],
                            'statistics_flag'=>$cebData['statistics_flag'],
                            'return_status'=>$cebData['return_status'],
                            'return_time'=>$cebData['return_time'],
                            'return_info'=>$cebData['return_info'],
                            'send_status'=>3,
                        );
                        Service_OrderSendList::update($updateRow,$orderSendRow['osl_id'],'osl_id');
                        if($cebData['return_status']==899){
                            //$updateRow['cmbl_send_status'] = 1;
                            $updateOrderCustomInfo = array(
                                'invt_no'=>$cebData['invt_no']
                            );
                            Service_OrderCustomInfo::update($updateOrderCustomInfo,$orderSendRow['order_code'],"order_code");
                            $obd = Service_OutboundBagDetail::getByField($orderSendRow['order_code'],"order_code","*");
                            $sbd = Service_ShipBatchDetail::getByField($obd['ob_no'],'ob_no',"*");
                            $oderCodeArr = Service_ShipBatchDetail::getOrderCode($sbd['sb_code']);
                            if(!empty($oderCodeArr)){
                                $allOk = 1;
                                foreach($oderCodeArr as $order_code){
                                    $condition = array('send_type'=>'603','send_status'=>3,'order_code'=>$order_code);
                                    $os = Service_OrderSendList::getByCondition($condition,"*");
                                    if(empty($os)||$os[0]['return_status']!=899) $allOk = 0;
                                }
                                if($allOk){
                                    $shipBatchXml = Service_ShipBatchXml::getByCondition(array('sb_code'=>$sbd['sb_code']),"*");
                                    foreach($shipBatchXml as $sbx){
                                        $ftpSendList = Service_FtpMessageSendlist::getByCondition(array('fmt_code'=>'MCK', 'refercence_no'=>$sbx['sub_sb_code']),"*");
                                        $updFtpRow = array(
                                            'fml_status'=>1,
                                            'fml_update_time'=>date("Y-m-d H:i:s"),
                                        );
                                        Service_FtpMessageSendlist::update($updFtpRow,$ftpSendList[0]['fml_id'],'fml_id');
                                    }
                                }
                            }
                        }
                        $orderCustomerInfo = Service_OrderCustomInfo::getByField($orderSendRow['order_code'],'order_code',"*");
                        $orderReceiveSgtlog = array(
                            'osl_id'=>$orderSendRow['osl_id'],
                            'add_time'=>date("Y-m-d H:i:s"),
                            'return_status'=>$cebData['return_status'],
                            'return_time'=>$cebData['return_time'],
                            'return_info'=>$cebData['return_info'],
                            'file_name'=>$backupPath . $filename,
                        );
                        Service_OrderReceiveSgtlog::add($orderReceiveSgtlog);
                        /*if($orderSendRow['send_status']=='2'&&in_array($cebData['return_status'],array(2,120,399,899))){
                            $addRow = array(
                                'guid'=>'',
                                'order_code'=>$orderSendRow['order_code'],
                                'refercence_no'=>$orderCustomerInfo['zfd_cop_no'],
                                'send_type'=>'607',
                                'send_status'=>1,
                                'agent_code'=>'',
                                'cop_no'=>'',
                                'pre_no'=>'',
                                'invt_no'=>'',
                                'ebc_code'=>'',
                                'ebp_code'=>'',
                                'bill_no'=>'',
                                'statistics_flag'=>'',
                                'msg_seq_no'=>'',
                                'return_status'=>'',
                                'return_time'=>'',
                                'return_info'=>'',
                            );
                            Service_OrderSendList::add($addRow);
                        }*/
                        $exist607 = Service_OrderSendList::getByCondition(array('order_code'=>$orderSendRow['order_code'],'send_type'=>'607'),"count(*)");
                        if(!$exist607){
                            $addRow = array(
                                'guid'=>'',
                                'order_code'=>$orderSendRow['order_code'],
                                'refercence_no'=>$orderCustomerInfo['zfd_cop_no'],
                                'send_type'=>'607',
                                'send_status'=>1,
                                'agent_code'=>'',
                                'cop_no'=>'',
                                'pre_no'=>'',
                                'invt_no'=>'',
                                'ebc_code'=>'',
                                'ebp_code'=>'',
                                'bill_no'=>'',
                                'statistics_flag'=>'',
                                'msg_seq_no'=>'',
                                'return_status'=>'',
                                'return_time'=>'',
                                'return_info'=>'',
                                'add_time'=>date("Y-m-d H:i:s")
                            );
                            Service_OrderSendList::add($addRow);
                        }
                    }
                    break;
                case 'SZCPORTCEB608':
                    $cebData      = array();
                    foreach($xmlObj->WayBillReturn as $item){
                        $cebData = array(
                            'guid'=>$item->guid,
                            'agent_code'=>$item->agentCode,
                            'cop_no'=>$item->copNo,
                            'pre_no'=>$item->preNo,
                            'invt_no'=>$item->invtNo,
                            'ebc_code'=>$item->ebcCode,
                            'ebp_code'=>$item->ebpCode,
                            'order_no'=>$item->orderNo,
                            'statistics_flag'=>$item->statisticsFlag,
                            'return_status'=>$item->returnStatus,
                            'return_time'=>$item->returnTime,
                            'return_info'=>$item->returnInfo,
                        );
                    }
                    //var_dump($cebData);
                    $orderSendRow = Service_OrderSendList::getByField($cebData['cop_no'],'refercence_no',"*");
                    if(!empty($orderSendRow)){
                        $updateRow = array(
                            'guid'=>$cebData['guid'],
                            'agent_code'=>$cebData['agent_code'],
                            'cop_no'=>$cebData['cop_no'],
                            'pre_no'=>$cebData['pre_no'],
                            'invt_no'=>$cebData['invt_no'],
                            'ebc_code'=>$cebData['ebc_code'],
                            'ebp_code'=>$cebData['ebp_code'],
                            'statistics_flag'=>$cebData['statistics_flag'],
                            'return_status'=>$cebData['return_status'],
                            'return_time'=>$cebData['return_time'],
                            'return_info'=>$cebData['return_info'],
                            'send_status'=>3,
                        );
                        Service_OrderSendList::update($updateRow,$orderSendRow['osl_id'],'osl_id');
                        $orderReceiveSgtlog = array(
                            'osl_id'=>$orderSendRow['osl_id'],
                            'add_time'=>date("Y-m-d H:i:s"),
                            'return_status'=>$cebData['return_status'],
                            'return_time'=>$cebData['return_time'],
                            'return_info'=>$cebData['return_info'],
                            'file_name'=>$backupPath . $filename,
                        );
                        Service_OrderReceiveSgtlog::add($orderReceiveSgtlog);
                        $orderCustomerInfo = Service_OrderCustomInfo::getByField($orderSendRow['order_code'],'order_code',"*");
                        /*if($orderSendRow['send_status']=='2'&&in_array($cebData['return_status'],array(2,120,399,899))){
                            $addRow = array(
                                'guid'=>'',
                                'order_code'=>$orderSendRow['order_code'],
                                'refercence_no'=>$orderCustomerInfo['l_cop_no'],
                                'send_type'=>'509',
                                'send_status'=>1,
                                'agent_code'=>'',
                                'cop_no'=>'',
                                'pre_no'=>'',
                                'invt_no'=>'',
                                'ebc_code'=>'',
                                'ebp_code'=>'',
                                'bill_no'=>'',
                                'statistics_flag'=>'',
                                'msg_seq_no'=>'',
                                'return_status'=>'',
                                'return_time'=>'',
                                'return_info'=>'',
                            );
                            Service_OrderSendList::add($addRow);
                        }*/
                        $exist509 = Service_OrderSendList::getByCondition(array('order_code'=>$orderSendRow['order_code'],'send_type'=>'509'),"count(*)");
                        if(!$exist509){
                            $addRow = array(
                                'guid'=>'',
                                'order_code'=>$orderSendRow['order_code'],
                                'refercence_no'=>$orderCustomerInfo['l_cop_no'],
                                'send_type'=>'509',
                                'send_status'=>1,
                                'agent_code'=>'',
                                'cop_no'=>'',
                                'pre_no'=>'',
                                'invt_no'=>'',
                                'ebc_code'=>'',
                                'ebp_code'=>'',
                                'bill_no'=>'',
                                'statistics_flag'=>'',
                                'msg_seq_no'=>'',
                                'return_status'=>'',
                                'return_time'=>'',
                                'return_info'=>'',
                                'add_time'=>date("Y-m-d H:i:s")
                            );
                            Service_OrderSendList::add($addRow);
                        }
                    }
                    break;
                case 'SZCPORTCEB510':
                    $cebData      = array();
                    foreach($xmlObj->DepartureReturn as $item){
                        $cebData = array(
                            'guid'=>$item->guid,
                            'logistics_code'=>$item->logisticsCode,
                            'cop_no'=>$item->copNo,
                            'pre_no'=>$item->preNo,
                            'msg_seq_no'=>$item->msgSeqNo,
                            'return_status'=>$item->returnStatus,
                            'return_time'=>$item->returnTime,
                            'return_info'=>$item->returnInfo,
                        );
                    }
                    //var_dump($cebData);
                    $orderSendRow = Service_OrderSendList::getByField($cebData['cop_no'],'refercence_no',"*");
                    if(!empty($orderSendRow)){
                        $updateRow = array(
                            'guid'=>$cebData['guid'],
                            'cop_no'=>$cebData['cop_no'],
                            'pre_no'=>$cebData['pre_no'],
                            'msg_seq_no'=>$cebData['msg_seq_no'],
                            'return_status'=>$cebData['return_status'],
                            'return_time'=>$cebData['return_time'],
                            'return_info'=>$cebData['return_info'],
                            'send_status'=>3,
                        );
                        Service_OrderSendList::update($updateRow,$orderSendRow['osl_id'],'osl_id');
                        $orderReceiveSgtlog = array(
                            'osl_id'=>$orderSendRow['osl_id'],
                            'add_time'=>date("Y-m-d H:i:s"),
                            'return_status'=>$cebData['return_status'],
                            'return_time'=>$cebData['return_time'],
                            'return_info'=>$cebData['return_info'],
                            'file_name'=>$backupPath . $filename,
                        );
                        Service_OrderReceiveSgtlog::add($orderReceiveSgtlog);
                    }
                    break;
                default:
                    throw new Exception('文件[' . $filename . ']回执类型未知', 500);
                    break ;
            }

            if (!empty($errorTips)) {
                throw new Exception(implode("\r\n", $errorTips), 500);
            }

            if (!@is_dir($backupPath)) {
                @mkdir($backupPath, 0777, TRUE);
            }

            @rename($receivePath . $filename, $backupPath . $filename);
            chmod($backupPath . $filename, 0777);

            $response['status']  = 1;
            $response['message'] = '回执[' . $filename . ']已解析';
        }
        catch (Exception $e) {
            $response['message'] = $e->getMessage();

            if (500 === $e->getCode()) {
                @rename($receivePath . $filename, $errorPath . $filename);
                chmod($errorPath . $filename, 0777);
            }
        }

        return $response;
    }

    /**
     * 生成GUID
     *
     * @param string $type      报文类型
     * @param string $code      海关备案编码
     * @param string $hyphen    连接字符
     * @return string
     */
    private static function generateGuid($type, $code, $hyphen = '-') {
        $uid   = strtoupper(md5(uniqid($type . $code . mt_rand(), TRUE)));
        $guid  = substr($uid, 6, 2) . substr($uid, 4, 2) . substr($uid, 2, 2) . substr($uid, 0, 2) . $hyphen;
        $guid .= substr($uid, 10, 2) . substr($uid, 8, 2) . $hyphen;
        $guid .= substr($uid, 14, 2) . substr($uid, 12, 2) . $hyphen;
        $guid .= substr($uid, 16, 4) . $hyphen;
        $guid .= substr($uid, 20, 12);

        return $guid;
    }

    /**
     * 获取时间
     *
     * @return array
     */
    private static function getDatetime() {
        $microtime = number_format(microtime(TRUE), 3, '.', '');

        list($time, $micro) = explode('.', $microtime);

        return array(
            'micro_date'  => date('YmdHis', $time) . $micro,
            'normal_date' => date('YmdHis', $time),
        );
    }

    /**
     * TAB（水平制表符）
     *
     * @param integer $quantity    TAB数量
     * @return string
     */
    private static function putTab($quantity = 1) {
        $tab = "\t";

        for ($i = 1; $i < $quantity; ++$i) {
            $tab .= "\t";
        }

        return $tab;
    }

    /**
     * 回车换行
     *
     * @return string
     */
    private static function putCrlf() {
        return "\r\n";
    }

}
