<?php
/**
 * Created by JetBrains PhpStorm.
 * User: user
 * Date: 15-12-20
 * Time: 下午12:19
 * To change this template use File | Settings | File Templates.
 */
class Service_SpOutBillXmlProcess
{
    public $version = '1.0';
    public $sendtime = '';
    public $MessageID = 0;
    public $formID = '';

    private $dom = null;
    private $elMessage = null;
    private $elHead = null;
    private $elDeclaration = null;
    private $elBillHead = null;

    private $sb_code = '';
    private $sbRow = array();
    private $sbaRow = array();	//ship_batch_attribute
    private $fmtRow = array();	//ftp_message_type
    private $fmtRows = array();	//ftp_message_type
    private $productList = array();
    private $customerRow = array();
    private $gross_weight = 0;
    private $net_weight = 0;
    private $kvCurrency = array();
    private $totalPrice = 0;	//总价
    //private $orderCodeArr = array();

    public function __construct($sub_sb_code) {
        $this->formID = $sub_sb_code;
        $this->shipBatchXml = Service_ShipBatchXml::getByField($sub_sb_code,'sub_sb_code');
        $this->sb_code = $this->shipBatchXml['sb_code'];
        $this->sbRow = Service_ShipBatch::getByField($this->sb_code, 'sb_code');
        $this->sbaRow = Service_ShipBatchAttribute::getByField($this->sb_code, 'sb_code');
        $this->productList = Service_ShipBatchXmlDetail::getByCondition(array('sub_sb_code'=>$sub_sb_code),"*",0,0);
        //$this->totalPrice = $this->productList['total'];
        $firstRow = current($this->productList);
        //$this->customerRow = Service_Customer::getByField($firstRow['customer_id']);
        $aOrderCode = Service_ShipBatch::getOrderCodes($this->sb_code);
        //$this->orderCodeArr = $aOrderCode;
        if ($this->sbaRow['form_type']=="E2F") {
            $orderRow = Service_Orders::getByField($aOrderCode[0],"order_code","*");
            $this->customerRow = Service_Customer::getByField($orderRow['customer_id']);
            $this->fmtRow = Service_FtpMessageType::getByField(5, 'fmt_id');
            /*$customer=Service_Orders::getByField($aOrderCode,'order_code');
            $this->customerRow=Service_Customer::getByField($customer['customer_code'],'customer_code');*/
            //$this->fmtRow=$fmtRow[0];
            $this->fmtRows=$this->fmtRow;
            $this->fmtRow['agent_code']=$this->customerRow['trade_co'];
            $this->fmtRow['agent_name']=$this->customerRow['trade_name'];
            $this->fmtRow['trade_co'] = $this->customerRow['trade_co'];
            $this->fmtRow['trade_name'] = $this->customerRow['trade_name'];
        }else{
            $this->fmtRow = Service_FtpMessageType::getByField('ZC-MCK', 'fmt_code');
            $this->fmtRow['trade_co'] = "4403660028";
            $this->fmtRow['trade_name'] = "深圳市招海国际货运代理有限公司";
            $this->fmtRows=$this->fmtRow;
        }
        $this->kvCurrency = Service_Currency::getKeyVal();
        //发送时间
        $this->sendtime = date('YmdHis').str_pad(rand(1,888), 3, '0', STR_PAD_LEFT);
        //MessageID
        $this->MessageID = ++$this->fmtRow['fmt_form_id'];
        Service_FtpMessageType::update(array('fmt_form_id'=>$this->MessageID), $this->fmtRow['fmt_id']);
    }

    /**
     * 创建根节点Message
     */
    private function createMessage() {
        $this->dom = new DOMDocument('1.0', 'UTF-8');
        $this->elMessage = $this->dom->createElement('Message');
        $this->elMessage->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
        $this->dom->appendChild($this->elMessage);
    }

    /**
     * 创建Head节点
     */
    private function createHead() {
        $this->elHead = $this->dom->createElement('Head');
        $this->elHead->appendChild($this->dom->createElement('MessageID', $this->MessageID));
        $this->elHead->appendChild($this->dom->createElement('FunctionCode', '2'));
        $this->elHead->appendChild($this->dom->createElement('MessageType', $this->fmtRow['fmt_type']));
        $this->elHead->appendChild($this->dom->createElement('SenderID', $this->fmtRow['fml_sender_id']));
        $this->elHead->appendChild($this->dom->createElement('ReceiverID', $this->fmtRow['fml_receiver_id']));
        $this->elHead->appendChild($this->dom->createElement('SendTime', $this->sendtime));
        $this->elHead->appendChild($this->dom->createElement('Version', $this->version));
        $this->elMessage->appendChild($this->elHead);
    }

