<?php

class Default_SystemController extends Ec_Controller_DefaultAction
{
    public function preDispatch()
    {
        $this->tplDirectory = "default/views/default/";
        $this->_userAuth = new Zend_Session_Namespace('userAuthorization');
        $action = strtolower($this->getRequest()->getParam('action'));
        $validAction = array('view-product-img', 'get-customer-logo'); // 合法的ACTION，无需验证权限
		
        if (!in_array($action, $validAction, TRUE) && !$this->_userAuth->isLogin) { // 查看产品图片无需登录验证
            $this->_redirect('/default/index/login');
            exit();
        }
    }

    /*
     * 布局头部
     */
    public function headerAction()
    {
        $userId = isset($this->_userAuth->userId) ? $this->_userAuth->userId : '-1';
        $this->view->userId = $userId;
        $warehouseId = $this->_userAuth->warehouseId;
        $warehouseRow = Service_Warehouse::getByField($warehouseId,"warehouse_id","*");
        $this->view->warehouse_code = $warehouseRow['warehouse_code'];
        $this->view->user_code = $this->_userAuth->userCode;
        echo $this->view->render($this->tplDirectory . 'header.tpl');

    }

    /*
     * 后台左导航
     */
    public function leftMenuAction()
    {
        $result = array('state' => 0, 'data' => array());
        $userMenu = isset($this->_userAuth->Acl['menuArr']) ? $this->_userAuth->Acl['menuArr'] : array();
        if ($this->_request->isPost()) {
            if (count($userMenu)) {
                $result = array('state' => 1, 'data' => $userMenu);
            }
            die(Zend_Json::encode($result));
        }
        $this->view->menu = $userMenu;
		$userAuth = new Zend_Session_Namespace('userAuthorization');
		$warehouse = $userAuth->warehouse;        
        $this->view->user = $userAuth->user;
		$this->view->warehouse_code = $warehouse['warehouse_code'];			
        echo $this->view->render($this->tplDirectory . 'left_menu.tpl');
    }

    public function homeAction()
    {   //绑定客户代码账号一律不许查看首页看板数据 add by @Felix
        $userId = isset($this->_userAuth->userId) ? $this->_userAuth->userId : '-1';
        $userInfo = Service_User::getByField($userId);
        if(empty($userInfo['customer_code'])){
            echo Ec::renderTpl($this->tplDirectory . "home.tpl", 'layout');
        }
    }
    
    public function rightGuildAction()
    {
        $user = $this->_userAuth->user;
        $warehouse = $this->_userAuth->warehouse;
        $this->view->user = $user;
        $this->view->warehouse = $warehouse;
        echo $this->view->render($this->tplDirectory . "right_guild.tpl");
    }

    /**
     * @查看产品图片
     * @desc WMS 全站使用
     */
    public function viewProductImgAction()
    {
        $productId = $this->_request->getParam('id', "");
        if ($productId) {
            $productAttach = Service_ProductAttached::getByField($productId, 'product_id');
            if ($productAttach) {
                if ($productAttach['pa_file_type'] == 'link') {
                    header("Location: " . $productAttach ['pa_path']);
                    exit ();
                }
                if ($productAttach['pa_file_type'] == 'img') {
                    $host = $_SERVER['HTTP_HOST'] == 'imwms.globex.cn' ? 'imoms.globex.cn' : ( $_SERVER['HTTP_HOST'] == 'testimportwms.globex.cn' ? 'testimportoms.globex.cn' : 'jinkouoms.cargo.com' );
                    header("Location: http://". $host ."/product-image/view-attach/productId/" . $productId);
                    exit ();
                }
            }
        }
        header("Location: /images/base/noimg.jpg");
        exit ();
    }

