<?php

class Service_PoOrderProcess {

    protected $_orderCode = null;
    protected $_products = null;
    protected $_customerId = null;
    protected $_customerInfo = null;
    protected $_warehouseId = null;
    protected $_error;
    protected $_pro;
    protected $_receiving = array();
    protected $_date = '';

    public static function getPurchaseOrderStatus() {
        $status['-1'] = Ec_Lang::getInstance()->getTranslate('CloseStatus'); //'关闭';
        $status['1'] = Ec_Lang::getInstance()->getTranslate('CommonStatus'); //'正常';		
        return $status;
    }

    public static function getPurchaseOrderStatusText($status) {
        $status_array = self::getPurchaseOrderStatus();
        return $status_array[$status];
    }

    public static function getStatus() {
        $status['-1'] = Ec_Lang::getInstance()->getTranslate('CloseStatus'); //'关闭';
        $status['1'] = Ec_Lang::getInstance()->getTranslate('CommonStatus'); //'正常';


        return $status;
    }

    public static function getStatusText($status = 0) {
        $status_array = self::getStatus();
        return $status_array[$status];
    }

    public static $applicationType = array(
        1 => 'avrived',
        2 => 'receive',
        3 => 'putaway',
    );

    public function __construct() {

        $this->_date = date('Y-m-d H:i:s');
    }

    /**
     * @author colinyang
     * @todo 创建一条新的采购单
     * @param
     * @return array('ask' => 0, 'msg' => '','Error'=>array(array('errorCode'=>'','errorMessage')), 'ASNCode' => '');
     */
    public static function createTransaction($data) {
        $result = array('ask' => 0, 'msg' => '', 'error' => array(), 'ASNCode' => '');

        $error = self::validate($data);

        //var_dump($error);
        //exit('cccnnn');
        if (!empty($error)) {
            $result['error'] = $error;
            return $result;
        }
        //exit('fff00sssf');
        try {
            $DB = Common_Common::getAdapter();
            $DB->beginTransaction();
            $date = date('Y-m-d H:i:s');

            $po_row = array();
            $po_row['po_code'] = $data['po_code'];
            $po_row['customer_id'] = $data['customer_id'];
            $po_row['supply_code'] = $data['supply_code'];
            $po_row['po_status'] = '1';
            $po_row['create_time'] = $date;
            $po_row['update_time'] = $date;
            $po_id = Service_PoOrder::add($po_row);
            $product_sku = $data['product_sku'];
            $sku = $data['sku'];
            $note=$data['note'];
            foreach ($product_sku as $k => $v) {
                $productList = Service_Product::getByCondition(array('product_sku' => $v, 'customer_id' => $data['customer_id']), "*");
                $product = $productList[0];
                if (empty($product)) {
                    continue;
                }
                $po_detail = array(
                    'po_id' => $po_id,
                    'product_id' => $product['product_id'],
                    'order_quantity' => trim($sku[$k]),
                    'note'=>$note[$k],
                    'pobd_status' => '1'
                );

                if (!Service_PoOrderBody::add($po_detail)) {
                    throw new Exception(Ec_Lang::getInstance()->getTranslate('AddPurchaseOrderDetailsFail'));
                }
            }

            $result['ask'] = '1';
            $result['msg'] = "PO单[{$po_row['po_code']}]创建成功."; //'ASN创建成功';
            $result['ASNCode'] = $po_row['po_code'];

            $DB->commit();
        } catch (Exception $e) {
            $DB->rollBack();
            $result['error'][] = $e->getMessage();
            $result['msg'] = $e->getMessage();
            return $result;
        }
        return $result;
    }

    public function dealPostData($post) {
        $postData = array();
        //基本信息
//    	$baseinfo = array();
//    	$baseinfo['tracking_number'] = trim($this->_request->getParam('tracking_number',''));
//		$baseinfo['express_company'] = trim($this->_request->getParam('express_company',''));
        //产品信息
        $p_list = array();
        $po_tb_ids = isset($post['po_tb_id'])?$post['po_tb_id']:array();

        if (is_array($po_tb_ids) && count($po_tb_ids) > 0) {
            $po_code = $post['po_code'];
            $product_sku = $post['product_sku'];
            $received_quantity = $post['num'];
            $poId = $post['poId'];
            foreach ($po_tb_ids as $key => $po_tb_id) {
                $row = array();
                $row['po_tb_id'] = trim($po_tb_id);
                $row['po_bd_id'] = trim($poId[$key]);
                $row['po_code'] = trim($po_code[$key]);
                $row['product_sku'] = trim($product_sku[$key]);
                $row['received_quantity'] = trim($received_quantity[$key]);
                $p_list[] = $row;
            }
        }
//    	$postData['baseinfo'] = $baseinfo;    	
        $postData['p_list'] = $p_list;
        return $postData;
    }

