<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Administrator
 * Date: 18-2-24
 * Time: 下午4:03
 * To change this template use File | Settings | File Templates.
 */
class Service_EnterpriseStorageServiceInterpreter
{
    /**
     * Globex海关注册编码、名称
     */
    const GLOBEX_CODE = '4403660028';
    const GLOBEX_NAME = '招海';

    /**
     * 账册号
     */
    const EMS_NO = 'I440363000114001';
    const Warehouse_No = "534908186250920180124000551425";

    /**
     * 特殊客户代码，不使用保宏WMS
     */
    private static $specialCustomer = array(
        'E0207',
        'E0110'
    );

    /**
     * 解析
     *
     * @param array $input
     * @return void
     */
    public static function interpret(array $input)
    {
        $response = array();

        try {
            $supportType = isset($input['supportType']) ? trim($input['supportType']) : '';

            if ('' === $supportType) { // 请求为空
                throw new Exception('Bad Request', 400);
            }

            $interpreter = 'support' . ucfirst($supportType);

            if (!method_exists(__CLASS__, $interpreter)) { // 请求方法不存在
                throw new Exception('Method Not Allowed', 405);
            }

            $fromTime = isset($input['fromTime']) ? trim($input['fromTime']) : '';
            $toTime   = isset($input['toTime']) ? trim($input['toTime']) : '';
            if ('' === $fromTime && '' === $toTime) {
                $postJson = file_get_contents('php://input');
                $jsonData = json_decode($postJson, true);

                if (isset($jsonData['fromTime'])) {
                    $fromTime = $jsonData['fromTime'];
                }

                if (isset($jsonData['toTime'])) {
                    $toTime = $jsonData['toTime'];
                }
            }
            $format   = '/^\d{4}\-\d{2}\-\d{2} \d{2}\:\d{2}\:\d{2}$/';

            if (!preg_match($format, $fromTime) || !preg_match($format, $fromTime)) {
                throw new Exception('Expectation Failed', 417);
            }

            $condition = array(
                'fromTime' => $fromTime,
                'toTime'   => $toTime,
            );

            $response = call_user_func(array(__CLASS__, $interpreter), $condition);
        } catch (Exception $e) {
            $response = array(
                'code'    => $e->getCode(),
                'message' => $e->getMessage(),
            );
        }

        header('content-type: application/json; charset=utf-8');

        echo json_encode($response, JSON_UNESCAPED_UNICODE);
    }

    /**
     * 获取库位货物信息
     *
     * LibCode: 库位代码
     * GName: 商品名称
     * GCode: 商品编码
     * SKU: 商品SKU
     * MaterialsCode": "商品料件号",
     * Unit: 法定单位
     * Quantity: 法定数量
     * Model: 规格型号
     * LOCALEMSNO: 园区账册号
     * EMSNO: H2010账册号
     * GOwnerCode: 货主企业海关编码
     * GOwnerName: 货主企业名称
     * STORECOMPANYNAME: 仓库使用企业名称
     * STOREUSCCODE: 仓库使用企业社会信用代码
     * STORECUSTOMSCODE: 仓库使用企业企业海关编码
     *
     * @param array $condition
     * @return array
     */
    private static function supportShelfGoodsInfos(array $condition)
    {
        $response = array(
            'LibPositionGoodsList' => array(
                'LibPositionGoodsInfo' => array(),
            ),
        );

        try {
            $db = Common_Common::getAdapter();

            $sql = <<<SQL
SELECT REPLACE(UUID(),"-","") AS id,inventory_batch.lc_code AS SEAT_NO,product.hs_goods_name AS GOODS_NAME,inventory_batch.receiving_code AS FORM_NO_DEC,inventory_batch.receiving_code AS FORM_NO,product.hs_code AS CODE_TS,product.product_sku AS SKU_NO,product.goods_id AS GOODS_ID,product.pu_code AS G_UNIT,sum(inventory_batch.ib_quantity) AS G_QYT,product.pu_code AS LEGAL_UNIT,inventory_batch.ib_quantity AS LEGAL_QYT,product.model_serial AS GOODS_MODEL,CONCAT("","I440363000114001") AS LOCAL_EMS_NO,customer.trade_co AS OWNER_CODE,customer.trade_name AS OWNER_NAME,CONCAT("深圳市招海国际货运代理有限公司","") AS STORE_COMPANY_NAME,CONCAT("","") AS STORE_USC_CODE,CONCAT("4403660028","") AS STORE_CUSTOMS_CODE,CONCAT("534908186250920180124000551425","") AS STORE_CODE,inventory_batch.ib_add_time AS  CREATE_TIME
FROM inventory_batch
INNER JOIN product  ON product.product_id=inventory_batch.product_id inner join customer on product.customer_id=customer.customer_id
WHERE customer.customer_platform='oms'
AND customer.customer_code<>'E0207'
AND customer.customer_code<>'E0110'
GROUP BY inventory_batch.product_id,inventory_batch.lc_code
SQL;

            /*if (!empty(self::$specialCustomer)) {
                $customerString = array();

                $customerList = Service_Customer::getByCondition(array('customer_platform'=>'oms','customer_status'=>2),"*");

                foreach ($customerList as $customerRow) {
                    if(!in_array($customerRow['customer_code'],self::$specialCustomer))
                        $customerString[] = "'{$customerRow['customer_code']}'";
                }

                $sql .= ' AND b.customer_code IN (' . implode(',', $customerString) . ')';
            }

            $sql .= ' GROUP BY a.product_id,a.lc_code';*/

            $resultSet = $db->fetchAll($sql);
            if(!empty($resultSet)){
                foreach($resultSet as $row){
                    if($row['G_QYT']==0) continue;
                    $row = self::checkNull($row);//过滤null

                    $response['LibPositionGoodsList']['LibPositionGoodsInfo'][] = array(
                        'LibCode'          => $row['SEAT_NO'],
                        'GName'            => $row['GOODS_NAME'],
                        'GCode'            => $row['CODE_TS'],
                        'SKU'              => $row['SKU_NO'],
                        'MaterialsCode'    => $row['GOODS_ID'],
                        'Unit'             => $row['G_UNIT'],
                        'Quantity'         => $row['G_QYT'],
                        'Model'            => $row['GOODS_MODEL'],
                        'LOCALEMSNO'       => self::EMS_NO,
                        //'EMSNO'            => self::EMS_NO,
                        'GOwnerCode'       => $row['OWNER_CODE'],
                        'GOwnerName'       => $row['OWNER_NAME'],
                        'STORECOMPANYNAME' => self::GLOBEX_NAME,
                        'STOREUSCCODE'     => self::GLOBEX_CODE,
                        'STORECUSTOMSCODE' => "",
                        'STORECODE'=>self::Warehouse_No,
                        'FORMNO'=>$row['FORM_NO'],
                        'FORMNODEC'=>$row['FORM_NO_DEC'],
                        'LEGALUNIT'=>$row['G_UNIT'],
                        'LEGALQYT'=> $row['G_QYT'],
                        'CREATETIME'=>date("Y-m-d",strtotime($row['CREATE_TIME']))."T".date("H:i:s",strtotime($row['CREATE_TIME'])),
                    );
                }
            }

            //while ($row = $resultSet->fetch()) {
                /*$customer = self::getCustomer($row['customer_code']);
                $receivingXml = Service_ReceivingXml::getByCondition(array('from_id'=>$row['receiving_code'],'goods_id'=>$row['goods_id']),"*");
                if(!empty($receivingXml)); $rxRow = Service_ReceivingXml::getByField($receivingXml['0']['sub_receiving_code'],"sub_receiving_code","*");
                $hsUom = Service_HsUom::getByField($row['hs_code'],"hs_code","*");
                $hsUomMap = Service_HsUomMap::getByField($row['product_id'],"product_id","*");*/
            //}
        } catch (Exception $e) {
            // Intentionally left blank.
        }

        return $response;
    }

