<?php

class Merchant_PoController extends Ec_Controller_Action {

    public function preDispatch() {
        $this->tplDirectory = "merchant/views/po/";
        $this->customerId = $this->_customerAuth['id'];
    }

    /* 创建采购单 */

    public function createAction() {
        $this->view->actions = '创建PO单'; //"新增";
        $this->view->actionLabel = "add";
        echo Ec::renderTpl($this->tplDirectory . 'po-order-create.tpl', 'noleftlayout');
    }

    /*
     * 获取供应商列表
     */

    public function supplycodeAction() {
        $customer = $this->_customerAuth;
        $page = $this->getRequest()->getParam('page', 1);
        $pageSize = $this->getRequest()->getParam('pageSize', 20);

        $selected_supply_code = $this->_request->getParam("selected_supply_code", "");
        $supplier_code = $this->_request->getParam("supplier_code", "");
        $supplier_name = $this->_request->getParam("supplier_name", "");

        $condition = array(
            'customer_company_name_like' => $supplier_name,
            'customer_code' => $supplier_code,
            'customer_status' => '2',
            'customer_type' => '1',
        );

        $from = 'po_order';


        $this->view->from = $from;
        $this->view->params = $condition;
        $this->view->pageSize = $pageSize;
        $this->view->page = $page;
        $this->view->selected_supply_code = $selected_supply_code;

        $this->view->count = Service_Customer::getByCondition($condition, 'count(*)');

        $result = Service_Customer::getByCondition($condition, '*', $pageSize, $page);
        $this->view->result = $result;
        echo $this->view->render($this->tplDirectory . "po-supplyer.tpl");
    }

    //新增po单		
    public function orderSaveAction() {
        if ($this->_request->isPost()) {
            $data = $this->getRequest()->getParams();
            if ($data) {
                foreach ($data as $k => &$v) {
                    if (!is_array($v)) {
                        $v = trim($v);
                    }
                }
            }

            $customer = $this->_customerAuth;
            $data['customer_id'] = $customer['id'];
            $data['customer_code'] = $customer['code'];
            $data['action'] = 'create';
            $doresult = Service_PoOrderProcess::createTransaction($data);

            //print_r($doresult);
            if (isset($doresult['msg'])) {
                $result['msg'] = $doresult['msg'];
            }
            $result['error'] = $doresult['error'];
            $result['ask'] = $doresult['ask'];
            $result['ASNCode'] = $doresult['ASNCode'];
            die(json_encode($result));
        }
    }

    /* PO单列表 */

    public function listAction() {
        $customer = $this->_customerAuth;

        $purchase_order_status_list = Service_PoOrderProcess::getStatus();

        //if ($this->_request->isPost()) {
        //$customerId = $this->customerId;
        $customerId = $customer['id'];
        $page = $this->_request->getParam('page', 1);
        $pageSize = $this->_request->getParam('pageSize', 20);

        $po_code = trim($this->_request->getParam('po_code', ''));
        $product_sku = trim($this->_request->getParam('product_sku', ''));
        $pobd_status = $this->_request->getParam('pobd_status', '');

        $created_start = trim($this->_request->getParam('created_start', ''));
        $created_end = trim($this->_request->getParam('created_end', ''));
        $productTitle = trim($this->_request->getParam('T1', ''));
        $params = array();
        $params['created_start'] = $created_start;
        $params['created_end'] = $created_end;
        $params['product_sku'] = $product_sku;
        $params['po_code'] = $po_code;
        $params['pobd_status'] = $pobd_status;
        $params['product_title'] = $productTitle;
        $created_start = ($created_start) ? $created_start . ' 00:00:00' : '';
        $created_end = ($created_end) ? $created_end . ' 59:59:59' : '';

        $page = $page ? $page : 1;
        $pageSize = $pageSize ? $pageSize : 20;
        $condition = array(
            'po_code' => $po_code,
            'product_sku' => $product_sku,
            'pobd_status' => $pobd_status,
            'created_start' => $created_start,
            'created_end' => $created_end,
            'customer_id' => $customerId,
            'product_title' => $productTitle,
        );
        $isSupplier = Service_Customer::checkIsService();
        if ($isSupplier) {
            unset($condition['customer_id']);
            $condition['supply_code'] = $customer['code'];
        }
        $count = Service_PoOrderBody::getJoinPoBodyByCondition($condition, 'count(*)');
        $result = '';
        $customerCompany = array();
        if ($count > 0) {
            $result = Service_PoOrderBody::getJoinPoBodyByCondition($condition, '*', $pageSize, $page, array('po_order.po_id desc', 'product.product_sku'));
            foreach ($result as &$row) {
                $row['pobd_status_text'] = Service_PoOrderProcess::getStatusText($row['pobd_status']);
                if ($isSupplier) {
                    if (!isset($customerCompany[$row['customer_id']])) {
                        $customerCompany[$row['customer_id']] = Service_Customer::getByField($row['customer_id'], 'customer_id');
                    }
                    $row['customer_company_name'] =$customerCompany[$row['customer_id']]['customer_code'].' '. $customerCompany[$row['customer_id']]['customer_company_name'];
                }
                $row['is_supplyer'] = $isSupplier;
            }
        }



        $this->view->page = $page;
        $this->view->pageSize = $pageSize;
        $this->view->count = $count;
        $this->view->isSupplier = $isSupplier;
        //die(Zend_Json::encode($return));
        //}

        $this->view->result = $result;
        $this->view->params = $params;
        $this->view->purchase_order_status_list = $purchase_order_status_list;
        echo Ec::renderTpl($this->tplDirectory . "po-list.tpl", 'noleftlayout');
    }

