<?php

/**
 * 入区派车单
 */
class Receiving_IntoAreaController extends Ec_Controller_Action
{
    public function preDispatch()
    {
        $this->tplDir = 'receiving/views/into-area/';
    }

    /**
     * 新增动作
     */
    public function createAction()
    {
        $this->view->container = Service_IntoArea::getContainer();

        echo Ec::renderTpl($this->tplDir . 'create.tpl', 'layout');
    }

    /**
     * 编辑动作
     */
    public function editAction()
    {
        $iaCode = trim($this->getRequest()->getParam('code', ''));

        if ('' === $iaCode) {
            exit('Warning: Invalid Request');
        }

        $intoArea = Service_IntoArea::getByCode($iaCode);

        if (empty($intoArea)) {
            exit('Warning: Invalid Request');
        }

        if (Service_IntoArea::STATUS_DRAFT !== (int)$intoArea['status']) {
            exit('Error: Invalid Status');
        }

        $this->view->container = Service_IntoArea::getContainer();
        $this->view->intoArea = $intoArea;
        $this->view->intoAreaDetail = Service_IntoArea::getDetailByCode($iaCode);

        echo Ec::renderTpl($this->tplDir . 'edit.tpl', 'layout');
    }

    /**
     * 保存动作
     */
    public function saveAction()
    {
        $response = array('status' => 0, 'message' => '非法HTTP请求', 'code' => '');

        if ($this->getRequest()->isPost()) {
            $iaCode = trim($this->getRequest()->getPost('ia_code', ''));
            $carNumber = trim($this->getRequest()->getPost('car_number', ''));
            $containerType = intval($this->getRequest()->getPost('container_type', 0));
            $telephone = trim($this->getRequest()->getPost('telephone', ''));
            $asnCode = $this->getRequest()->getPost('selectedAsnCode', array());
            $intoAreaRow = array(
                'ia_code' => $iaCode,
                'car_number' => $carNumber,
                'container_type' => $containerType,
                'telephone' => $telephone,
                'asn_code' => $asnCode
            );

            if ('' === $iaCode) { // 新增
                $result = Service_IntoArea::create($intoAreaRow);

                if (is_array($result)) {
                    $response['message'] = '入区派车单创建失败：' . join('；', $result);
                } else {
                    $response['status'] = 1;
                    $response['message'] = '入区派车单已创建，单号【' . $result . '】';
                    $response['code'] = $result;
                }
            } else { // 修改
                $result = Service_IntoArea::update($intoAreaRow);

                if (TRUE === $result) {
                    $response['status'] = 1;
                    $response['message'] = '入区派车单【' . $iaCode . '】于' . date('Y-m-d H:i:s') . '已更新';
                } else {
                    $response['message'] = '入区派车单【' . $iaCode . '】于' . date('Y-m-d H:i:s') . '更新失败：' . $result;
                }
            }
        }

        exit(Zend_Json::encode($response));
    }

    /**
     * 列表动作
     */
    public function listAction()
    {
        if ($this->getRequest()->isPost()) {
            $page = (int)trim($this->_request->getParam('page', 1));
            $size = (int)trim($this->_request->getParam('pageSize', 20));
            $iaCode = trim($this->_request->getParam('ia_code', ''));
            $status = trim($this->_request->getParam('status', ''));
            $carNumber = trim($this->_request->getParam('car_number', ''));
            $containerType = trim($this->_request->getParam('container_type', ''));
            $condition = array();
            $condition['created_time_from'] = trim($this->_request->getParam('dateFor', ''));
            $condition['created_time_to'] = trim($this->_request->getParam('dateTo', ''));

            if ('' !== $iaCode) {
                $condition['ia_code'] = $iaCode;
            }

            if ('' !== $status) {
                $condition['status'] = (int)$status;
            }

            if ('' !== $carNumber) {
                $condition['car_number'] = $carNumber;
            }

            if ('' !== $containerType) {
                $condition['container_type'] = (int)$containerType;
            }
            $total = Service_IntoArea::getByCondition($condition, array('count' => TRUE));
            $record = Service_IntoArea::getByCondition($condition, array('page' => $page, 'size' => $size, 'order' => 'ia_id DESC'));

            exit(Zend_Json::encode(array(
                'state' => $total ? 1 : 0,
                'total' => $total,
                'data' => $record,
            )));
        }

        $this->view->container = Service_IntoArea::getContainer();
        $this->view->type = Service_IntoArea::getType();
        $this->view->bgCompany = Common_SelectMap::getBgCompany();

        echo Ec::renderTpl($this->tplDir . 'list.tpl', 'layout');
    }