    public function createPoOrderTracking($data) {
        $returnOrderTracking = array();
        foreach ($data['p_list'] as $i => &$p_info) {
            $orderTrackingBodyData = array();
            $orderTrackingBodyData['po_order_id'] = $p_info['po_id'];
            $orderTrackingBodyData['po_order_body_id'] = $p_info['po_bd_id'];
            $orderTrackingBodyData['product_id'] = $p_info['product_id'];
            $orderTrackingBodyData['received_quantity'] = $p_info['received_quantity']; //本次接受数量
            $orderTrackingBodyData['create_time'] = date('Y-m-d H:i:s');

            $poOrderBody = array();
              $poOrderBody['received_quantity'] = $p_info['old_received_quantity'] + $p_info['received_quantity'];
            if ($p_info['order_quantity'] == $p_info['old_received_quantity'] + $p_info['received_quantity']) {
                $orderTrackingBodyData['po_tb_status'] = '1'; //orderTrackingBody
                $poOrderBody['pobd_status'] = '-1'; //PurchaseOrderBody				
            } else {
                $poOrderBody['pobd_status'] = '1';
            }
            $returnOrderTracking[] = Service_PoOrderTracking::add($orderTrackingBodyData);
            Service_PoOrderBody::update($poOrderBody, $p_info['po_bd_id'], 'pobd_id');
        }
        return $returnOrderTracking;
    }

    public function validator(&$data) {
        $result = array();
        //产品信息
        if (isset($data['p_list']) && is_array($data['p_list'])) {
            $p_list = &$data['p_list'];
            if (empty($p_list) || count($p_list) == 0) {
                $result['p_list'] = '至少需要一条PO单';
            } else {
                foreach ($p_list as $i => &$p_info) {
                    $line = $i + 1;
                    if (!isset($p_info['po_bd_id']) || empty($p_info['po_bd_id'])) {
                        $result['p_list'] = '第[' . $line . ']行信息 ：错误的po单列表，请重新选择po单';
                        break;
                    } else {
                        $poOrderBody = Service_PoOrderBody::getByField($p_info['po_bd_id'], 'pobd_id');
                        if (empty($poOrderBody)) {
                            $result['p_list'] = '第[' . $line . ']行信息 ：PO单号号找不到';
                            break;
                        }
                    }
                    if ($poOrderBody['pobd_id']) {
                        if ($poOrderBody['pobd_status'] == '-1') {
                            $result['p_list'] = '第[' . $line . ']行信息 ：此PO单已经关闭';
                            break;
                        }
                        $purchaseBodyProduct = $poOrderBody;
                        $p_info['product_id'] = $purchaseBodyProduct['product_id'];
                        $p_info['old_received_quantity'] = $purchaseBodyProduct['received_quantity'];
                        $p_info['po_id'] = $purchaseBodyProduct['po_id'];
                        $p_info['order_quantity'] = $purchaseBodyProduct['order_quantity'];
                    }



                    if (!isset($p_info['received_quantity']) || empty($p_info['received_quantity'])) {
                        $result['p_list'] = '第[' . $line . ']行信息 ：请输入实收数量';
                        break;
                    } else {

                        if (!(preg_match("/^[0-9]+$/", $p_info['received_quantity']) && is_numeric($p_info['received_quantity']) && $p_info['received_quantity'] > 0 )) {
                            $result['p_list'] = '第[' . $line . ']条信息 ：实收数量必须为正整数';
                            break;
                        }
                        if ($purchaseBodyProduct['pobd_status'] == '-1') {
                            $result['p_list'] = '第[' . $line . ']条信息 ：对应PO单项已关闭';
                            break;
                        }

                        if ($purchaseBodyProduct['received_quantity'] + $p_info['received_quantity'] > $purchaseBodyProduct['order_quantity']) {

                            $result['p_list'] = '第[' . $line . ']条信息 ：实收数量+已收数量大于采购数量';
                            break;
                        }
                    }
                }//foreach

                if (empty($result)) {

                    $keylist = array();
                    foreach ($p_list as $i => $product_info) {
                        $line = $i + 1;
                        $key = trim($product_info['po_bd_id']);
                        if (isset($keylist[$key])) {
                            $result['p_list'] = '第[' . $line . ']条信息 ：数据重复';
                            break;
                        } else {
                            $keylist[$key] = $key;
                        }
                    }
                }
            }
        } else {
            $result['p_list'] = '数据错误';
        }
        return empty($result) ? true : $result;
    }