    /**
     * 创建Declaration节点
     */
    private function createDeclaration() {
        $this->elDeclaration = $this->dom->createElement('Declaration');
        $this->elMessage->appendChild($this->elDeclaration);
    }

    /**
     * 创建WAREHOUSE_BILL_HEAD节点
     */
    private function createBillHead() {
        $this->elBillHead = $this->dom->createElement('WAREHOUSE_BILL_HEAD');
        $this->elBillHead->appendChild($this->dom->createElement('SERIAL_NO', $this->sbRow['sb_id']));
        $this->elBillHead->appendChild($this->dom->createElement('FORM_ID', $this->formID));
        $this->elBillHead->appendChild($this->dom->createElement('DECL_PORT', $this->fmtRow['fmt_decl_port']));
        $this->elBillHead->appendChild($this->dom->createElement('I_E_PORT', $this->sbaRow['ie_port']));
        $this->elBillHead->appendChild($this->dom->createElement('I_E_MODE', $this->fmtRow['fmt_ie_mode']));
        $this->elBillHead->appendChild($this->dom->createElement('PS_TYPE', $this->fmtRow['fml_ps_type']));
        $this->elBillHead->appendChild($this->dom->createElement('RELATIVE_FORM_TYPE', $this->fmtRow['relative_form_type']));
        $this->elBillHead->appendChild($this->dom->createElement('FORM_TYPE', $this->sbaRow['form_type']));
        $this->elBillHead->appendChild($this->dom->createElement('EMS_NO', $this->fmtRow['fml_ems_no']));
        $this->elBillHead->appendChild($this->dom->createElement('OwnerCompanyID', "SZBH"));
        $this->elBillHead->appendChild($this->dom->createElement('EMS_COP_NO'));
        $this->elBillHead->appendChild($this->dom->createElement('TRAF_NAME'));
        //if($this->sbaRow['traf_name']=='truck') $this->sbaRow['voyage_no'] = '';
        $this->elBillHead->appendChild($this->dom->createElement('VOYAGE_NO'));
        $this->elBillHead->appendChild($this->dom->createElement('BILL_NO'));
        $gw = $this->shipBatchXml['gross_wt']>1?round($this->shipBatchXml['gross_wt'],2):"1";
        $this->elBillHead->appendChild($this->dom->createElement('GROSS_WT', $gw));
        $this->elBillHead->appendChild($this->dom->createElement('NET_WT', round($this->shipBatchXml['net_wt'],2)));
        $this->elBillHead->appendChild($this->dom->createElement('PACK_NO', $this->shipBatchXml['pack_no']));
        //$this->elBillHead->appendChild($this->dom->createElement('WRAP_TYPE', $this->sbaRow['wrap_type']));
        $this->elBillHead->appendChild($this->dom->createElement('WRAP_TYPE', '7'));	//固定为其他
        $this->elBillHead->appendChild($this->dom->createElement('I_E_DATE'));
        $this->elBillHead->appendChild($this->dom->createElement('TRAF_MODE', $this->sbaRow['traf_mode']));
        $this->elBillHead->appendChild($this->dom->createElement('TRADE_CO', $this->fmtRow['trade_co']));
        $this->elBillHead->appendChild($this->dom->createElement('TRADE_NAME', $this->fmtRow['trade_name']));
        $this->elBillHead->appendChild($this->dom->createElement('TRADE_MODE', $this->sbaRow['trade_mode']));
        $this->elBillHead->appendChild($this->dom->createElement('TRANS_MODE', $this->sbaRow['trans_mode']));
        $this->elBillHead->appendChild($this->dom->createElement('AGENT_CODE', $this->fmtRows['agent_code']));
        $this->elBillHead->appendChild($this->dom->createElement('AGENT_NAME', $this->fmtRows['agent_name']));
        $this->elBillHead->appendChild($this->dom->createElement('TRADE_COUNTRY', $this->sbaRow['country_id']));
        $this->elBillHead->appendChild($this->dom->createElement('OWNER_CODE', '4403660028'));
        $this->elBillHead->appendChild($this->dom->createElement('OWNER_NAME', '招海'));
        $this->elBillHead->appendChild($this->dom->createElement('NOTE_S'));
        /* $consignee = '收货人：'.$this->sbaRow['consignee'];
        $total = '总价：'.$this->totalPrice;
        $this->elBillHead->appendChild($this->dom->createElement('NOTE_S', $consignee.'  '.$total)); */
        $this->elBillHead->appendChild($this->dom->createElement('RELATIVE_FORM_ID'));
        $this->elBillHead->appendChild($this->dom->createElement('RELATIVE_FORM_STATUS'));
        $this->elBillHead->appendChild($this->dom->createElement('INPUT_DATE'));
        $this->elBillHead->appendChild($this->dom->createElement('INPUT_NO'));
        $this->elBillHead->appendChild($this->dom->createElement('FORM_STATUS'));
        $this->elBillHead->appendChild($this->dom->createElement('D_DATE'));
        $this->elBillHead->appendChild($this->dom->createElement('CHK_DATE'));
        $this->elBillHead->appendChild($this->dom->createElement('CHK_STATUS'));
        $this->elBillHead->appendChild($this->dom->createElement('AUDIT_DATE'));
        $this->elBillHead->appendChild($this->dom->createElement('CAN_BINDING_DATE'));
        $this->elBillHead->appendChild($this->dom->createElement('CAN_CHANNEL_DATE'));
        $this->elBillHead->appendChild($this->dom->createElement('DEDUC_DATE'));
        $this->elBillHead->appendChild($this->dom->createElement('COP_GB_CODE', $this->fmtRow['fml_receiver_id']));
        $this->elBillHead->appendChild($this->dom->createElement('EMC_EPORTCARD_ID'));
        $this->elBillHead->appendChild($this->dom->createElement('SIGN'));
        $this->elBillHead->appendChild($this->dom->createElement('DESTINATION_PORT', $this->sbaRow['country_id']));
        $this->elBillHead->appendChild($this->dom->createElement('TURN_NO'));
        $this->elBillHead->appendChild($this->dom->createElement('CUS_CODE', $this->fmtRow['outbound_trade_co']));
        $this->elBillHead->appendChild($this->dom->createElement('CUS_NAME', $this->fmtRow['outbound_trade_name']));
        /*$this->elBillHead->appendChild($this->dom->createElement('CUS_CODE', $this->customerRow['cus_code']));
        $this->elBillHead->appendChild($this->dom->createElement('CUS_NAME', $this->customerRow['cus_name']));*/
        $this->elBillHead->appendChild($this->dom->createElement('DECLARE_REMARK'));
        $OrderIDArr = array();
        //var_dump($this->orderCodeArr);
        $infoList = Service_OrderCustomInfo::getByCondition(array('sub_sb_code'=>$this->formID),"*");
        if(!empty($infoList)){
            foreach($infoList as $key=>$val){
                //if(!empty($orderSendList)) $OrderIDArr[]=$orderSendList[0]['invt_no'];
                $OrderIDArr[]=$val['invt_no'];
            }
            if(!empty($OrderIDArr)){
                $orderIdStr = implode("|",$OrderIDArr);
                $orderIdStr = base64_encode(bzcompress($orderIdStr));
                //echo $orderIdStr;
                $this->elBillHead->appendChild($this->dom->createElement('ORDER_ID',$orderIdStr));
            }
        }
        $this->elDeclaration->appendChild($this->elBillHead);
    }

