<?php
/**
 * Created by JetBrains PhpStorm.
 * User: user
 * Date: 14-11-20
 * Time: 上午10:50
 * To change this template use File | Settings | File Templates.
 */
class Api_ServiceForOther
{
    protected $_customerId = null;

    protected $_customer = null;

    protected $_token = null;

    protected $_key = null;

    protected $_auth = false;

    protected $_error = null;

    protected $_date = null;

    protected $_paramterArr = array();//将传递过来的对象转为数组存储


    private function _init ($headerRequest) {
        $this->_customerId = (string) $headerRequest['customerCode'];
        $this->_token = (string) $headerRequest['appToken'];
        $this->_key = (string) $headerRequest['appKey'];
    }

    private function authenticate(){
        $customer = Service_Customer::getByField($this->_customerId, 'customer_code');
        if (! $customer || $customer['customer_status'] != 2) {
            $this->_error = 'No Authority For ' . $this->_customerId . '.';
            return false;
        }
        $this->_customer = $customer;
        $customerAuth = Service_CustomerApi::getByField($this->_customerId, 'customer_code');
        //file_put_contents('token.txt', $this->_token);

        //file_put_contents('authenticate.txt', var_export($customerAuth,true).$this->_customerId.$this->_token.'>>>>'. $this->_key);
        // return true;
        if ($customerAuth && $customerAuth['ca_token'] == $this->_token && $customerAuth['ca_key'] == $this->_key) {
            $this->_auth = true;
            return true;
        }
        $this->_error = 'App Token/App Key Not match for ' . $this->_customerId . '.';
        return false;
    }

    /**
     * @todo 写日志
     */
    private function logError ($error) {
        $logger = new Zend_Log();
        $uploadDir = APPLICATION_PATH . "/../data/log/";
        $writer = new Zend_Log_Writer_Stream($uploadDir . 'api-order.log');
        $logger->addWriter($writer);
        $logger->info(date('Y-m-d H:i:s') . ': ' . $error . " \n");
    }

    /**
     * @author william-fan
     * @todo 对wsdl 自动将多维数组转为一维数组的处理
     */
    private function multiArr ($arr) {
        $return = array();
        if(is_array($arr)){
            $isMulti = true;
            foreach($arr as $k=>$v){
                if(!is_int($k)){
                    $isMulti = false;
                }
            }
            if(!$isMulti){
                $return[] = $arr;
            }else{
                $return = $arr;
            }
        }else if(is_string($arr)){
            $return[] = $arr;
        }
        return $return;
    }

    private function common ($paramter) {
        // var_dump($paramter);exit;
        // 对象转数组
        $this->_paramterArr = Common_Common::objectToArray($paramter);//对象转数组
        $headRequest = $this->_paramterArr['HeaderRequest'];
        $this->_init($headRequest);
        //print_r($this->_paramterArr);
        //$this->_token = $this->_paramterArr['appToken'];
        //file_put_contents('error002.txt', '00000221'.$this->_token.var_export($this->_paramterArr,true));
        $this->_date = date('Y-m-d H:i:s');
        //file_put_contents('common.txt', '00000221'.$this->_token.var_export($this->_paramterArr,true));

        $this->authenticate();
        /* exit;
        file_put_contents('error003.txt', '0000020000555'.var_export($this->_paramterArr,true));return; */
    }

    public function createDistributor($paramter){
        $this->common($paramter);
        $result = array(
            'ask' => '1',
            'message' => "",
            'error' => array()
        );
        if ($this->_error) {
            $result['message'] = $this->_error;
            return $result;
        }
        $DistributorInfo = $this->_paramterArr['distributorInfo'];
        $code = trim($DistributorInfo['distributor_code']);
        $name = trim($DistributorInfo['distributor_name']);
        $status = intval(trim($DistributorInfo['distributor_status']));
        $error = array();
        $headRequest = $this->_paramterArr['HeaderRequest'];

        if (empty($code)) {
            array_push($error, '供应商代码不能为空');
        }
        elseif (Service_Distributor::isRepeatCode($code, $headRequest['customerCode'])) {
            array_push($error, '供应商代码【' . $code . '】已经存在');
        }

        if (empty($name)) {
            array_push($error, '供应商名称不能为空');
        }
        if(!empty($error)){
            $result['error'] = $error;
            return $result;
        }

        if (!in_array($status, array(0, 1), TRUE)) {
            $status = 1;
        }

        $data = array(
            'distributor_code' => $code,
            'distributor_name' => $name,
            'distributor_status' => $status,
            'distributor_creator' => $this->_customer['customer_id'],
            'distributor_created' => date('Y-m-d H:i:s'),
            'customer_code' => $this->_customer['customer_code']
        );

        Service_Distributor::insert($data);
        $result['ask'] = 1;
        $result['message'] = "供应商新增成功";
        return $result;
    }