    /**
     * 确认动作
     */
    public function confirmAction()
    {
        //echo "<pre>";
        $iaCode = trim($this->getRequest()->getParam('code', ''));
        $response = array('status' => 0, 'message' => '非法HTTP请求');
        $bg_company = trim($this->getRequest()->getParam('bg_company', ''));

        if (!$this->getRequest()->isPost()) {
            exit(Zend_Json::encode($response));
        }

        if ('' === $iaCode) {
            $response['message'] = '入区派车单号不能为空';
            exit(Zend_Json::encode($response));
        }
        if ('' === $bg_company) {
            $response['message'] = '传输企业不能为空';
            exit(Zend_Json::encode($response));
        }


        $intoArea = Service_IntoArea::getByCode($iaCode);

        if (empty($intoArea)) {
            $response['message'] = '不存在入区派车单【' . $iaCode . '】';
            exit(Zend_Json::encode($response));
        }

        if (Service_IntoArea::STATUS_DRAFT !== (int)$intoArea['status']) {
            $response['message'] = '入区派车单【' . $iaCode . '】不是草稿状态';
            exit(Zend_Json::encode($response));
        }

        $result = Service_IntoArea::confirm($iaCode,$bg_company);

        if (TRUE === $result) {
            $response['status'] = 1;
            $response['message'] = '入区派车单【' . $iaCode . '】已移至【确认】状态';
        } else {
            $response['message'] = $result;
        }

        exit(Zend_Json::encode($response));
    }

    /**
     * 打印动作
     */
    public function printAction()
    {
        $iaCode = trim($this->getRequest()->getParam('code', ''));
        $this->view->isError = TRUE;
        $this->view->errorContent = '入区派车单号不能为空';

        if ('' !== $iaCode) {
            $intoArea = Service_IntoArea::getByCode($iaCode);

            if (empty($intoArea)) {
                $this->view->errorContent = '入区派车单号【' . $iaCode . '】不存在';
            } elseif (Service_IntoArea::STATUS_CONFIRMED !== (int)$intoArea['status']) {
                $this->view->errorContent = '入区派车单号【' . $iaCode . '】不是确认状态';
            } else {
                $intoAreaDetail = Service_IntoArea::getDetailByCode($iaCode);
                $asnDetail = array();
                $errorMessage = array();

                if (empty($intoAreaDetail)) {
                    $this->view->errorContent = '入区派车单号【' . $iaCode . '】不存在ASN单';
                } else {
                    foreach ($intoAreaDetail as $item) {
                        $receivingXml = Service_ReceivingXml::getByCondition(array('receiving_code' => $item['receiving_code']));
                        $receiving = Service_Receiving::getByCondition(array('receiving_code' => $item['receiving_code']));
                        $receiving = $receiving[0];
                        if (empty($receivingXml)) { // 在receiving_xml没有找到相对应ASN信息
                            $errorMessage[] = 'ASN单【' . $item['receiving_code'] . '】缺乏必要数据';
                        } else {
                            foreach ($receivingXml as $subReceiving) {
                                if ('' === trim($subReceiving['refercence_form_id'])) { // 海关单号为空
                                    $errorMessage[] = 'ASN单【' . $item['receiving_code'] . '】子单号【' . $subReceiving['sub_receiving_code'] . '】海关单号为空';
                                } else {
                                    $asnDetail[] = array(
                                        'receiving_code' => $item['receiving_code'],
                                        'sub_receiving_code' => $subReceiving['sub_receiving_code'],
                                        'customs_form_id' => $subReceiving['refercence_form_id'],
                                        'pack_no' => $subReceiving['pack_no'],
                                        'customer_code' => $receiving['customer_code'],
                                    );
                                }
                            }
                        }
                    }

                    if (empty($errorMessage)) {
                        $container = Service_IntoArea::getContainer();
                        $intoArea['car_number'] = preg_replace('/([a-zA-Z0-9]+)/', '<span class="english">\1</span>', $intoArea['car_number']);
                        $intoArea['container_type'] = $container[$intoArea['container_type']];

                        $size = 12;
                        $total = count($asnDetail);
                        $this->view->isError = FALSE;
                        $this->view->intoArea = $intoArea;
                        $this->view->intoAreaDetail = array_chunk($asnDetail, $size);
                        $this->view->totalAsn = $total;
                        $this->view->totalPage = ceil($total / $size);
                        $this->view->size = $size;
                    } else {
                        $this->view->errorContent = join('；', $errorMessage);
                    }
                }
            }
        }

        echo $this->view->render($this->tplDir . 'print.tpl');
    }

