<?php
class Common_Rest
{

    /**
     * @创建订单
     * @param string $orderArray=array(),$abnormal=true 遇到库存不足、余额不足，自动为异常状态; false：创建失败回退
     * @return state=>0:失败;1=>成功 orderStatus:返回创建后订单状态;message=>array 失败原因
     */
    public function createOrder($orderArray,$abnormal)
    {
        $result = array('state' => 0, 'message' => array(), 'referenceNo' => '', 'orderCode' => '', 'orderStatus' => '');
        $error = array();
        try {

            $orderArray = Common_Common::authcode($orderArray, 'DECODE');

            //无法解析字符串
            if (empty($orderArray)) {
                $result['message'][] = 'Could not parse parameter.';
                return $result;
            }
            //解析
            $orderArray = unserialize($orderArray);

            //  return $orderArray;
            $orderKeys = array(
                'CustomerCode' => '',
                'OrderStatus' => '1',
                'ReferenceNo' => '',
                'ShippingMethod' => '',
                'parcelContents' => '',
                'parcelDeclaredValue' => '',
                'Country' => '',
                'FirstName' => '',
                'LastName' => '',
                'WarehouseCode' => '',
                'Address1' => '',
                'Address2' => '',
                'City' => '',
                'State/Provice' => '',
                'Postalcode' => '',
                'Email' => '',
                'Company' => '',
                'PhoneNo' => '',
                'remark' => '',
                'orderProduct' => array(),
            );
            foreach ($orderKeys as $key => $val) {
                $orderKeys[$key] = isset($orderArray[$key]) ? $orderArray[$key] : '';
            }


            $result['referenceNo'] = $orderKeys['ReferenceNo'];

            if ($orderKeys['CustomerCode'] == '') {
                $error[] = 'CustomerCode can not be null.';
            } else {
                $customerRow = Service_Customer::getByField($orderKeys['CustomerCode'], 'customer_code');
                if (empty($customerRow)) {
                    $error[] = 'CustomerCode: ' . $orderKeys['CustomerCode'] . '  can not be found.';
                } else {
                    $orderArr['customer_id'] = $customerRow['customer_id'];
                }
                $orderArr['customer_code'] = $orderKeys['CustomerCode'];
            }

            if ($orderKeys['ShippingMethod'] == '') {
                $error[] = 'ShippingMethod can not be null.';
            } else {
                $smRow = Service_ShippingMethod::getByField($orderKeys['ShippingMethod'], 'sm_code');
                if (!isset($smRow['sm_status']) || $smRow['sm_status'] != '1') {
                    $error[] = 'Shipping method is not Available.';
                }
                $orderArr['sm_code'] = $orderKeys['ShippingMethod'];
            }

            if ($orderKeys['WarehouseCode'] == '') {
                $error[] = 'WarehouseCode can not be null.';
            } else {
                $whRow = Service_Warehouse::getByField($orderKeys['WarehouseCode'], 'warehouse_code');
                if (!isset($whRow['warehouse_status']) || $whRow['warehouse_status'] != '1') {
                    $error[] = 'WarehouseCode:' . $orderKeys['WarehouseCode'] . ' can not be found.';
                } else {
                    $orderArr['warehouse_id'] = $whRow['warehouse_id'];
                }

            }

            if ($orderKeys['Country'] == '') {
                $error[] = 'Country can not be null.';
            } else {
                $countryRow = Service_Country::getByField($orderKeys['Country'], 'country_code');
                if (empty($countryRow)) {
                    $error[] = 'Country:' . $orderKeys['Country'] . ' can not be found.';
                } else {
                    $orderAddressArr['oab_country_id'] = $countryRow['country_id'];
                }
            }

            //参考号
            if (Service_OrderDispatchProcess::checkReferenceNo($orderKeys['ReferenceNo'], $orderKeys['CustomerCode'])) {
                $error[] = 'referenceNo ' . $orderKeys['ReferenceNo'] . ' exists;';
            }

            //订单产品
            $orderProductArr = array();
            if (!is_array($orderKeys['orderProduct'])) {
                $error[] = 'SKU can not be null.';
            } elseif (isset($orderArr['customer_id']) && $orderArr['customer_id'] != '') {
                foreach ($orderKeys['orderProduct'] as $product) {
                    if (isset($product['sku']) && isset($product['quantity'])) {
                        $productRows = Service_Product::getByCondition(array('product_sku' => $product['sku'], 'customer_id' => $orderArr['customer_id']));
                        if (empty($productRows)) {
                            $error[] = 'SKU: ' . $product['sku'] . '  can not be found.';
                            break;
                        }
                        if (!is_numeric($product['quantity']) || $product['quantity'] < 1) {
                            $error[] = 'SKU: ' . $product['sku'] . ' outlier quantity.';
                            break;
                        }
                        $orderProductArr[] = array(
                            'product_id' => $productRows[0]['product_id'],
                            'product_barcode' => $productRows[0]['product_barcode'],
                            'op_quantity' => $product['quantity'],
                            'op_category' => $productRows[0]['pc_id'],
                            'op_ref_tnx' => isset($product['refTnx']) ? $product['refTnx'] : '',
                            'op_ref_item_id' => isset($product['refItemId']) ? $product['refItemId'] : '',
                            'op_ref_buyer_id' => isset($product['refBuyerId']) ? $product['refBuyerId'] : '',
                            'op_ref_paydate' => isset($product['refPayDate']) ? $product['refPayDate'] : '',
                        );
                    } else {
                        $error[] = 'SKU can not be null.';
                        break;
                    }
                }
            }

            if (count($error) > 0) {
                $result['referenceNo']=$orderKeys['ReferenceNo'];
                $result['message'] = $error;
                return $result;
            }

            $orderArr['remark'] = $orderKeys['remark'];
            $orderArr['parcel_declared_value'] = $orderKeys['parcelDeclaredValue'];
            $orderArr['parcel_contents'] = $orderKeys['parcelContents'];
            $orderArr['reference_no'] = $orderKeys['ReferenceNo'];

            $orderAddressArr['oab_firstname'] = $orderKeys['FirstName'];
            $orderAddressArr['oab_lastname'] = $orderKeys['LastName'];
            $orderAddressArr['oab_company'] = $orderKeys['Company'];
            $orderAddressArr['oab_postcode'] = $orderKeys['Postalcode'];
            $orderAddressArr['oab_state'] = $orderKeys['State/Provice'];
            $orderAddressArr['oab_city'] = $orderKeys['City'];
            $orderAddressArr['oab_street_address1'] = $orderKeys['Address1'];
            $orderAddressArr['oab_street_address2'] = $orderKeys['Address2'];
            $orderAddressArr['oab_phone'] = $orderKeys['PhoneNo'];
            $orderAddressArr['oab_email'] = $orderKeys['Email'];

            $orderStatus = $orderKeys['OrderStatus'] != '' ? $orderKeys['OrderStatus'] : '1';
            $orderObj = new Service_OrderDispatchProcess();
            $return = $orderObj->createOrderTransaction($orderArr, $orderAddressArr, $orderProductArr, $orderStatus, $abnormal);

            if (isset($return['state']) && $return['state'] == '1') {
                $result = array('state' => 1, 'message' => array('success'), 'referenceNo' => $orderArr['reference_no'], 'orderCode' => $return['orderCode'], 'orderStatus' => $return['orderStatus']);
            } else {
                $result['state'] = 0;
                $result['message'] = isset($return['errorMessage']) ? $return['errorMessage'] : array('Fail');
            }
        } catch (Exception $e) {
            $result['message'][] = $e->getMessage();
        }
        return $result;
    }