    /**
     * 创建WAREHOUSE_BILL_CONTAINER节点
     * @return DOMElement
     */
    private function createBillContainer() {
        $elBillContainer = $this->dom->createElement('WAREHOUSE_BILL_CONTAINER');
        $elBillContainer->appendChild($this->dom->createElement('FORM_ID', $this->formID));
        $elBillContainer->appendChild($this->dom->createElement('CONTA_ID', $this->sbaRow['conta_id']));
        $elBillContainer->appendChild($this->dom->createElement('CONTA_MODEL', $this->sbaRow['conta_model']));
        $elBillContainer->appendChild($this->dom->createElement('CONTA_WT', $this->sbaRow['conta_wt']));
        $this->elBillHead->appendChild($elBillContainer);
    }

    /**
     * 创建WAREHOUSE_BILL_LIST节点
     * @param int $no
     * @param array $info
     * @return DOMElement
     */
    private function createBillList( $info) {
        $elBillList = $this->dom->createElement('WAREHOUSE_BILL_LIST');
        $elBillList->appendChild($this->dom->createElement('FORM_ID', $this->formID));
        $elBillList->appendChild($this->dom->createElement('G_NO', $info['g_no']));
        $elBillList->appendChild($this->dom->createElement('PutrecSeqno',$info['putrec_seqno']));
        $elBillList->appendChild($this->dom->createElement('GOODS_ID', $info['goods_id']));
        $elBillList->appendChild($this->dom->createElement('MERGER_G_NO', $info['merger_g_no']));
        $elBillList->appendChild($this->dom->createElement('MERGER_MODE', $info['merger_mode']));	//固定传1
        $elBillList->appendChild($this->dom->createElement('CODE_TS', $info['code_ts']));
        $elBillList->appendChild($this->dom->createElement('G_NAME_CN', $info['g_name_cn']));
        /*$hemList = Service_HsElementMap::getByCondition(array('product_id'=>$info['product_id']), 'hem_detail');
        $elements = array();
        foreach($hemList as $hemRow) {
            $hem_detail = trim($hemRow['hem_detail']);
            $elements[] = $hem_detail ? $hem_detail : '/';
        }*/
        $elBillList->appendChild($this->dom->createElement('G_MODEL', $info['g_model']));
        $elBillList->appendChild($this->dom->createElement('G_NAME_EN', $info['g_name_en']));
        //$QTY = round($info['hum_quantity_law'] * $info['quantity'], 3);
        //$QTY = round($info['hum_quantity_law'], 3);
        //$QTY = $info['hum_quantity_law'];
        /* $elBillList->appendChild($this->dom->createElement('G_QTY', $QTY));
        $elBillList->appendChild($this->dom->createElement('G_UNIT', $info['pu_code_law'])); */
        $elBillList->appendChild($this->dom->createElement('G_QTY', $info['g_qty']));
        $elBillList->appendChild($this->dom->createElement('G_UNIT', $info['g_unit']));
        //$DECL_PRICE = sprintf("%.4f", $info['product_declared_value']/$info['hum_quantity_law']);
        //$total_price = sprintf("%.2f", $info['total_price']);
        //$DECL_PRICE = sprintf("%.4f", $total_price/$info['quantity']);
        $elBillList->appendChild($this->dom->createElement('DECL_PRICE', $info['decl_price']));
        $elBillList->appendChild($this->dom->createElement('CURR', $info['curr']));
        $elBillList->appendChild($this->dom->createElement('QTY_1', $info['qty_1']));
        $elBillList->appendChild($this->dom->createElement('UNIT_1', $info['unit_1']));
        //$hum_quantity_second =  $info['pu_code_second'] ? $info['hum_quantity_second'] : '';
        $elBillList->appendChild($this->dom->createElement('QTY_2', $info['qty_2']));
        $elBillList->appendChild($this->dom->createElement('UNIT_2', $info['unit_2']));
        $elBillList->appendChild($this->dom->createElement('ORIGIN_COUNTRY', $info['origin_country']));	//固定110
        $elBillList->appendChild($this->dom->createElement('DUTY_MODE', '3'));	//固定3
        $elBillList->appendChild($this->dom->createElement('USE_TO', '11'));	//固定11
        $elBillList->appendChild($this->dom->createElement('NOTE_S', ''));
        $elBillList->appendChild($this->dom->createElement('CAR_NO', ''));
        $elBillList->appendChild($this->dom->createElement('URM_NO', ''));
        $elBillList->appendChild($this->dom->createElement('BIND_DATE', ''));
        $elBillList->appendChild($this->dom->createElement('CHANNEL_DATE', ''));
        /* $decl_total = sprintf("%.2f", $info['product_declared_value']*$info['quantity']);
        $elBillList->appendChild($this->dom->createElement('DECL_TOTAL', $decl_total)); */
        $elBillList->appendChild($this->dom->createElement('DECL_TOTAL', $info['decl_total']));
        //总单总价
        //$this->totalPrice += $total_price;
        return $elBillList;
    }

    /**
     * 生成XML文档
     * @param string $path
     * @return int|string
     */
    public function generate($path='') {
        if(empty($this->productList)) return false;
        $this->createMessage();
        $this->createHead();
        $this->createDeclaration();
        $this->createBillHead();
        $no = 0;
        foreach($this->productList as $product) {
            ++$no;
            $this->elBillHead->appendChild($this->createBillList($product));
        }
        $this->createBillContainer();
        $nodeList = $this->elBillHead->getElementsByTagName('NOTE_S');
        if($nodeList->length == 0) return false;
        $consignee = '收货人：'.$this->sbaRow['consignee'];
        $total = '总价：'.sprintf("%.2f", $this->shipBatchXml['total_price']);
        $nodeList->item(0)->nodeValue = $consignee.'  '.$total;
        if($path) return $this->dom->save($path);
        return $this->dom->saveXML();
    }

}