    /**
     * 详情动作
     */
    public function detailAction()
    {
        $iaCode = trim($this->getRequest()->getParam('code', ''));
        $response = array('status' => 0, 'message' => '非法HTTP请求', 'data' => array());

        if ('' === $iaCode) {
            $response['message'] = '入区派车单号不能为空';
        } else {
            $intoArea = Service_IntoArea::getByCode($iaCode);

            if (empty($intoArea)) {
                $response['message'] = '入区派车单【' . $iaCode . '】不存在';
            } else {
                $intoAreaDetail = Service_IntoArea::getDetailByCode($iaCode);
                $asnDetail = array();

                foreach ($intoAreaDetail as $item) {
                    $receivingXml = Service_ReceivingXml::getByCondition(array('receiving_code' => $item['receiving_code']));

                    if (empty($receivingXml)) {
                        $asnDetail[] = array(
                            'receiving_code' => $item['receiving_code'],
                            'sub_receiving_code' => '',
                            'customs_form_id' => '',
                        );
                    } else {
                        foreach ($receivingXml as $subReceiving) {
                            $asnDetail[] = array(
                                'receiving_code' => $item['receiving_code'],
                                'sub_receiving_code' => $subReceiving['sub_receiving_code'],
                                'customs_form_id' => $subReceiving['refercence_form_id'],
                            );
                        }
                    }
                }

                $response['status'] = 1;
                $response['message'] = '入区派车单【' . $iaCode . '】数据已返回';
                $response['data'] = array(
                    'intoArea' => $intoArea,
                    'intoAreaDetail' => $asnDetail,
                );
            }
        }

        exit(Zend_Json::encode($response));
    }