    public function stopOrder($orderArray){
        $result = array('state' => 0, 'message' => array(), 'orderCode' =>'');
        $error = array();
        try {
            $orderArray = Common_Common::authcode($orderArray, 'DECODE');
            //无法解析字符串
            if (empty($orderArray)) {
                $result['message'] = 'Could not parse parameter.';
                return $result;
            }
            $orderArray = unserialize($orderArray);
            if (!isset($orderArray['CustomerCode']) || $orderArray['CustomerCode'] == '') {
                $result['message'] = 'CustomerCode can not be null.';
                return $result;
            }
            if (!isset($orderArray['OrderCode']) || $orderArray['OrderCode'] == '') {
                $result['OrderCode'] = 'OrderCode can not be null.';
                return $result;
            }
            $result['orderCode']=$orderArray['OrderCode'];
             $customerArr=Service_Customer::getByField($orderArray['CustomerCode'],'customer_code',array('customer_code'));
            if(empty($customerArr)){
                $result['message'] = 'CustomerCode:'.$orderArray['CustomerCode'].' can not be found.';
                return $result;
            }
           $orderRow= Service_Orders::getByField($orderArray['OrderCode'],'order_code');
            if(empty($orderRow) || !isset($orderRow['customer_code']) || $orderRow['customer_code']!=$customerArr['customer_code']){
                $result['message'] = 'OrderCode:'.$orderArray['OrderCode'].' can not be found..';
                return $result;
            }
            $obj=new Service_OrderDispatchProcess();
            $return= $obj->stopOrderTransaction($orderArray['OrderCode']);
            if(isset($return['state']) && $return['state']=='1' ){
                $result['state']=1;
                $result['message']='Operation Successfully Completed';
            }else{
                $result['message']=$return['message'];
            }
        } catch (Exception $e) {
            $result['message'] = $e->getMessage();
        }
        return $result;
    }


}