<?php
class Common_CurrencyController extends Ec_Controller_Action
{
    public function preDispatch()
    {
        $this->tplDirectory = "common/views/currency/";
        $this->serviceClass = new Service_Currency();
    }

    public function listAction()
    {
        if ($this->_request->isPost()) {
            $page = $this->_request->getParam('page', 1);
            $pageSize = $this->_request->getParam('pageSize', 20);

            $page = $page ? $page : 1;
            $pageSize = $pageSize ? $pageSize : 20;

            $return = array(
                "state" => 0,
                "message" => "No Data"
            );

            $params = $this->_request->getParams();

            $condition = $this->serviceClass->getMatchFields($params);

            $count = $this->serviceClass->getByCondition($condition, 'count(*)');
            $return['total'] = $count;

            if ($count) {
                $showFields=array(
                    
                'currency_name_en',
                'currency_name',
                'currency_code',
                'currency_symbol_left',
                'currency_decimal_places',
                'currency_rate',
                'currency_update_time',
                'currency_add_time',
                'currency_stop_time',
                'currency_id',
                );
                $showFields = $this->serviceClass->getFieldsAlias($showFields);
                $rows = $this->serviceClass->getByCondition($condition,$showFields, $pageSize, $page, array('currency_id desc'));
                $return['data'] = $rows;
                $return['state'] = 1;
                $return['message'] = "";
            }
            die(Zend_Json::encode($return));
        }
        echo Ec::renderTpl($this->tplDirectory . "currency_index.tpl", 'layout');
    }

    public function historyListAction()
    {
        $historyClass   = new Service_CurrencyLog();
        $params         = $this->_request->getParams();
        $currency_code  = isset($params['E3'])? $params['E3'] : '';
        if ($this->_request->isPost() || !empty($currency_code)) {
            $page       = $this->_request->getParam('page', 1);
            $pageSize   = $this->_request->getParam('pageSize', 20);

            $page       = $page ? $page : 1;
            $pageSize   = $pageSize ? $pageSize : 20;
            
            $return = array(
                "state" => 0,
                "message" => "No Data"
            );

            $condition          = $historyClass->getMatchFields($params);
            $count              = $historyClass->getByCondition($condition, 'count(*)');

            if ($count) {
                $showFields=array(
                    'currency_name_en',
                    'currency_name',
                    'currency_code',
                    'currency_symbol_left',
                    'currency_decimal_places',
                    'currency_rate',
                    'currency_update_time',
                    'currency_add_time',
                    'currency_stop_time',
                    'currency_id',
                );
                $showFields         = $historyClass->getFieldsAlias($showFields);
                $return['data']     = $historyClass->getByCondition($condition,$showFields, $pageSize, $page, array('currency_id desc'));
                $return['state']    = 1;
                $return['message']  = "";
            }
            if($this->_request->isPost()){
                die(Zend_Json::encode($return));
            } else {
                $this->view->historyRows = $return['data'];
            }
        }
        echo Ec::renderTpl($this->tplDirectory . "currency_index_log.tpl", 'layout');
    }