    /*导出入区单*/
    public function exportAction()
    {

        $exportType = trim($this->_request->getParam('exportType', ""));

        if ($exportType == '1') {
            $iaCode = $this->_request->getParam('iaCode', array());
            if (!empty($iaCode) && is_array($iaCode)) {
                $iaCodes = array();
                foreach ($iaCode as $key => $ia) {
                    $into = Service_IntoArea::getByCondition(array('ia_code' => $ia));
                    if (!empty($into)) {
                        $iaCodes[] = $into[0];
                    }
                }
            }
        } else {
            $params = $this->_request->getParams();
            $iaCode = trim($this->_request->getParam('ia_code', ''));
            $status = trim($this->_request->getParam('status', ''));
            $carNumber = trim($this->_request->getParam('car_number', ''));
            $containerType = trim($this->_request->getParam('container_type', ''));
            $condition = array();
            $condition['created_time_from'] = trim($this->_request->getParam('dateFor', ''));
            $condition['created_time_to'] = trim($this->_request->getParam('dateTo', ''));

            if ('' !== $iaCode) {
                $condition['ia_code'] = $iaCode;
            }

            if ('' !== $status) {
                $condition['status'] = (int)$status;
            }

            if ('' !== $carNumber) {
                $condition['car_number'] = $carNumber;
            }

            if ('' !== $containerType) {
                $condition['container_type'] = (int)$containerType;
            }
            $iaCodes = Service_IntoArea::getByCondition($condition, array('page' => $page, 'size' => $size, 'order' => 'ia_id DESC'));

        }
        $filename = "intoArea-" . date("YmdHis");
        require_once("PHPExcel.php");
        require_once("PHPExcel/Reader/Excel2007.php");
        require_once("PHPExcel/Reader/Excel5.php");
        require_once('PHPExcel/IOFactory.php');

        $objExcel = new PHPExcel();
        $objProps = $objExcel->getProperties();
        $objProps->setCreator('EC');
        $objProps->setTitle('Template');
        $objExcel->setActiveSheetIndex(0);

        $objActSheet = $objExcel->getActiveSheet();

        $objActSheet->getColumnDimension('A')->setWidth(25);
        $objActSheet->getColumnDimension('B')->setWidth(20);
        $objActSheet->getColumnDimension('C')->setWidth(20);
        $objActSheet->getColumnDimension('D')->setWidth(15);
        $objActSheet->getColumnDimension('E')->setWidth(10);
        $objActSheet->getColumnDimension('F')->setWidth(25);


        $objActSheet->setCellValue('A1', '入区派车单号');
        $objActSheet->setCellValue('B1', '项目名称');
        $objActSheet->setCellValue('C1', '车牌号');
        $objActSheet->setCellValue('D1', '柜型');
        $objActSheet->setCellValue("E1", '状态');
        $objActSheet->setCellValue('F1', '创建时间');
        $index = 2;
        foreach ($iaCodes as $key => $value) {
            $objActSheet->setCellValue("A" . $index, $value['ia_code']);
            $objActSheet->setCellValue("B" . $index, $value['project_name']);
            $objActSheet->setCellValueExplicit("C" . $index, $value['car_number'], PHPExcel_Cell_DataType::TYPE_STRING);
            if ($value['container_type'] == '1') {
                $objActSheet->setCellValue("D" . $index, "集装箱");
            } else {
                $objActSheet->setCellValue("D" . $index, "吨车");
            }
            if ($value['status'] == '1') {
                $objActSheet->setCellValue("E" . $index, "确认");
            } else {
                $objActSheet->setCellValue("E" . $index, "草稿");
            }

            $objActSheet->setCellValue("F" . $index, $value['created_time']);
            $index++;
        }

        header('Pragma:public');
        header('Content-Type:application/x-msexecl;name="' . $filename . '.xls');
        header("Content-Disposition:inline;filename=" . $filename . '.xls');
        $objWriter = PHPExcel_IOFactory::createWriter($objExcel, 'Excel5');
        $objWriter->save('php://output');
    }

    // 修改车牌
    public function modnumAction()
    {
        $iaCode = trim($this->getRequest()->getParam('code', ''));
        $carNum = trim($this->getRequest()->getParam('num', ''));
        $response = array('status' => 0, 'message' => '非法HTTP请求');
        if (!$this->getRequest()->isPost()) {
            exit(Zend_Json::encode($response));
        }

        if ('' === $carNum) {
            $response['message'] = '车牌号不能为空';
            exit(Zend_Json::encode($response));
        }
        $row = array(
            'ia_code' => $iaCode,
            'car_number' => $carNum,
        );
        $outArea = Service_IntoArea::updateByCode($row, $iaCode);
        if ($outArea == TRUE) {
            $response['status'] = 1;
        }
        exit(Zend_Json::encode($response));
    }
}
