<?php

/**
 * luffy丶大叔 
 * <><><><><><><><><><><><><>有妹子加微信不哦！~<><><><><><><><><><><><><><><><>
 * $Author: luffy丶大叔 
 * $Z 2015-4-9 17:30:40
 * $email luffy00789@126.com
 * $encoding UTF-8
 * $ Copyright (c) 2014-2015, http://www.globex.cn. All Rights Reserved.
 */
class Exception_ExceptionController extends Ec_Controller_Action{
    ######name is not a number, it is freemarker.template.SimpleScalar#######
    public function preDispatch()
    {
        $this->tplDirectory = "exception/views/default/";
        $this->_userAuth = new Zend_Session_Namespace('userAuthorization');
        $this->serviceClass = new Service_Exception();
    }
    
    public function listAction() {
        
        $typeModel  =   Service_ExceptionType::_typeModel();
        
        if ($this->_request->isPost()){
            $page = $this->_request->getParam('page', 1);
            $pageSize = $this->_request->getParam('pageSize', 20);
            $return = array(
                "state" => 0,
                "message" => "No Data"
            );
            $condition   =   array(
                    'et_code'   =>  $this->_request->getParam('et_code',''),
                    'et_model'  =>  $this->_request->getParam('et_model',''),
                    'like_e_refer_no'    =>  $this->_request->getParam('like_e_refer_no',''),
                    'like_e_title'   =>  $this->_request->getParam('like_e_title',''),
                    'eu_status'     =>  $this->_request->getParam('eu_status' , ''),
                    'eu_user_id'    =>  $this->_userAuth->userId
            );  
            $count  = Service_Exception::getAllByCondition($condition,'count(*)');
            $return['total'] = $count;
            if ($count){
                $rows   =   Service_Exception::getAllByCondition($condition,"*",$pageSize,$page,'e_id desc');
                foreach($rows AS $key=>$row){
                    if($row['user_id'] == 0){
                        $rows[$key]['operater'] =   '无';
                    }else{
                        $user   =   Service_User::getByField($row['user_id']);
                        $user_position  =   Service_UserPosition::getByField($user['up_id']);
                        $rows[$key]['operater'] =   "{$user_position['up_name']}/{$user['user_name']}";
                    }
                    $rows[$key]['et_model'] =   isset($typeModel[$row['et_model']]) ? $typeModel[$row['et_model']]['name'] : '未知';
                    $rows[$key]['readstatus']   =    ($row['eu_status'] == 0) ? '未读' : '已读';
                }
                $return['data'] = $rows;
                $return['state'] = 1;
            }
            die(Zend_Json::encode($return));
            
        }
        $this->view->model  = $typeModel;     
        
        echo Ec::renderTpl($this->tplDirectory . "index.tpl", 'layout');
    }
    
    public function viewAction() {
        $e_id = (int)$this->_request->getParam('e_id', 0);
      
        $exception  =   Service_Exception::getAllByEid($e_id);
        
        if(!$exception){
            throw new Zend_EventManager_Exception_InvalidArgumentException;
        }

        if($exception['eu_status'] == 0){
            $exceptionUser['eu_status']    =   1;   
            $exceptionUser['user_id']       =   $this->_userAuth->userId;
            Service_ExceptionUser::update($exceptionUser, $exception['eu_id']);
            Service_ExceptionLog::add(array(
                'e_id'      =>    $exception['e_id'],
                'user_id'   =>  $this->_userAuth->userId,
                'el_msg'    =>      $this->_userAuth->user['user_name'] .'读取:'.$exception['e_title']
            ));
        }
//        if($exception['e_explain'] == ''){
//            $detail =   Service_ExceptionDetail::getDetailByEid($exception['e_id']); 
//            foreach($detail AS $key=>$val){
//                $exception['e_explain'][$key]    = unserialize($val['refer_no']);
//            }
//        }
    
        $exceptionLog   =   Service_ExceptionLog::getLogByEid($exception['e_id']);

        $exceptionOperation   =   Service_ExceptionOperation::getAllByEid($exception['e_id']);
        $this->view->exception  =   $exception;
        $this->view->exceptionLog  =   $exceptionLog;
        $this->view->exceptionOperation  =   $exceptionOperation;
        $this->view->userPosition   =   Service_UserPosition::getAll();
        echo Ec::renderTpl($this->tplDirectory . "view1.tpl", 'layout');
    }
    
    public function getExplainAction() {
        $e_id = (int)$this->_request->getParam('e_id', 0);
        $page = $this->_request->getParam('page', 1);
        $pageSize = $this->_request->getParam('pageSize', 20);
        $return = array(
            "state" => 0,
            "message" => "No Data"
        );
        $count  =    Service_ExceptionDetail::getDetailByEid($e_id , 'count(*)'); 
        $return['total'] = $count;
        if($pageSize * ($page - 1) > $count){
            $page = 1;
        }
        if($count > 0){        
            $detail =   Service_ExceptionDetail::getDetailByEid($e_id , ['refer_no'] , $page , $pageSize); 
            foreach($detail AS $key=>$value){
                $detail[$key]   = unserialize($value['refer_no']);
            }
            $return['data'] = $detail;
            $return['state'] = 1;
        }
        die(Zend_Json::encode($return));
    }
    