    /**
     * 获取企业货物上下架信息
     *
     * GOODSNAME: 商品名称
     * CODETS: 商品编码
     * SKU: 商品SKU
     * MaterialsCode: 商品料件号
     * Unit: 法定单位
     * Quantity: 法定数量
     * GOODSMODEL: 规格型号
     * LOCALEMSNO: 园区账册号
     * EMSNO: H2010账册号
     * LibCode: 库位代码
     * InAndOutRackDate: 上/下架时间
     * RackType: 上下架类型
     * STORECOMPANYNAME: 仓库使用企业名称
     * STOREUSCCODE: 仓库使用企业社会信用代码
     * STORECUSTOMSCODE: 仓库使用企业企业海关编码
     *
     * @param array $condition
     * @return array
     */
    private static function supportShelfLoadInfos(array $condition)
    {
        $response = array(
            'InAndOutRackList' => array(
                'InAndOutRack' => array(),
            ),
        );

        try {
            $db = Common_Common::getAdapter();

            $inSql = <<<SQL
SELECT REPLACE(UUID(),"-","") AS id,product.hs_goods_name AS GOODS_NAME,product.hs_code AS CODE_TS,receiving_xml.refercence_form_id AS FORM_NO_DEC,receiving_xml.sub_receiving_code AS FORM_NO,
product.product_sku AS SKU_NO,product.goods_id AS GOODS_ID,product.pu_code AS UNIT,putaway_detail.pd_quantity AS QYT,product.model_serial AS GOODS_MODEL,CONCAT("","I440363000114001") AS LOCAL_EMS_NO,
putaway_detail.lc_code AS SEAT_NO,putaway_detail.pd_add_time AS SHELF_LOAD_TIME,CONCAT("","E") AS SHELF_LOAD_TYPE,CONCAT("","") AS STORE_COMPANY_NAME,
CONCAT("","") AS STORE_USC_CODE,CONCAT("4403660028","") AS STORE_CUSTOMS_CODE,CONCAT("534908186250920180124000551425","") AS STORE_CODE,putaway_detail.pd_add_time AS CREATE_TIME
FROM putaway_detail JOIN product ON product.product_id=putaway_detail.product_id JOIN  receiving_xml_detail on
( putaway_detail.receiving_code=receiving_xml_detail.from_id AND receiving_xml_detail.goods_id=product.goods_id)
join receiving_xml on receiving_xml.sub_receiving_code=receiving_xml_detail.sub_receiving_code JOIN customer ON customer.customer_id=product.customer_id
WHERE 1 AND product.product_status=1 AND customer.customer_platform='oms' AND putaway_detail.pd_status=1
AND putaway_detail.pd_add_time>='{$condition['fromTime']}' AND  putaway_detail.pd_add_time<'{$condition['toTime']}';
SQL;

            /*if (!empty(self::$specialCustomer)) {
                $customerString = array();

                $customerList = Service_Customer::getByCondition(array('customer_platform'=>'oms','customer_status'=>2),"*");

                foreach ($customerList as $customerRow) {
                    if(!in_array($customerRow['customer_code'],self::$specialCustomer))
                        $customerString[] = "'{$customerRow['customer_code']}'";
                }

                $inSql .= ' AND b.customer_code IN (' . implode(',', $customerString) . ')';
            }*/

            $resultSet = $db->fetchAll($inSql);
            if(!empty($resultSet)){
                foreach($resultSet as $row){
                    $row = self::checkNull($row);//过滤null
                    if($row['QYT']==""||$row['UNIT']=="") continue;

                    $response['InAndOutRackList']['InAndOutRack'][] = array(
                        'GOODSNAME'        => $row['GOODS_NAME'],
                        'CODETS'           => $row['CODE_TS'],
                        'SKU'              => $row['SKU_NO'],
                        'MaterialsCode'    => $row['GOODS_ID'],
                        'Unit'             => $row['UNIT'],
                        'Quantity'         => $row['QYT'],
                        'GOODSMODEL'       => $row['GOODS_MODEL'],
                        'LOCALEMSNO'       => self::EMS_NO,
                        //'EMSNO'            => self::EMS_NO,
                        'LibCode'          => $row['SEAT_NO'],
                        'InAndOutRackDate' => date("Y-m-d",strtotime($row['SHELF_LOAD_TIME']))."T".date("H:i:s",strtotime($row['SHELF_LOAD_TIME'])),
                        'RackType'         => 'I',
                        'STORECOMPANYNAME' => self::GLOBEX_NAME,
                        'STOREUSCCODE'     => self::GLOBEX_CODE,
                        'STORECUSTOMSCODE' => "",
                        'STORECODE'=>self::Warehouse_No,
                        'FromNo'=>$row['FORM_NO'],
                        'LEGALUNIT'=>$row['UNIT'],
                        'LEGALQYT'=>$row['QYT'],
                        'FromNoDec'=>$row['FORM_NO_DEC']==""?"":$row['FORM_NO_DEC'],
                    );
                }
            }
            //while ($row = $resultSet->fetch()) {
                /*$customer = self::getCustomer($row['customer_code']);
                $receivingXml = Service_ReceivingXmlDetail::getByCondition(array('from_id'=>$row['receiving_code'],'goods_id'=>$row['goods_id']),"*");
                if(!empty($receivingXml)) {
                    $rxRow = Service_ReceivingXml::getByField($receivingXml['0']['sub_receiving_code'],"sub_receiving_code","*");
                }else{
                    continue;
                }
                $hsUom = Service_HsUom::getByField($row['hs_code'],"hs_code","*");
                $hsUomMap = Service_HsUomMap::getByField($row['product_id'],"product_id","*");*/
            //}

            $outSql = <<<SQL
SELECT REPLACE(UUID(),"-","") AS id, product.hs_goods_name AS GOODS_NAME,product.hs_code AS CODE_TS,picking_detail.order_code AS FORM_NO_DEC,picking_detail.order_code AS FORM_NO,
product.product_sku AS SKU_NO,product.goods_id AS GOODS_ID,product.pu_code AS G_UNIT,picking_detail.pd_quantity AS G_QYT,
product.pu_code AS LEGAL_UNIT,picking_detail.pd_quantity AS LEGAL_QYT,product.model_serial AS GOODS_MODEL,CONCAT("","I440363000114001") AS LOCAL_EMS_NO,
picking_detail.lc_code AS SEAT_NO,picking_detail.pd_add_time AS SHELF_LOAD_TIME,CONCAT("","E") AS SHELF_LOAD_TYPE,CONCAT("","") AS STORE_COMPANY_NAME,
CONCAT("","") AS STORE_USC_CODE,CONCAT("4403660028","") AS STORE_CUSTOMS_CODE,CONCAT("534908186250920180124000551425","") AS STORE_CODE,
picking_detail.pd_add_time AS CREATE_TIME
FROM picking_detail
JOIN product ON product.product_id=picking_detail.product_id
JOIN orders ON orders.order_code=picking_detail.order_code
JOIN customer ON customer.customer_code=orders.customer_code
WHERE customer.customer_platform='oms'
AND customer.customer_code<>'E0207'
AND customer.customer_code<>'E0110'
and picking_detail.pd_add_time>='{$condition['fromTime']}'
AND  picking_detail.pd_add_time<'{$condition['toTime']}';
SQL;

            /*if (!empty(self::$specialCustomer)) {
                $customerString = array();

                $customerList = Service_Customer::getByCondition(array('customer_platform'=>'oms','customer_status'=>2),"*");

                foreach ($customerList as $customerRow) {
                    if(!in_array($customerRow['customer_code'],self::$specialCustomer))
                        $customerString[] = "'{$customerRow['customer_code']}'";
                }

                $outSql .= ' AND b.customer_code IN (' . implode(',', $customerString) . ')';
            }*/

            $resultSet = $db->fetchAll($outSql);
            if(!empty($resultSet)){
                foreach($resultSet as $row){
                    $row = self::checkNull($row);//过滤null
                    if($row['QYT']==""||$row['UNIT']=="") continue;

                    $response['InAndOutRackList']['InAndOutRack'][] = array(
                        'GOODSNAME'        => $row['GOODS_NAME'],
                        'CODETS'           => $row['CODE_TS'],
                        'SKU'              => $row['SKU_NO'],
                        'MaterialsCode'    => $row['GOODS_ID'],
                        'Unit'             => $row['G_UNIT'],
                        'Quantity'         => $row['G_QYT'],
                        'GOODSMODEL'       => $row['GOODS_MODEL'],
                        'LOCALEMSNO'       => self::EMS_NO,
                        //'EMSNO'            => self::EMS_NO,
                        'LibCode'          => $row['SEAT_NO'],
                        'InAndOutRackDate' => date("Y-m-d",strtotime($row['SHELF_LOAD_TIME']))."T".date("H:i:s",strtotime($row['SHELF_LOAD_TIME'])),
                        'RackType'         => 'E',
                        'STORECOMPANYNAME' => self::GLOBEX_NAME,
                        'STOREUSCCODE'     => self::GLOBEX_CODE,
                        'STORECUSTOMSCODE' => "",
                        'STORECODE'=>self::Warehouse_No,
                        'FromNo'=>$row['FORM_NO'],
                        'LEGALUNIT'=>$row['LEGAL_UNIT'],
                        'LEGALQYT'=>$row['LEGAL_QYT'],
                        'FromNoDec'=>$row['FORM_NO_DEC']==""?"":$row['FORM_NO_DEC'],
                    );
                }
            }

            //while ($row = $resultSet->fetch()) {
                /*$customer = self::getCustomer($row['customer_code']);
                $shipBatchSql = "select sb_code from ship_batch_detail join outbound_bag_detail on ship_batch_detail.ob_no=outbound_bag_detail.ob_no where outbound_bag_detail.order_code='".$row['order_code']."'";
                $db = Common_Common::getAdapter();
                $sbCode = $db->fetchRow($shipBatchSql);
                $shipBatchXmlDetail = Service_ShipBatchXmlDetail::getByCondition(array('sb_code'=>$sbCode['sb_code'],'goods_id'=>$row['goods_id']),"*");
                if(!empty($shipBatchXmlDetail)){
                    $shipBatchXml = Service_ShipBatchXml::getByField($shipBatchXmlDetail['0']['sub_sb_code'],"sub_sb_code","*");
                }else{
                    continue;
                }
                $hsUom = Service_HsUom::getByField($row['hs_code'],"hs_code","*");
                $hsUomMap = Service_HsUomMap::getByField($row['product_id'],"product_id","*");*/
            //}
        } catch (Exception $e) {
            // Intentionally left blank.
        }

        return $response;
    }