    public function getSearchFilterAction()
    {
        $result = array('state' => 0, 'message' => 'Fail', 'data' => array());
        $actionId = $this->_request->getParam('quick', '-1');

        $actionId = empty($actionId) ? '-1' : $actionId;
        if (!empty($actionId)) {
            $condition = array(
                "filter_action_id" => $actionId
            );
            $rows = Service_SearchFilter::getByCondition($condition, '*', 50, 1, array('parent_id asc', 'search_sort asc'));
           
		    if (!empty($rows)) {
                $sType = $sFilter = array();
                foreach ($rows as $key => $value) {
                    if ($value['parent_id'] == '0') {
                        $sType[$value['search_sort'] . '_' . $value['sf_id']] = $value;
                        $sFilter[$value['sf_id']] = $value;
                    } elseif (isset($sFilter[$value['parent_id']])) {
                        $sType[$sFilter[$value['parent_id']]['search_sort'] . '_' . $value['parent_id']]['item'][] = $value;
                    }
                }
                ksort($sType);
                $result = array('state' => 1, 'message' => '', 'data' => $sType);
            }
        }
        die(Zend_Json::encode($result));
    }

    /**
     * @desc 获取自定义导航
     */
    public function getSkyeQuiKeyAction()
    {
        $result = array('state' => 1, 'message' => 'Fail', 'data' => array(), 'userId' => 0);
        $data = Service_UserRightHeaderMap::getSkyeQuiKey();
        if (!empty($data)) {
            $userId = isset($this->_userAuth->userId) ? $this->_userAuth->userId : '0';
            $result = array('state' => 1, 'userId' => $userId, 'data' => $data);
        }
		
        $warehouseId = $this->_userAuth->warehouseId;
        $warehouseRow = Service_Warehouse::getByField($warehouseId,"warehouse_id","*");
        $result['warehouse_code'] = $warehouseRow['warehouse_code'];
        $result['user_code'] = $this->_userAuth->userCode;
        die(Zend_Json::encode($result));
    }
    
    public function getExceptionDataAction() {
        $result = array('state' => 1, 'unreadMsg' => 0);
        $userId = isset($this->_userAuth->userId) ? $this->_userAuth->userId : '0';
        $result['unreadMsg']  =   Service_ExceptionUser::getByCondition(array(
            'user_id'   => $userId,
            'eu_status' =>   0
        ),'count(*)');        
        die(Zend_Json::encode($result));
    }
    /**
     * @desc 获取用户权限
     * @desc 设置快捷导航
     */
    public function getSkyeQuiKeyListAction()
    {
        $result = array('state' => 0, 'message' => '', 'data' => array());
        $userId = isset($this->_userAuth->userId) ? $this->_userAuth->userId : '0';
        $data = Service_User::getUserRightCustomByUserId($userId);
        if (!empty($data)) {
            $result = array('state' => 1, 'data' => $data);
        }
        die(Zend_Json::encode($result));
    }

    public function updateSkyeQuiKeyAction()
    {
        $result = array('state' => 0, 'message' => '操作失败.', 'data' => array());
        if ($this->_request->isPost()) {
            $actionIdArr = $this->_request->getParam('actionId', array());
            $result = Service_UserRightHeaderMap::updateSkyeQuiKey($actionIdArr);
            if ($result) {
                $result = array('state' => 1);
            }
        }
        die(Zend_Json::encode($result));
    }

    /**
     * @desc 返回运输方式代码
     * @use 打印机设置
     */
    public function setupPrinterAction()
    {
        $result = array('state' =>1, 'data' => array('A4'));
        if ($this->_request->isPost()) {
            $smArr = Service_ShippingMethod::getShippingMethodSimple();
            if (!empty($smArr)) {
                $result = array('state' => 1, 'data' => $smArr);
            }
        }
        die(Zend_Json::encode($result));
    }