    /*
     * 获取供应商选择客户的po列表
     */

    public function getPoListAction() {
        $page = $this->getRequest()->getParam('page', 1);
        $pageSize = $this->getRequest()->getParam('pageSize', 20);
        $selectCustom = $this->_request->getParam('select_custom', '');
        $createTimeStart = $this->_request->getParam('time_start', '');
        $createTimeEnd = $this->_request->getParam('time_end', '');
        $loginUserSession = $this->_customerAuth;
        $condition = array(
            // 'supply_code'=> $this->_customerAuth['code'],
            'customer_id' => $selectCustom,
            'product_title' => $this->getRequest()->getParam('product_title'),
            'pobd_status' => '1',
            'po_code' => $this->getRequest()->getParam('po_code'),
            'created_start' => $createTimeStart,
            'created_end' => $createTimeEnd,
            'supply_code' => $loginUserSession['code']
        );
        $this->view->params = $condition;
        $this->view->pageSize = $pageSize;
        $this->view->page = $page;
        $this->view->count = Service_PoOrderBody::getJoinPoBodyByCondition($condition, 'count(*)');
        $result = Service_PoOrderBody::getJoinPoBodyByCondition($condition, '*', $pageSize, $page, array('po_order.po_id desc'));
        $category = Common_DataCache::getProductCategory();
        if (!empty($result)) {
            foreach ($result as $keyp => $valuep) {
                $result[$keyp]['no_receive'] = $valuep['order_quantity'] - $valuep['received_quantity'];
            }
        }
        $this->view->result = $result;
        $this->view->category = $category;
        $this->view->user = $this->_customerAuth;
        echo $this->view->render($this->tplDirectory . "po-repository.tpl");
    }

    /*
     * po收货管理列表
     */