    /**
     * 获取企业货号海关料号对应关系
     *
     * SKU: 商品SKU
     * MaterialsCode: 商品料件号
     * GCode: 商品编码
     * GName: 商品名称
     * Model: 规格型号
     * GoodsIdUnit: 商品料件号对应计量单位
     * SkuUnit: 商品SKU对应计量单位
     * Ratio: 商品SKU对应商品料件号数量换算比例
     * Unit1: 法定单位
     * Unit2: 第二单位
     * STORECOMPANYNAME: 仓库使用企业名称
     * STOREUSCCODE: 仓库使用企业社会信用代码
     * STORECUSTOMSCODE: 仓库使用企业企业海关编码
     *
     * @param array $condition
     * @return array
     */
    private static function supportSkuPartRelations(array $condition)
    {
        $response = array(
            'GMRList' => array(
                'GoodsMaterialsRelation' => array(),
            ),
        );

        try {
            $db = Common_Common::getAdapter();

            $sql = <<<SQL
SELECT REPLACE(UUID(),"-","") AS id,product.product_sku AS SKU_NO,product.goods_id AS GOODS_ID,product.hs_code AS CODE_TS,product.hs_goods_name AS GOODS_NAME,
product.model_serial AS GOODS_MODEL,product.pu_code AS GOODS_ID_UNIT,product_uom.pu_name AS GOODS_ID_UNIT_NAME,product.pu_code AS SKU_UNIT,product_uom.pu_name AS SKU_UNIT_NAME,
CONCAT("","1:1") AS RATIO,CONCAT("招海","") AS STORE_COMPANY_NAME,CONCAT("","") AS STORE_USC_CODE,CONCAT("4403660028","") AS STORE_CUSTOMS_CODE,
product.product_add_time AS CREATE_TIME,product.pu_code AS UNIT1,CONCAT("","") AS UNIT2,CONCAT("534908186250920180124000551425","") AS STORE_CODE
FROM product
JOIN customer ON product.customer_code=customer.customer_code
JOIN product_uom ON product.pu_code=product_uom.pu_code
WHERE product.product_status=1
AND customer.customer_platform='oms'
AND customer.customer_code<>'E0207'
AND customer.customer_code<>'E0110'
AND customer.customer_status=2
AND product.product_status=1
AND product.product_add_time>='{$condition['fromTime']}'
AND product.product_add_time<'{$condition['toTime']}'
SQL;

            /*if (!empty(self::$specialCustomer)) {
                $customerString = array();

                $customerList = Service_Customer::getByCondition(array('customer_platform'=>'oms','customer_status'=>2),"*");

                foreach ($customerList as $customerRow) {
                    if(!in_array($customerRow['customer_code'],self::$specialCustomer))
                        $customerString[] = "'{$customerRow['customer_code']}'";
                }

                $sql .= ' AND customer_code IN (' . implode(',', $customerString) . ')';
            }*/

            $resultSet = $db->fetchAll($sql);
            if(!empty($resultSet)){
                foreach($resultSet as $row){
                    $unit     = self::getHscodeUnit($row['CODE_TS']);
                    //$customer = self::getCustomer($row['customer_code']);
                    $row = self::checkNull($row);//过滤null

                    $response['GMRList']['GoodsMaterialsRelation'][] = array(
                        'SKU'              => $row['SKU_NO'],
                        'MaterialsCode'    => $row['GOODS_ID'],
                        'GCode'            => $row['CODE_TS'],
                        'GName'            => $row['GOODS_NAME'],
                        'Model'            => $row['GOODS_MODEL'],
                        'GoodsIdUnit'      => $row['GOODS_ID_UNIT'],
                        'SkuUnit'          => $row['SKU_UNIT'],
                        'Ratio'            => '1:1',
                        'Unit1'            => $unit['unit1'],
                        'Unit2'            => $unit['unit2']==""?"":$unit['unit2'],
                        'STORECOMPANYNAME' => self::GLOBEX_NAME,
                        'STOREUSCCODE'     => self::GLOBEX_CODE,
                        'STORECUSTOMSCODE' => "",
                        'STORECODE'         =>self::Warehouse_No,
                    );
                }
            }

            /*while ($row = $resultSet->fetch()) {

            }*/
        } catch (Exception $e) {
            // Intentionally left blank.
        }

        return $response;
    }