    /**
     * @系统数据看板
     */
    public function getBoardAction()
    {
        $result = array('state' => 0, 'data' => array());
        $type = trim($this->_request->getParam('type', ''));
        $model = trim($this->_request->getParam('model', ''));
        $warehouseId = $this->_userAuth->warehouseId;
        $db = Common_Common::getAdapter();
        $sql = "select Statistik_data from statistik_data_save where Statistik_warehouse_id=$warehouseId order by id desc limit 3";
        $statistikSData = $db->fetchAll($sql); 
        $dataArr = array();
        foreach (array_reverse($statistikSData) as $key=>$value){
            $dataArr[] = unserialize(base64_decode($value['Statistik_data']));
        } 
        switch ($model . '_' . $type) {
            case 'shipment_0':
                $result['state'] = 1;
                $result['data']['name'] = array('日期', '接收订单数', '生产数', '未生产数', '出区包裹数', '审核通过', '待审核/审核不通过', '审核通过率', '订单出库率');
                foreach ($dataArr as $keyOne=>$valueOne){
                    $result['data']['value'][] = array($valueOne['date'], $valueOne['oderTotal'], $valueOne['productionNumber'], $valueOne['notProductionNumber'], $valueOne['packageNumber'], $valueOne['auditPassNumber'], $valueOne['auditPendingNumber'].'/'.$valueOne['auditNumber'], $valueOne['auditPassRate'], $valueOne['deliveryRate']);
                }
                break;
            case 'shipment_1':
                $result['state'] = 1;
                $result['data']['name'] = array('日期', '提交ASN个数', '未审核通过ASN数', '审核通过ASN数', '待上架数', '已上架数', '上架完成率');
                foreach ($dataArr as $keyTwo=>$valueTwo){
                    $result['data']['value'][] = array($valueTwo['date'],$valueTwo['asnTotal'], $valueTwo['notAuditedAsnNumber'], $valueTwo['auditPassAsnNumber'], $valueTwo['stayShelvesNumber'], $valueTwo['asnAlreadyShelvesNumber'], $valueTwo['asnAlreadyShelvesRate']);
                }
                break;
            case 'picking_0':
                $result['state'] = 1;
                $result['data']['name'] = array('日期', '新增产品个数', '提交产品个数', '海关审核通过个数', '国检审核通过个数', '国检审核不通过个数', '今日海关审核率', '今日国检审核率');
                foreach ($dataArr as $keyThree=>$valueThree){
                    $result['data']['value'][] = array($valueThree['date'], $valueThree['producttotal'], $valueThree['submitProductNumber'], $valueThree['customsAuditPassNumber'], $valueThree['ciqAuditPassNumber'], $valueThree['ciqNOtAuditNumber'], $valueThree['customsAuditPassRate'], $valueThree['ciqAuditPassRate']);
                }
                break;
            default:
                $result = array();
                break;
        }
        if(!empty($dataArr)){
            die(Zend_Json::encode($result));
        }
    }
	/**
	 * @author william-fan
	 * @todo 获取客户logo图片
	 */
    public function getCustomerLogoAction(){
    	$customerCode = $this->_request->getParam('customerCode', "");
    	if ($customerCode) {
    		$customer = Service_Customer::getByField($customerCode, 'customer_code');
			if($customer && $customer['customer_logo']!='' && $customer['customer_logo_save_site']!=''){
				header("Location: ".$customer['customer_logo_save_site'].'/'.'index/view-logo-image/customerCode/'.$customer['customer_code']);
				exit ();
			}
    	}
    	exit();
    	//header("Location: /images/base/noimg.jpg");
    }

    /**
     * @todo 获取左菜单的json
     */
    public function leftMenuJsonAction(){
        $result = array('state' => 0, 'data' => array());
        $userMenu = isset($this->_userAuth->Acl['menuArr']) ? $this->_userAuth->Acl['menuArr'] : array();
        //echo "<pre>";
        //print_r($userMenu);
        $jsonData = Service_UserRight::getRightJson($userMenu);
        //print_r($jsonData);
        $josnString = "var indexdata =".Zend_Json::encode($jsonData);
        die($josnString);
    }

}