    public function poReceivListAction() {

        $customer = $this->_customerAuth;

        $purchase_order_status_list = Service_PoOrderProcess::getStatus();

        //if ($this->_request->isPost()) {
        //$customerId = $this->customerId;
        $customerId = $customer['id'];
        $page = $this->_request->getParam('page', 1);
        $pageSize = $this->_request->getParam('pageSize', 20);

        $po_code = trim($this->_request->getParam('po_code', ''));
        $product_sku = trim($this->_request->getParam('product_sku', ''));
        $pobd_status = $this->_request->getParam('pobd_status', '');

        $created_start = trim($this->_request->getParam('created_start', ''));
        $created_end = trim($this->_request->getParam('created_end', ''));

        $params = array();
        $params['created_start'] = $created_start;
        $params['created_end'] = $created_end;
        $params['product_sku'] = $product_sku;
        $params['po_code'] = $po_code;
        $params['pobd_status'] = $pobd_status;

        $created_start = ($created_start) ? $created_start . ' 00:00:00' : '';
        $created_end = ($created_end) ? $created_end . ' 59:59:59' : '';

        $page = $page ? $page : 1;
        $pageSize = $pageSize ? $pageSize : 20;
        $condition = array(
            'po_code' => $po_code,
            'product_sku' => $product_sku,
            'po_status' => $pobd_status,
            'created_start' => $created_start,
            'created_end' => $created_end,
            'customer_id' => $customerId,
        );

        $count = Service_PoOrderTracking::getJoinPoBodyByCondition($condition, 'count(*)');
        $result = '';
        if ($count > 0) {
            $result = Service_PoOrderTracking::getJoinPoBodyByCondition($condition, '*', $pageSize, $page, array('po_order_tracking.id desc'));
            $receiving = array();
            foreach ($result as &$row) {
                if (!empty($row['receiving_id']) && !isset($receiving[$row['receiving_id']])) {
                    $receivingInfo = Service_Receiving::getByField($row['receiving_id']);
                    $receiving[$row['receiving_id']] = $receivingInfo['receiving_code'];
                }
                $row['receiving_code'] = '';
                if (isset($receiving[$row['receiving_id']])) {
                    $row['receiving_code'] = $receiving[$row['receiving_id']];
                }
                $row['pobd_status_text'] = Service_PoOrderProcess::getStatusText($row['pobd_status']);
            }
        }



        $this->view->page = $page;
        $this->view->pageSize = $pageSize;
        $this->view->count = $count;

        //die(Zend_Json::encode($return));
        //}

        $this->view->result = $result;
        $this->view->params = $params;
        $this->view->purchase_order_status_list = $purchase_order_status_list;
        echo Ec::renderTpl($this->tplDirectory . "po_tracking_list.tpl", 'noleftlayout');
    }

    /*
     * po单详情
     */

    public function detailAction() {
        $po_id = $this->_request->getParam('po_id', '');
        $customer = $this->_customerAuth;
        if (empty($po_id)) {
            echo Ec_Lang::getInstance()->getTranslate('PurchaseReceivedIDRequired');
            exit;
        }


        $condition = array();
        $condition['po_id'] = $po_id;
        if (Service_Customer::checkIsService()) {
            $condition['supply_code'] = $customer['code'];
        } else {
            $condition['customer_id'] = $customer['id'];
        }
        $PurchaseOrderBody = new Service_PoOrderBody();
        $purchase_order_body_rows = $PurchaseOrderBody->getJoinPoBodyByCondition($condition, "*");

        $purchase_order_row = $purchase_order_body_rows[0];
        if (empty($purchase_order_body_rows)) {
            echo Ec_Lang::getInstance()->getTranslate('data_not_found');
            exit;
        }


        foreach ($purchase_order_body_rows as $key => &$value) {
            if ($value['product_id']) {
                $product = Service_Product::getByField($value['product_id'], "product_id", "*");
                if ($product) {
                    $value['product_sku'] = $product['product_sku'];
                    $value['product_title'] = $product['product_title'];
                }
            }
        }
        $this->view->purchase_order_body_rows = $purchase_order_body_rows;
        $this->view->purchase_order_row = $purchase_order_row;
        echo Ec::renderTpl($this->tplDirectory . "po-detail.tpl", 'noleftlayout');
    }

    /*
     * 验证po创建入库单参考号
     * @return ask,msg
     */

    public function checkRefcodeAction() {
        $result = array('ask' => '1', 'msg' => 'Success');
        if ($this->_request->isPost()) {
            $refCode = $this->_request->refCode;
            $ASNCode = $this->_request->ASNCode;
            $customerId = $this->_request->customerId;
            $asn_arrays = Service_AsnProccess::checkReferenceNo(array('reference_no' => $refCode, 'customer_id' => $customerId, 'receiving_status_arr' => array('1', '2', '3', '4', '5', '6', '7')));
            //如果存在
            if ($asn_arrays) {
                if ($ASNCode) {
                    foreach ($asn_arrays as $row) {
                        if ($row['receiving_code'] != $ASNCode) {
                            $result = array('ask' => '0', 'msg' => '客户参考号存在!');
                            break;
                        }
                    } //if($ASNCode){	
                } else { //if($ASNCode){
                    $result = array('ask' => '0', 'msg' => '客户参考号存在!');
                }
            } else {//如果不重复，则提示OK			
                $result = array('ask' => '1', 'msg' => 'Success');
            }//if($asn_arrays)
        }
        die(json_encode($result));
    }

    /* 关闭采购单项 */