    /**
     * 获取库存信息
     *
     * GName: 商品名称
     * GCode: 商品编码
     * SKU: 商品SKU
     * MaterialsCode": "商品料件号",
     * Unit: 法定单位
     * Quantity: 法定数量
     * Model: 规格型号
     * LOCALEMSNO: 园区账册号
     * EMSNO: H2010账册号
     * GOwnerCode: 货主企业海关编码
     * GOwnerName: 货主企业名称
     * STORECOMPANYNAME: 仓库使用企业名称
     * STOREUSCCODE: 仓库使用企业社会信用代码
     * STORECUSTOMSCODE: 仓库使用企业企业海关编码
     *
     * @param array $condition
     * @return array
     */
    private static function supportInventoryList(array $condition)
    {
        $response = array(
            'StockList' => array(
                'Stock' => array(),
            ),
        );

        try {
            $db = Common_Common::getAdapter();

            $sql = <<<SQL
SELECT REPLACE(UUID(),"-","") AS id,product.hs_goods_name AS GOODS_NAME,product.hs_code AS CODE_TS,product.product_sku AS SKU_NO,product.goods_id AS GOODS_ID,
product.pu_code AS UNIT,product_inventory.pi_sellable AS QYT,product.pu_code AS G_UNIT,product_inventory.pi_sellable AS G_QYT,product.pu_code AS LEGAL_UNIT,
product_inventory.pi_sellable AS LEGAL_QYT,product.model_serial AS GOODS_MODEL,CONCAT("","I440363000114001") AS LOCAL_EMS_NO,customer.trade_co AS OWNER_CODE,
customer.trade_name AS OWNER_NAME,CONCAT("深圳市招海国际货运代理有限公司","") AS STORE_COMPANY_NAME,CONCAT("","") AS STORE_USC_CODE,
CONCAT("4403660028","") AS STORE_CUSTOMS_CODE,product_inventory.pi_add_time AS CREATE_TIME
FROM product_inventory
JOIN product ON product_inventory.product_id=product.product_id
JOIN customer ON customer.customer_id=product.customer_id
WHERE product_inventory.pi_sellable>0
AND customer.customer_platform='oms'
AND customer.customer_code<>'E0110'
AND customer.customer_code<>'E0207'
GROUP by product_inventory.product_id ;
SQL;

            /*if (!empty(self::$specialCustomer)) {
                $customerString = array();

                $customerList = Service_Customer::getByCondition(array('customer_platform'=>'oms','customer_status'=>2),"*");

                foreach ($customerList as $customerRow) {
                    if(!in_array($customerRow['customer_code'],self::$specialCustomer))
                        $customerString[] = "'{$customerRow['customer_code']}'";
                }

                $sql .= ' AND b.customer_code IN (' . implode(',', $customerString) . ')';
            }*/

            $resultSet = $db->fetchAll($sql);
            if(!empty($resultSet)){
                foreach($resultSet as $row){
                    $row = self::checkNull($row);//过滤null

                    $response['StockList']['Stock'][] = array(
                        'GName'            => $row['GOODS_NAME'],
                        'GCode'            => $row['CODE_TS'],
                        'SKU'              => $row['SKU_NO'],
                        'MaterialsCode'    => $row['GOODS_ID'],
                        'Unit'             => $row['UNIT'],
                        'Quantity'         => $row['QYT'],
                        'Model'            => $row['GOODS_MODEL'],
                        'LOCALEMSNO'       => self::EMS_NO,
                        //'EMSNO'            => self::EMS_NO,
                        'GOwnerCode'       => $row['OWNER_CODE'],
                        'GOwnerName'       => $row['OWNER_NAME'],
                        'STORECOMPANYNAME' => self::GLOBEX_NAME,
                        'STOREUSCCODE'     => self::GLOBEX_CODE,
                        'STORECUSTOMSCODE' => "",
                        'STORECODE'         =>self::Warehouse_No,
                        'LEGALUNIT'=>$row['UNIT'],
                        'LEGALQYT'=>$row['QYT'],
                        'CREATETIME'=>date("Y-m-d",strtotime($row['pi_add_time']))."T".date("H:i:s",strtotime($row['pi_add_time'])),
                    );
                }
            }

            //while ($row = $resultSet->fetch()) {
                /*$customer = self::getCustomer($row['customer_code']);
                $quantity = $row['pi_sellable'] + $row['pi_unsellable'] + $row['pi_reserved'] ; // + $row['pi_receiving_less'];
                if($quantity==0) continue;
                $hsUom = Service_HsUom::getByField($row['hs_code'],"hs_code","*");
                $hsUomMap = Service_HsUomMap::getByField($row['product_id'],"product_id","*");*/

            //}
        } catch (Exception $e) {
            // Intentionally left blank.
        }

        return $response;
    }