    public function onlybodyAction() {
        $action = $this->_request->getParam('act', 'begin');
        $e_id   =   $this->_request->getParam('e_id' , 0);
        
        $exception  =   Service_Exception::getByField($e_id);
        if(!$exception){
            throw new Exception;
        }
        if($action == 'begin'){
            if($exception['e_status'] > 0){
                throw new Exception;
            }
            $this->_updateOperation($e_id , 1 , 0 ,$this->_userAuth->userId , '开始处理');          
        }elseif($action == 'assign'){
            $user_id   =   (int)$this->_request->getParam('user_id' , 0);
            $remark     =   $this->_request->getParam('remark' , '');
            if($user_id <= 0){
                throw new Exception;
            }
            $to_user    =   Service_User::getByField($user_id);
            //通知用户
            $exceptionUser  =   Service_ExceptionUser::getByCondition(array(
                'e_id'  =>  $e_id,
                'user_id'   =>  $user_id
            ));
            
            if($exceptionUser && isset($exceptionUser[0]) ){//修改通知状态 
                $exceptionUser  =   $exceptionUser[0];
                Service_ExceptionUser::update(array(
                    'e_id'  =>  $e_id,
                    'user_id'   =>  $user_id,
                    'eu_status' =>  0
                ),$exceptionUser['eu_id']);
            }else{//添加通知
                Service_ExceptionUser::add(array(
                    'e_id'  =>  $e_id,
                    'user_id'   =>  $user_id
                ));
            }
            
            $this->_updateOperation($e_id , 1 , 1 ,$user_id , "指派{$to_user['user_name']}" , $remark);    
            
        }elseif($action == 'close'){
            $this->_updateOperation($e_id , 2 , 1 ,$this->_userAuth->userId , '关闭异常');      
        }
        $this->_redirect("/exception/exception/view?e_id={$e_id}");
        exit();
    }
    
    public function _updateOperation($e_id,$status,$status_from,$to_user_id,$el_msg = '',$remark = '') {
        //更改状态和当前操作人
        Service_Exception::update(array(
            'user_id'   =>  $to_user_id,
            'e_status'  =>  $status,
            'e_update_time' =>  date('Y-m-d H:i:s')
        ), $e_id);
          //添加操作
        Service_ExceptionOperation::add(array(
            'to_user_id'    =>  $to_user_id,
            'e_id'          =>  $e_id,
            'status_to'     =>  $status,
            'status_from'   =>  $status_from,
            'user_id'       =>  $this->_userAuth->userId,
            'eo_remark'    =>  $remark
        ));
        //添加日志
        Service_ExceptionLog::add(array(
            'user_id'   =>  $this->_userAuth->userId,
            'e_id'      =>  $e_id,
            'el_msg'    =>  $el_msg
        ));
    }
    
    public function deleteAction() {
        $result = array(
            "state" => 0,
            "message" => "Fail."
        );
        if($this->_request->isPost()){
            $e_id   =   $this->_request->getParam('paramId' , 0);
            Service_Exception::delete($e_id);
            Service_ExceptionLog::delete($e_id, 'e_id');
            Service_ExceptionDetail::delete($e_id,'e_id');
            Service_ExceptionOperation::delete($e_id, 'e_id');
            Service_ExceptionUser::delete($e_id, 'e_id');
            $result['state'] = 1;
            $result['message'] = 'Success.';
        }
        die(Zend_Json::encode($result));
    }
    //测试时用的手动
    public function manualAction() {
//        $flag = APPLICATION_PATH . '/../data/log/ExceptionCron.lock';
//        if (@file_exists($flag)) {
//          echo "Another process is running\r\n";
//          echo "{$flag}\r\n";
//          exit();
//        }
//        $handler = fopen($flag, 'wb');
//        fclose($handler);
//        echo '[', date('Y-m-d H:i:s'), '] Start', "\r\n";
//
//        $exceptionType  =   Service_ExceptionType::getByCondition(array(
//            'et_status'=>1
//        ));
//
//        if($exceptionType){
//            foreach ($exceptionType as  $value) {
//                //检查是否存在，避免重复
//                $count  =   Service_Exception::getByCondition(array(
//                    'et_code'   =>  $value['et_code'],
//                    'array_e_status'  =>  array(0,1)
//                ),'count(*)');
//                if($count > 0)
//                    continue;
//                //处理
//                require_once APPLICATION_PATH.'/../libs/Exception.php';
//                $cronFunc   =   strtolower($value['et_code']);        
//                if(!method_exists('Lib_Exception',$cronFunc)){
//                    continue;
//                }        
//                Lib_Exception::$cronFunc();
//            }
//        }
//
//        echo '[', date('Y-m-d H:i:s'), '] End', "\r\n";
//        @unlink($flag);
    }
}