    public function editAction()
    {
        $serviceCurrencyLogClass    = new Service_CurrencyLog();
        $nowTime = date('Y-m-d H:i:s');
        $nowBth  = date('Ymd');
        $return = array(
            'state' => 0,
            'message' => '',
            'errorMessage'=>array('Fail.')
        );
        try{
            if ($this->_request->isPost()) {
                $params = $this->_request->getParams();
                $row = array(                
                  'currency_id'             => '',
                  'currency_name_en'        => '',
                  'currency_name'           => '',
                  'currency_code'           => '',
                  'currency_symbol_left'    => '',
                  'currency_decimal_places' => '',
                  'currency_rate'           => '',
                );
                $row=$this->serviceClass->getMatchEditFields($params,$row);
                $paramId = $row['currency_id'];
                if (!empty($row['currency_id'])) {
                    unset($row['currency_id']);
                }
                $errorArr = $this->serviceClass->validator($row);

                if (!empty($errorArr)) {
                    $return = array(
                        'state' => 0,
                        'message'=>'',
                        'errorMessage' => $errorArr
                    );
                    die(Zend_Json::encode($return));
                }

                if (!empty($paramId)) {
                    $row['currency_update_time']  = $nowTime;
                    $oldCurrencyRow             = Service_Currency::getByField($paramId);
                    $condition = array(
                        'currency_batch_number' => $oldCurrencyRow['currency_batch_number'],
                        'currency_code'     => $row['currency_code'],
                    );
                    $logCurrencyRow = Service_CurrencyLog::getByCondition($condition);
                    if(!empty($logCurrencyRow)){
                        $logCurrencyRow = $logCurrencyRow[0];
                    }else{
                        //若 currency_log 表不存在该笔汇率，先插入该笔汇率
                        $logCurrencyRow = $oldCurrencyRow;
                        unset($logCurrencyRow['currency_id']);
                        $serviceCurrencyLogClass->add($logCurrencyRow);
                        $logCurrencyRow = Service_CurrencyLog::getByCondition($condition);
                        if(!empty($logCurrencyRow)){
                            $logCurrencyRow = $logCurrencyRow[0];
                        } else {
                            throw new Exception('currency_log 更新失败！');
                        }
                    }
                    //创建时间如果超过24小时，则停止原汇率，产生新batch编号
                    if((strtotime($nowTime) - strtotime($oldCurrencyRow['currency_add_time'])) >= 86400 ){
                        $bakCurrencyRow = $logCurrencyRow;
                        $newCurrencyRow = $row;
                        //更新 currency_log 表，把原纪录 stop
                        unset($bakCurrencyRow['currency_id']);
                        $bakCurrencyRow['currency_update_time'] = $nowTime;
                        $bakCurrencyRow['currency_stop_time']   = $nowTime;
                        $result_l = $serviceCurrencyLogClass->update($bakCurrencyRow,$logCurrencyRow['currency_id']);
                        
                        //更新 currency 
                        $newCurrencyRow['currency_add_time']        = $nowTime;
                        $newCurrencyRow['currency_batch_number']    = $nowBth;
                        $newCurrencyRow['currency_update_time']     = '0000-00-00 00:00:00';
                        $newCurrencyRow['currency_stop_time']       = '9999-09-09 00:00:00';
                        $result_c = $this->serviceClass->update($newCurrencyRow, $paramId);
                        if(!$recult_c){ $return['message'] = '异日更新currency失败'; }
                        //插入 currency_log 
                        unset($newCurrencyRow['currency_id']);
                        $serviceCurrencyLogClass->add($newCurrencyRow);
                    } else {
                        //创建时间如果不超24小时，更新log表，更新 currency 
                        $updateCurrencyRow = $row;
                        $updateCurrencyRow['currency_update_time']     = $nowTime;
                        $result_c   = $this->serviceClass->update($updateCurrencyRow, $paramId);
                        if(!$recult_c){ $return['message'] = '当日更新currency失败'; }
                        unset($updateCurrencyRow['currency_id']);
                        $result_l = $serviceCurrencyLogClass->update($updateCurrencyRow,$logCurrencyRow['currency_id']);
                    }
                } else {
                    $row['currency_add_time']       = date('Y-m-d H:i:s');
                    $row['currency_batch_number']   = $nowBth; /* 同一天内编辑都算同一批，我们假设汇率在一天之内不会有两次修改 */
                    $result_c   = $this->serviceClass->add($row);
                    $result_l   = $serviceCurrencyLogClass->add($row);
                    
                }
                if ($result_c && $result_l) {
                    $return['state'] = 1;
                    $return['message'] = array('Success.');
                }
                if(!$result_l){
                    $return['message'] = '更新currency_log失败';
                }
                if(!$recult_c){
                    $return['message'] = '更新currency失败';
                }

            }
        } catch (Exception $e) {
            $return['state'] = 0;
            $return['message'] = $e->getMessage();
        }
        die(Zend_Json::encode($return));
    }

    public function getByJsonAction()
    {
        $result = array('state' => 0, 'message' => 'Fail', 'data' => array());
        $paramId = $this->_request->getParam('paramId', '');
        if (!empty($paramId) && $rows = $this->serviceClass->getByField($paramId, 'currency_id')) {
            $rows=$this->serviceClass->getVirtualFields($rows);
            $result = array('state' => 1, 'message' => '', 'data' => $rows);
        }
        die(Zend_Json::encode($result));
    }

    public function deleteAction()
    {
        $result = array(
            "state" => 0,
            "message" => "Fail."
        );
        if ($this->_request->isPost()) {
            $paramId = $this->_request->getPost('paramId');
            if (!empty($paramId)) {
                if ($this->serviceClass->delete($paramId)) {
                    $result['state'] = 1;
                    $result['message'] = 'Success.';
                }
            }
        }
        die(Zend_Json::encode($result));
    }
    public function getByCodeAction(){
    	$result = array('state' => 0, 'message' => '货币无效', 'data' => array());
    	$currency_code = $this->_request->getParam('code', '');
    	if (!empty($currency_code) && $rows = $this->serviceClass->getByField($currency_code, 'currency_code')) {
    		$result = array('state' => 1, 'message' => '', 'data' => $rows);
    	}
    	die(Zend_Json::encode($result));
    }
}