    /**
     * 获取 企业货物出入库 信息
     *
     * CarNO: 车牌号
     * CheckNO: 核放单号
     * WareHouseBillCode: 报关申请单号
     * Type: 出入类型 I:入 E：出
     * BillNo: 出入仓单号
     * STORECOMPANYNAME: 仓库使用企业名称
     * STOREUSCCODE: 仓库使用企业社会信用代码
     * STORECUSTOMSCODE: 仓库使用企业企业海关编码
     * IETIME: 出入仓时间
     * STORECODE: 仓库编码
     * @param array $condition
     * @return array
     */
    private static function supportGoodInOutList(array $condition){
        $response = array(
            'InAndOutLibList' => array(
                'InAndOutLib' => array(),
            ),
        );

        try {
            $db = Common_Common::getAdapter();

            $inSql = <<<SQL
SELECT REPLACE(UUID(),"-","") AS id,receiving.traf_name AS CAR_NO,CONCAT("I","") AS I_E_TYPE,
receiving.refercence_form_id AS URM_NO,receiving.receiving_code AS FORM_NO,
receiving.receiving_code AS BILL_NO,CONCAT("深圳市招海国际货运代理有限公司","") AS STORE_COMPANY_NAME,CONCAT("","") AS STORE_USC_CODE,
CONCAT("4403660028","") AS STORE_CUSTOMS_CODE,CONCAT("534908186250920180124000551425","") AS STORE_CODE,
receiving.receiving_update_time AS LOAD_TIME,receiving.receiving_update_time AS I_E_TIME,receiving.receiving_update_time AS CREATE_TIME
 FROM receiving
 JOIN customer ON customer.customer_code=receiving.customer_code
 WHERE customer.customer_platform='oms'
 AND customer.customer_code<>'E0207'
 AND customer.customer_code<>'E0110'
 AND receiving.receiving_status=7
AND receiving.receiving_update_time>='{$condition['fromTime']}'
AND receiving.receiving_update_time<'{$condition['toTime']}'
SQL;

            /*if (!empty(self::$specialCustomer)) {
                $customerString = array();

                $customerList = Service_Customer::getByCondition(array('customer_platform'=>'oms','customer_status'=>2),"*");

                foreach ($customerList as $customerRow) {
                    if(!in_array($customerRow['customer_code'],self::$specialCustomer))
                        $customerString[] = "'{$customerRow['customer_code']}'";
                }

                $inSql .= ' customer_code IN (' . implode(',', $customerString) . ')';
            }*/
            $resultSet = $db->fetchAll($inSql);
            if(!empty($resultSet)){
                foreach($resultSet as $row){
                    $row = self::checkNull($row);//过滤null

                    $response['InAndOutLibList']['InAndOutLib'][] = array(
                        'CarNO'         => $row['CAR_NO'],
                        'CheckNO'       => $row['URM_NO'],
                        'WareHouseBillCode'              => $row['FORM_NO'],
                        'Type'          => "I",
                        'BillNo'             => $row['BILL_NO'],
                        'STORECOMPANYNAME' => self::GLOBEX_NAME,
                        'STOREUSCCODE'     => self::GLOBEX_CODE,
                        'STORECUSTOMSCODE' => "",
                        'IETIME'=>date("Y-m-d",strtotime($row['LOAD_TIME']))."T".date("H:i:s",strtotime($row['LOAD_TIME'])),
                        'STORECODE'=>self::Warehouse_No,
                    );
                }
            }

            //while ($row = $resultSet->fetch()) {
                //$receivingRow = Service_Receiving::getByField($row['receiving_code'],'receiving_code',"*");
                //$customer = self::getCustomer($receivingRow['customer_code']);

            //}

            $outSql = <<<SQL
SELECT REPLACE(UUID(),"-","") AS id,ship_batch.sb_truck_no AS CAR_NO,CONCAT("E","") AS I_E_TYPE,ship_batch.FORM_ID_XML AS URM_NO,
ship_batch.sb_code AS FORM_NO,ship_batch.sb_code AS BILL_NO,CONCAT("深圳保宏电子商务综合服务股份有限公司","") AS STORE_COMPANY_NAME,
CONCAT("","") AS STORE_USC_CODE,CONCAT("4403660028","") AS STORE_CUSTOMS_CODE,CONCAT("534908186250920180124000551425","") AS STORE_CODE,
ship_batch.sb_update_time AS I_E_TIME,ship_batch.sb_add_time AS CREATE_TIM,CONCAT("","") AS CAR_POSITION
FROM ship_batch
JOIN ship_batch_detail ON ship_batch_detail.sb_code=ship_batch.sb_code
WHERE 1 AND sb_status=3
AND ship_batch.sb_update_time>='{$condition['fromTime']}'
AND ship_batch.sb_update_time<'{$condition['toTime']}'
SQL;

            /*if (!empty(self::$specialCustomer)) {
                $customerString = array();

                $customerList = Service_Customer::getByCondition(array('customer_platform'=>'oms','customer_status'=>2),"*");

                foreach ($customerList as $customerRow) {
                    if(!in_array($customerRow['customer_code'],self::$specialCustomer))
                        $customerString[] = "'{$customerRow['customer_code']}'";
                }

                $outSql .= ' AND b.customer_code IN (' . implode(',', $customerString) . ')';
            }*/

            $resultSet = $db->fetchAll($outSql);
            if(!empty($resultSet)){
                foreach($resultSet as $row){
                    $row = self::checkNull($row);//过滤null

                    $response['InAndOutLibList']['InAndOutLib'][] = array(
                        'CarNO'         => $row['CAR_NO'],
                        'CheckNO'       => $row['URM_NO'],
                        'WareHouseBillCode'              => $row['FORM_NO'],
                        'Type'          => "E",
                        'BillNo'             => $row['BILL_NO'],
                        'STORECOMPANYNAME' => self::GLOBEX_NAME,
                        'STOREUSCCODE'     => self::GLOBEX_CODE,
                        'STORECUSTOMSCODE' => "",
                        'IETIME'=>date("Y-m-d",strtotime($row['I_E_TIME']))."T".date("H:i:s",strtotime($row['I_E_TIME'])),
                        'STORECODE'=>self::Warehouse_No,
                    );
                }
            }

            //while ($row = $resultSet->fetch()) {
                //$receivingRow = Service_ReceivingXml::getByCondition(array('from_id'=>$row['receiving_code'],'goods_id'=>$row['goods_id']),"*");
                //$customer = self::getCustomer($receivingRow['customer_code']);

            //}
        } catch (Exception $e) {
            // Intentionally left blank.
        }

        return $response;

    }