    public function closeOrderAction() {

        $return = array('ask' => 0, 'message' => '关闭采购单失败', 'error' => '');
        $customer = $this->_customerAuth;
        $customer_id = $customer['id'];
        $pobd_id = $this->_request->getParam("pobd_id", "");
        if (empty($pobd_id)) {
            $return['message'] = '系统错误:PO单ID必须传递';
        }

        $condition = array();
        $condition['pobd_id'] = $pobd_id;
        $condition['customer_id'] = $customer_id;
        $purchase_order_bodys = Service_PoOrderBody::getJoinPoBodyByCondition($condition);
        if (empty($purchase_order_bodys)) {
            $return['message'] = '系统错误:找不到对应PO单项';
        } else {
            $purchase_order_body = $purchase_order_bodys[0];
            if ($purchase_order_body['pobd_status'] == '-1') {
                $return['message'] = '此PO单已经是关闭状态，不能重复关闭';
            } else {
                $row = array();
                $row['pobd_status'] = '-1';
                $status = Service_PoOrderBody::update($row, $pobd_id, "pobd_id");
                if ($status === false) {
                    $return['message'] = '系统错误:更新失败';
                } else {
                    $return['ask'] = '1';
                    $return['message'] = 'PO单关闭成功';
                }
            }
        }

        die(Zend_Json::encode($return));


        //$is_created_asn
    }