    public function createPurchaseOrder($paramter){
        $this->common($paramter);
        $result = array(
            'ask' => '1',
            'message' => "",
        );
        if ($this->_error) {
            $result['message'] = $this->_error;
            return $result;
        }
        $PurchaseOrderInfo = $this->_paramterArr['purchaseOrderInfo'];
        //$date = date('Y-m-d H:i:s');
        $data = array(
            'po_code'=>$PurchaseOrderInfo['po_code'],
            'supply_code'=>$PurchaseOrderInfo['supply_code'],
            'po_description'=>$PurchaseOrderInfo['po_description'],
            'customer_id'=>$this->_customer['customer_id'],
            'customer_code'=>$this->_customer['customer_code'],
            'action'=>'create',
        );
        $productDetail = $PurchaseOrderInfo['productDetail'];
        $product_sku = array();
        $sku = array();
        foreach($productDetail as $key=>$value){
            if(!is_numeric($key)){
                $productList = Service_Product::getByCondition(array('product_sku'=>$value,'customer_id'=>$this->_customer['customer_id']),"*");
                $product = $productList[0];
                $product_sku[$product['product_id']] = $value;
                $sku[$product['product_id']] = $productDetail['quantity'];
                break;
            }else{
                $productList = Service_Product::getByCondition(array('product_sku'=>$value['product_sku'],'customer_id'=>$this->_customer['customer_id']),"*");
                $product = $productList[0];
                $product_sku[$product['product_id']] = $value['product_sku'];
                $sku[$product['product_id']] = $value['quantity'];
            }
        }
        $data['product_sku'] = $product_sku;
        $data['sku'] = $sku;
        $doresult = Service_PurchaseOrderProcess::createTransaction($data);
        $result['ask'] = $doresult['ask'];
        $result['message'] = $doresult['msg'];
        $result['error'] = $doresult['error'];

        return $result;

    }

    public function getOutReceivingInfo($paramter){
        $this->common($paramter);
        $result = array(
            'ask' => '0',
            'message' => "",
        );
        if ($this->_error) {
            $result['message'] = $this->_error;
            return $result;
        }
        $po_code = $this->_paramterArr['po_code'];
        $purchaseOrder = Service_PurchaseOrder::getByField($po_code,"po_code","*");
        if(empty($purchaseOrder)){
            $result['message'] = "采购单号不存在";
            return $result;
        }
        $condition = array(
            'po_code'=>$po_code,
        );
        $count = Service_PurchaseOrderTrackingBody::getJoinPurchaseTrackingBodyByCondition($condition, 'count(*)');
        if($count){
            $poList = Service_PurchaseOrderTrackingBody::getJoinPurchaseTrackingBodyByCondition($condition, '*', 0, 0, array('purchase_order_tracking.po_t_id desc','product.product_sku'));
            foreach( $poList as $key=>$row){
                if($row['po_id']){
                    $po = Service_PurchaseOrder::getByField($row['po_id'],'po_id');
                    if($po){
                        $poList[$key]['po_code'] = $po['po_code'];
                    }
                }
                if($row['receiving_id']){
                    $receive = Service_Receiving::getByField($row['receiving_id'],'receiving_id');
                    if($receive){$poList[$key]['receiving_code'] = $receive['receiving_code'];}
                }

                $poList[$key]['po_tb_status_text'] = Service_PurchaseOrderTrackingProcess::getStatusText($row['po_tb_status']);
                $poList[$key]['is_created_asn_text'] = Service_PurchaseOrderTrackingProcess::getIsCreateAsnText($row['is_created_asn']);
            }
            $result['ask'] = 1;
            $result['poData'] = $poList;
        }else{
            $result['message'] = "NO Data";
        }
        return $result;
    }

    public function closePurchase($paramter){
        $this->common($paramter);
        $result = array(
            'ask' => '1',
            'message' => "",
        );
        $poCode = $this->_paramterArr['po_code'];
        $PurchaseOrder = Service_PurchaseOrder::getByField($poCode,'po_code',"*");
        if(empty($PurchaseOrder)){
            $result['ask'] = '0';
            $result['message'] = "采购单".$poCode."不存在";
            return $result;
        }
        if($PurchaseOrder['po_status']=='-1'){
            $result['ask'] = '0';
            $result['message'] = "采购单".$poCode."已关闭";
            return $result;
        }
        $DB = Common_Common::getAdapter();
        $DB->beginTransaction();
        try{
            $updatePO = array(
                'po_status'=>'-1',
                'update_time'=>date("Y-m-d H:i:s"),
            );
            Service_PurchaseOrder::update($updatePO,$poCode,"po_code");
            $upob = array(
                'pobd_status'=>'-1',
            );
            Service_PurchaseOrderBody::update($upob,$PurchaseOrder['po_id'],"po_id");
            $DB->commit();
            $result['ask'] = '1';
            $result['message'] = "采购单".$poCode."关闭成功!";
        }catch (Exception $e){
            $DB->rollBack();
            $result['ask']='0';
            $result['message'] = "采购单".$poCode."关闭失败:".$e->getMessage();
        }
        return $result;
    }
}