    private function supportGoodsMoveList(array $condition){
        $response = array(
            'GoodsMoveList' => array(
                'GoodsMoveInfo' => array(),
            ),
        );

        try {
            $db = Common_Common::getAdapter();

            $sql = <<<SQL
SELECT
REPLACE(UUID(),"-","") AS id,
inventory_change_log.operation_time AS SHELF_LOAD_TIME,
DATE_SUB(inventory_change_log.operation_time,interval 10 minute) AS SHELF_UNLOAD_TIME,
inventory_change_log.original_shelf_code AS TARGET_SEAT_NO,
inventory_change_log.to_shelf_code AS ORIGIN_SEAT_NO,
product.hs_goods_name AS GOODS_NAME,
product.hs_code AS CODE_TS,
product.product_sku AS SKU_NO,
product.goods_id AS GOODS_ID,
product.pu_code AS G_UNIT,
inventory_change_log.original_quantity AS G_QYT,
product.pu_code AS LEGAL_UNIT,
inventory_change_log.original_quantity AS LEGAL_QYT,
product.model_serial AS GOODS_MODEL,
CONCAT("","I440363000114001") AS LOCAL_EMS_NO,
CONCAT("深圳市招海国际货运代理有限公司","") AS STORE_COMPANY_NAME,
CONCAT("","") AS STORE_USC_CODE,
CONCAT("4403660028","") AS STORE_CUSTOMS_CODE,
CONCAT("534908186250920180124000551425","") AS STORE_CODE
FROM inventory_change_log
JOIN product ON product.product_id=inventory_change_log.product_id
JOIN customer ON product.customer_code=customer.customer_code
WHERE 1
AND customer.customer_platform='oms'
AND customer.customer_code<>'E0207'
AND customer.customer_code<>'E0110'
AND inventory_change_log.operation_time>='{$condition['fromTime']}'
AND inventory_change_log.operation_time<'{$condition['toTime']}'
;
SQL;

            $resultSet = $db->fetchAll($sql);
            if(!empty($resultSet)){
                foreach($resultSet as $row){
                    $row = self::checkNull($row);//过滤null

                    $response['GoodsMoveList']['GoodsMoveInfo'][] = array(
                        'InRackDate'            => $row['SHELF_LOAD_TIME'],
                        'OutRackDate'            => $row['SHELF_UNLOAD_TIME'],
                        'SourceLibCode'              => $row['TARGET_SEAT_NO'],
                        'NowLibCode'    => $row['ORIGIN_SEAT_NO'],
                        'GOODSNAME'             => $row['GOODS_NAME'],
                        'CODETS'         => $row['CODE_TS'],
                        'SKU'            => $row['SKU_NO'],
                        'MaterialsCode'            => $row['GOODS_ID'],
                        'Unit'            => $row['G_UNIT'],
                        'Quantity'            => $row['G_QYT'],
                        'GOODSMODEL'            => $row['GOODS_MODEL'],
                        'LOCALEMSNO'       => self::EMS_NO,
                        //'EMSNO'            => self::EMS_NO,
                        'STORECOMPANYNAME' => self::GLOBEX_NAME,
                        'STOREUSCCODE'     => self::GLOBEX_CODE,
                        'STORECUSTOMSCODE' => "",
                        'STORECODE'         =>self::Warehouse_No,
                        //'CREATETIME'=>date("Y-m-d",strtotime($row['pi_add_time']))."T".date("H:i:s",strtotime($row['pi_add_time'])),
                    );
                }

            }

            /*while ($row = $resultSet->fetch()) {
                /*$customer = self::getCustomer($row['customer_code']);
                $quantity = $row['pi_sellable'] + $row['pi_unsellable'] + $row['pi_reserved'] ; // + $row['pi_receiving_less'];
                if($quantity==0) continue;
                $hsUom = Service_HsUom::getByField($row['hs_code'],"hs_code","*");
                $hsUomMap = Service_HsUomMap::getByField($row['product_id'],"product_id","*");*/

            //}
        } catch (Exception $e) {
            // Intentionally left blank.
        }

        return $response;

    }