    /**
     * 导出po单列表
     */
    public function exportAction() {
        set_time_limit(0);
        $customer = $this->_customerAuth;
        $customerId = $customer['id'];
        $customer_code = $customer['code'];
        $orderArr = $this->_request->getParam('orderArr', '');
        $exportformat = $this->_request->getParam('dateformate', 'xls');
        $exportformat = 'xls';
        $fileName = 'poOrder' . date('YmdHis') . '.' . $exportformat;
        $isSupplier = Service_Customer::checkIsService();
        $customerCompany = array();
        if (!empty($orderArr)) {  //通过选择的订单获取
            if ($exportformat == 'xls') {
                $orderHtml = '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><table border="1"><tr>';
                $htmlTitle = '<td>客户代码</td>';
                $htmlTitle .= '<td>采购单号</td>';
                $htmlTitle .= '<td>客户公司名称</td>';
                $htmlTitle .= '<td>SKU</td>';
                $htmlTitle .= '<td>产品名称</td>';
                $htmlTitle .= '<td>采购数量</td>';
                $htmlTitle .= '<td>待收数量</td>';
                $htmlTitle .= '<td>状态</td>';
                $htmlTitle .= '<td>创建时间</td>';
                $htmlTitle .= '<td>备注</td>';
                $htmlTitle .='</tr>';
                $orderContent = '';
                $max = 1;
                foreach ($orderArr as $key => $pobd_id) {
                    if ($isSupplier) {
                        $condition = array('pobd_id' => $pobd_id, 'supply_code' => $customer_code);
                    } else {
                        $condition = array('pobd_id' => $pobd_id, 'customer_id' => $customerId);
                    }
                    $data_rows = Service_PoOrderBody::getJoinPoBodyByCondition($condition);
                    if (empty($data_rows)) {
                        continue;
                    }

                    $data_row = $data_rows[0];
                    if ($isSupplier) {
                        if (!isset($customerCompany[$data_row['customer_id']])) {
                            $customerCompany[$data_row['customer_id']] = Service_Customer::getByField($data_row['customer_id'], 'customer_id');
                        }
                        $data_row['customer_company_name'] = $customerCompany[$data_row['customer_id']]['customer_code'].' '.$customerCompany[$data_row['customer_id']]['customer_company_name'];
                    }
                    $data_row['pobd_status_text'] = Service_PoOrderProcess::getStatusText($data_row['pobd_status']);
                    $data_row['rest_quantity'] = $data_row['order_quantity'] - $data_row['received_quantity'];

                    $orderContent.="<tr>";
                    //客户代码
                    $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$customer_code}</td>";
                    //采购单号						 
                    $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$data_row['po_code']}</td>";
                    //供应商代码						 
                    $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$data_row['customer_company_name']}</td>";
                    //SKU
                    $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$data_row['product_sku']}</td>";
                    //产品名称
                    $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$data_row['product_title']}</td>";
                    //采购数量
                    $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$data_row['order_quantity']}</td>";
                    //待收数量
                    $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$data_row['rest_quantity']}</td>";
                    //状态
                    $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$data_row['pobd_status_text']}</td>";
                    //创建时间	
                    $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$data_row['create_time']}</td>";
                    //备注
                    $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$data_row['note']}</td>";

                    $orderContent.="</tr>";
                }

                $html = $orderHtml . $htmlTitle . $orderContent . '</table>';


                header('Pragma:public');
                header('Content-Type:application/x-msexecl;name="' . $fileName);
                header("Content-Disposition:inline;filename=" . $fileName);
                //file_put_contents(APPLICATION_PATH . "/../data/{$fileName}",$html);
                echo $html;
                exit;
                //echo $orderHtml;exit;
            }
        } else {
            //获取全部情况
            $condition = array();
            $po_code = trim($this->_request->getParam('po_code', ''));
            $product_sku = trim($this->_request->getParam('product_sku', ''));
            $pobd_status = $this->_request->getParam('pobd_status', '');

            $created_start = trim($this->_request->getParam('created_start', ''));
            $created_end = trim($this->_request->getParam('created_end', ''));

            $created_start = ($created_start) ? $created_start . ' 00:00:00' : '';
            $created_end = ($created_end) ? $created_end . ' 59:59:59' : '';
            $condition = array(
                'po_code' => $po_code,
                'product_sku' => $product_sku,
                'pobd_status' => $pobd_status,
                'created_start' => $created_start,
                'created_end' => $created_end,
                'customer_id' => $customerId,
            );
            if ($isSupplier) {
                $condition['supply_code'] = $customer_code;
                unset($condition['customer_id']);
            }
            $count = Service_PoOrderBody::getJoinPoBodyByCondition($condition, 'count(*)');
            $result = '';
            if ($count > 0) {
                $pageSize = 20;
                $pages = ceil($count / 20);

                $orderHtml = '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><table border="1"><tr>';
                $htmlTitle = '<td>客户代码</td>';
                $htmlTitle .= '<td>采购单号</td>';
                $htmlTitle .= '<td>客户公司名称</td>';
                $htmlTitle .= '<td>SKU</td>';
                $htmlTitle .= '<td>产品名称</td>';
                $htmlTitle .= '<td>采购数量</td>';
                $htmlTitle .= '<td>待收数量</td>';
                $htmlTitle .= '<td>状态</td>';
                $htmlTitle .= '<td>创建时间</td>';
                $htmlTitle .= '<td>备注</td>';
                $htmlTitle .='</tr>';
                $orderContent = '';

                $max = 1;

                for ($page = 1; $page <= $pages; $page++) {
                    $rows = Service_PoOrderBody::getJoinPoBodyByCondition($condition, '*', $pageSize, $page, array('po_order.po_id desc', 'product.product_sku'));
                    if (empty($rows)) {
                        continue;
                    }
                    foreach ($rows as $keyo => $row) {

                        $row['pobd_status_text'] = Service_PoOrderProcess::getStatusText($row['pobd_status']);
                        if ($isSupplier) {
                            if (!isset($customerCompany[$row['customer_id']])) {
                                $customerCompany[$row['customer_id']] = Service_Customer::getByField($row['customer_id'], 'customer_id');
                            }
                            $row['customer_company_name'] = $customerCompany[$row['customer_id']]['customer_code'].' '. $customerCompany[$row['customer_id']]['customer_company_name'];
                        }
                        $row['rest_quantity'] = $row['order_quantity'] - $row['received_quantity'];
                        $orderContent.="<tr>";
                        //客户代码
                        $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$customer_code}</td>";
                        //采购单号						
                        $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$row['po_code']}</td>";
                        //供应商代码
                        $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$row['customer_company_name']}</td>";
                        //SKU
                        $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$row['product_sku']}</td>";
                        //产品名称
                        $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$row['product_title']}</td>";
                        //采购数量
                        $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$row['order_quantity']}</td>";
                        //待收数量
                        $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$row['rest_quantity']}&nbsp;</td>";
                        //状态
                        $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$row['pobd_status_text']}</td>";
                        //创建时间
                        $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$row['create_time']}</td>";
                        //备注
                        $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$row['note']}&nbsp;</td>";
                        $orderContent.="</tr>";
                    }
                }

                header('Pragma:public');
                header('Content-Type:application/x-msexecl;name="' . $fileName);
                header("Content-Disposition:inline;filename=" . $fileName);
                echo $orderHtml . $htmlTitle . $orderContent . '</table>';
            }
        }
        exit;
    }

}