    /**
     * @author johnson
     * @todo 备货表单数据验证
     * @param array $data
     * @return array('ask' => 0, 'msg' => array(), 'data' => array());
     */
    public static function validate($data = array()) {
        $error = array();
        if (empty($data)) {
            $error[] = Ec_Lang::getInstance()->getTranslate('DataError'); //'数据出错';
            return $error;
        }
        if (!in_array($data['action'], array('create', 'update'))) {
            $error[] = Ec_Lang::getInstance()->getTranslate('DataError'); //'数据出错';
            return $error;
        }


        $total_weight = 0;
        if (isset($data['sku']) && !empty($data['sku'])) {
            $product_sku_array = $data['product_sku'];
            $number_array = $data['sku'];
            $notes=$data['note'];
            foreach ($number_array as $k => $number) {
                $number = trim($number);
                $product = Service_Product::getByField($k, 'product_id');
                if(strlen($notes[$k])>255){
                    $error[]='备注不能超过255个字符';
                }
                if (empty($product)) {
                    $error[] = Ec_Lang::getInstance()->getTranslate('product_not_exist');
                    continue;
                } else {
                    if ($product['product_type'] != '0') {
                        $error[] = Ec_Lang::getInstance()->getTranslate('can_not_combine_product');
                        continue;
                    }

                    if ($product['product_status'] != '1') {
                        $error[] = Ec_Lang::getInstance()->getTranslate('product_no_record');
                        continue;
                    }
                }
                $sku = $product_sku_array[$k];
                if (!(preg_match('/^[0-9]+$/i', $number) && is_numeric($number) && $number > 0)) {
                    $error[] = "产品SKU[{$sku}]" . Ec_Lang::getInstance()->getTranslate('NumberMustBeAnInteger');
                }
            }
        } else {
            $error[] = Ec_Lang::getInstance()->getTranslate('ProductsMusBeSelected');
        }



        if ("" == $data['po_code']) {
            $error[] = Ec_Lang::getInstance()->getTranslate('po_order_code_required'); //采购单号必填
        } else {

            if ($data['action'] == 'create') {
                $condition = array('po_code' => $data['po_code']);
                $po_orders = Service_PoOrder::getByCondition($condition, 'po_code');
                if ($po_orders) {
                    $error[] = Ec_Lang::getInstance()->getTranslate('po_order_code_exist'); //采购单号已经存在;
                }
            }

            if ($data['action'] == 'update' && $data['po_id']) {
                $condition = array('po_code' => $data['po_code']);
                $po_orders = Service_PoOrder::getByCondition($condition);
                if ($po_orders) {
                    foreach ($po_orders as $po_order) {
                        if ($po_order['po_id'] != $data['po_id']) {
                            $error[] = Ec_Lang::getInstance()->getTranslate('po_order_code_exist'); //采购单号已经存在;
                        }
                    }
                }
            }
        }


        if ($data['supply_code'] == '') {
            $error[] = Ec_Lang::getInstance()->getTranslate('supplier_code_required'); //'进出口口岸必填';
        } else {
            $supplies = Service_Customer::getByCondition(array('customer_code' => $data['supply_code'], 'customer_status' => '2', ''));
            if (empty($supplies)) {
                $error[] = Ec_Lang::getInstance()->getTranslate('supplier_code_not_exists'); //'进出口口岸必填';
            }
        }







        return $error;
    }

}

?>