    private function supportCarLoadInfoList(array $condition){
        $response = array(
            'LoadingGoods' => array(
                'LoadingGoodInfo' => array(),
            ),
        );

        try {
            $db = Common_Common::getAdapter();

            $inSql = <<<SQL
SELECT REPLACE(UUID(),"-","") AS id,receiving.traf_name AS CAR_NO,receiving.refercence_form_id AS URM_NO,receiving.receiving_code AS BILL_NO,
receiving.receiving_code AS FORM_NO,CONCAT("I","") AS LOAD_TYPE,CONCAT("深圳保宏电子商务综合服务股份有限公司","") AS STORE_COMPANY_NAME,CONCAT("","") AS STORE_USC_CODE,
CONCAT("4403660028","") AS STORE_CUSTOMS_CODE,CONCAT("534908186250920180124000551425","") AS STORE_CODE,receiving.receiving_update_time AS LOAD_TIME,
receiving.receiving_add_time AS CREATE_TIM,CONCAT("","") AS CAR_POSITION
FROM receiving JOIN customer ON customer.customer_code=receiving.customer_code
WHERE customer.customer_platform='oms'
AND customer.customer_code<>'E0207'
AND customer.customer_code<>'E0110'
AND receiving.receiving_status=7
AND receiving.receiving_update_time>='{$condition['fromTime']}'
AND receiving.receiving_update_time<'{$condition['toTime']}'
SQL;

            $resultSet = $db->fetchAll($inSql);
            if(!empty($resultSet)){
                foreach($resultSet as $row){
                    $row = self::checkNull($row);//过滤null

                    $response['LoadingGoods']['LoadingGoodInfo'][] = array(
                        'CarNO'         => $row['CAR_NO'],
                        'CheckNO'       => $row['URM_NO'],
                        'LibCode'              => $row['BILL_NO'],
                        'Type'          => "I",
                        'BillCode'             => $row['FORM_NO'],
                        'STORECOMPANYNAME' => self::GLOBEX_NAME,
                        'STOREUSCCODE'     => self::GLOBEX_CODE,
                        'STORECUSTOMSCODE' => "",
                        'IETIME'=>date("Y-m-d",strtotime($row['LOAD_TIME']))."T".date("H:i:s",strtotime($row['LOAD_TIME'])),
                        'STORECODE'=>self::Warehouse_No,
                    );
                }
            }

            //while ($row = $resultSet->fetch()) {
                //$receivingRow = Service_Receiving::getByField($row['receiving_code'],'receiving_code',"*");
                //$customer = self::getCustomer($receivingRow['customer_code']);
            //}

            $outSql = <<<SQL
SELECT REPLACE(UUID(),"-","") AS id,ship_batch.sb_truck_no AS CAR_NO,ship_batch.FORM_ID_XML AS URM_NO,ship_batch.sb_code AS BILL_NO,
ship_batch.sb_code AS FORM_NO,CONCAT("E","") AS LOAD_TYPE,CONCAT("深圳保宏电子商务综合服务股份有限公司","") AS STORE_COMPANY_NAME,
CONCAT("","") AS STORE_USC_CODE,CONCAT("4403660028","") AS STORE_CUSTOMS_CODE,CONCAT("534908186250920180124000551425","") AS STORE_CODE,
ship_batch.sb_update_time AS LOAD_TIME,ship_batch.sb_add_time AS CREATE_TIM,CONCAT("","") AS CAR_POSITION
FROM ship_batch
JOIN ship_batch_detail ON ship_batch_detail.sb_code=ship_batch.sb_code
WHERE 1
AND sb_status=3
AND ship_batch.sb_update_time>='{$condition['fromTime']}'
AND ship_batch.sb_update_time<'{$condition['toTime']}'
SQL;


            $resultSet = $db->fetchAll($outSql);
            if(!empty($resultSet)){
                foreach($resultSet as $row){
                    $row = self::checkNull($row);//过滤null

                    $response['LoadingGoods']['LoadingGoodInfo'][] = array(
                        'CarNO'         => $row['CAR_NO'],
                        'CheckNO'       => $row['URM_NO'],
                        'LibCode'              => $row['BILL_NO'],
                        'Type'          => "E",
                        'BillCode'             => $row['FORM_NO'],
                        'STORECOMPANYNAME' => self::GLOBEX_NAME,
                        'STOREUSCCODE'     => self::GLOBEX_CODE,
                        'STORECUSTOMSCODE' => "",
                        'IETIME'=>date("Y-m-d",strtotime($row['LOAD_TIME']))."T".date("H:i:s",strtotime($row['LOAD_TIME'])),
                        'STORECODE'=>self::Warehouse_No,
                    );
                }
            }

            /*while ($row = $resultSet->fetch()) {

            }*/
        } catch (Exception $e) {
            // Intentionally left blank.
        }

        return $response;
    }

    /**
     * 获取产品规格型号
     *
     * @param integer $productId
     * @return string
     */
    private static function getProductModel($productId)
    {
        $modelSet   = array();
        $elementSet = Service_HsElementMap::getByCondition(array(
            'product_id' => $productId,
        ));

        if (!empty($elementSet)) {
            foreach ($elementSet as $item) {
                if ('' !== trim($item['hem_detail'])) {
                    $modelSet[] = $item['hem_detail'];
                }
            }
        }

        return implode('|', $modelSet);
    }

    /**
     * 获取海关编码对应法定单位
     *
     * @param string $hsCode
     * @return array
     */
    private static function getHscodeUnit($hsCode)
    {
        $unit = array(
            'unit1' => '',
            'unit2' => '',
        );

        $hsUom = Service_HsUom::getByField($hsCode, 'hs_code');

        if (!empty($hsUom)) {
            $unit['unit1'] = trim($hsUom['pu_code_law']);
            $unit['unit2'] = trim($hsUom['pu_code_second']);
        }

        return $unit;
    }

    /**
     * 获取客户信息
     *
     * @param string $customerCode
     * @return array
     */
    private static function getCustomer($customerCode)
    {
        $customer = array(
            'cus_name' => '',
            'ecp_code' => '',
            'trade_co' => '',
            'trade_name'=>'',
        );

        $record = Service_Customer::getByField($customerCode, 'customer_code');

        if (!empty($record)) {
            $customer['cus_name'] = $record['cus_name'];
            $customer['ecp_code'] = $record['ecp_code'];
            $customer['trade_co'] = $record['trade_co'];
            $customer['trade_name'] = $record['trade_name'];
        }

        return $customer;
    }

    private static function checkNull($data){
        $returnData = array();
        foreach($data as $key=>$value){
            if($value==""){
                $returnData[$key] = "";
            }else{
                $returnData[$key] = $value;
            }
        }
        return $returnData;
    }
}
