<?php

class Ship_FeeController extends Ec_Controller_Action
{
    public function preDispatch()
    {
        $this->tplDirectory = "ship/views/";
        $this->serviceClass = new Service_OtherFee();
    }

    /**
     * @author william-fan
     * @todo 用于显示费用列表
     */
    public function listAction()
    {
        $status = Common_Status::SMStatus('auto');
        $currency = Common_DataCache::getCurrency();
        $warehouse = Common_DataCache::getWarehouseSimple();

        //载体
        $conditionApplication = array(
            'customer_id' => '0',
            'customer_code_empty' => ''
        );
        $applicationDate = Service_Application::getByCondition($conditionApplication, "*");
        $applicationDateKey = array();
        if (!empty($applicationDate)) {
            foreach ($applicationDate as $key => $app) {
                $applicationDateKey[$app['application_id']] = $app;
            }
        }
        /* echo "<pre>";
        print_r($applicationDateKey); */
        $feeunit = $this->serviceClass->getFeeUnit();
        $defaultFee = $this->serviceClass->getDefaultFee();
        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);
            unset($params);
            $count = $this->serviceClass->getByCondition($condition, 'count(*)');
            $return['total'] = $count;

            if ($count) {
                $showFields = array(
                    'fee_id',
                    'fee_name',
                    'fee_code',
                    'warehouse_id',
                    'fee_application_id',
                    'fee_unit',
                    'fee_value',
                    'fee_currency_code',
                    'is_default_fee',
                    'fee_discount',
                    'status',
                    'fee_amount',
                    'sp_code'
                );
                $showFields = $this->serviceClass->getFieldsAlias($showFields);
                $rows = $this->serviceClass->getByCondition($condition, $showFields, $pageSize, $page, array('fee_id desc'));
                $return['data'] = $rows;
                $return['state'] = 1;
                $return['feeunit'] = $feeunit;
                $return['warehouse'] = $warehouse;
                $return['application'] = $applicationDateKey;
                $return['defaultFee'] = $defaultFee;
                $return['status'] = $status;

                $return['message'] = "";
            }
            die(Zend_Json::encode($return));
        }
        $this->view->type     = Service_FeeType::getByCondition( array(), array('ft_code','ft_name_cn'));
        $this->view->attributeType = Service_OtherFeeProcess::$attributeType;
        $this->view->currency = $currency;
        $this->view->warehouse = $warehouse;
        $this->view->application = $applicationDate;
        $this->view->feeunit = $feeunit;
        $this->view->status = $status;
        $this->view->defaultFee = $defaultFee;
        $this->view->serviceProvider = Service_ServiceProvider::getByCondition(array(),'*',0);
        echo Ec::renderTpl($this->tplDirectory . "fee_index.tpl", 'layout');
    }

    /**
     * @author william-fan
     * @todo用于修改和添加费用
     */
    public function editAction()
    {
        $return = array(
            'state' => 0,
            'message' => '',
            'errorMessage' => array('Fail.')
        );

        if ($this->_request->isPost()) {
            $params = $this->_request->getParams();
            $row = array(
                'fee_id' => '',
                'fee_name' => '',
                'fee_code' => '',
                'warehouse_id' => '',
                'fee_application_id' => '',
                'fee_unit' => '',
                'fee_value' => '',
                'fee_currency_code' => '',
                'is_default_fee' => '',
                'fee_discount' => '',
                'status' => '',
                'fee_amount'=>'',
                'sp_code'=>'',
                'cost_currency_code'=>'',
                'remark'=>''
            );
            $row = $this->serviceClass->getMatchEditFields($params, $row);
            unset($params);

            $paramId = $row['fee_id'];
            if (!empty($paramId)) {
                unset($row['fee_id']);
            }
            $errorArr = $this->serviceClass->validator($row);

            if (!empty($errorArr)) {
                $return = array(
                    'state' => 0,
                    'message' => '',
                    'errorMessage' => $errorArr
                );
                die(Zend_Json::encode($return));
            }
            
            if(strlen($row['remark']) > 500){
                $return = array(
                    'state' => 0,
                    'message' => '备注项字符数超过500限制',
                    'errorMessage' => array('备注项字符数超过500限制')
                );
                die(Zend_Json::encode($return));
            }

            $conditionOtherFee = array(
                'fee_code' => $row['fee_code'],
            );
            $otherfeeRows = Service_OtherFee::getByCondition($conditionOtherFee);
            if (!empty($otherfeeRows)) {
                //添加时判断代码是否已经存在
                if( empty($paramId) ) {
                    $return = array(
                        'state' => 0,
                        'message' => '费用代码已存在',
                        'errorMessage' => array('费用代码已存在')
                    );
                    die(Zend_Json::encode($return));
                }
                $otherfeeRow = $otherfeeRows[0];
            }

            if( !isset( $row['fee_discount'] ) ) {
                $row['fee_discount'] = 1;//默认是不打折
            } else if( !is_numeric( $row['fee_discount'] ) ) {
                $return = array(
                    'state' => 0,
                    'message' => '折扣必须是数字',
                    'errorMessage' => array('折扣必须是数字')
                );
                die(Zend_Json::encode($return));
            } else if( $row['fee_discount'] <=0 || $row['fee_discount'] > 1 ) {
                $return = array(
                    'state' => 0,
                    'message' => '折扣大于0，且小于等于1',
                    'errorMessage' => array('折扣大于0，且小于等于1')
                );
                die(Zend_Json::encode($return));
            }
            //$smRow=Service_ShippingMethod::getByField($row['sm_code'],'sm_code');
            //$row['fee_id']=$otherfeeRow['fee_id'];
            unset($smRow);
            if (!empty($paramId)) {
                $result = $this->serviceClass->update($row, $paramId);
            } else {
                $result = $this->serviceClass->add($row);
            }
            if ($result) {
                $return['state'] = 1;
                $return['message'] = array('Success.');
            }

        }
        die(Zend_Json::encode($return));
    }

    /**
     * @author william-fan
     * @todo 用于得到费用的信息
     */
    public function getByJsonAction()
    {
        $result = array('state' => 0, 'message' => 'Fail', 'data' => array());
        $paramId = $this->_request->getParam('paramId', '');
        if (!empty($paramId) && $rows = $this->serviceClass->getByField($paramId, 'fee_id')) {
            $rows = $this->serviceClass->getVirtualFields($rows);
            $result = array('state' => 1, 'message' => '', 'data' => $rows);
        }
        die(Zend_Json::encode($result));
    }

    /**
     * @author william-fan
     * @todo 用于删除费用信息
     */
    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 getItemAction() {
        $warehouse = $this->_request->getParam('warehouse');
        $item = array();
        if( $warehouse ) {
            $item = Service_OtherFee::getByCondition( array('warehouse_id'=>$warehouse ),array('fee_name','fee_code'));
        }
        die(json_encode($item));
    }

    public function addAttributeAction() {
        $params = $this->_request->getParams();
        $obj = new Service_OtherFeeProcess();
        $result = $obj->addAttribute( $params );
        die(json_encode($result));
    }

    public function viewConfigAction() {
        $id = $this->_request->getParam('id','');
        $config = $item = array();
        if( $id) {
            $item  = Service_OtherFee::getByField( $id,'fee_id');
            if( $item ) {
                $attribute = Service_OtherFeeAttribute::getByCondition( array('fee_id'=>$id ),'*',0,0,array('ofa_value_type','ofa_id'));
                foreach($attribute as $key=>$value){
                    if( $value['ofa_value_type'] == 4 ) {
                        $configTable = Service_OtherFeeConfigTable::getByCondition( array('fee_id'=>$id,'ofa_id'=>$value['ofa_id']));
                        if( $configTable ) {
                            $tmpData = $data = array();
                            foreach( $configTable as $k => $v ) {
                                $text = $v['ofct_ref_code'];
                                if( $v['ofct_ref_id'] ) {
                                    $tmpRow = Service_OtherFeeAttribute::getByField($v['ofct_ref_id']);
                                    $text = $tmpRow['fia_name'];
                                }
                                $tmpData[$text][] = $v;
                            }
                            //行转列(数据表是的内容是列转行保存下来的)
                            $rows = count($configTable) / count($tmpData);
                            $keys = array_keys($tmpData);
                            for( $i=0; $i<$rows; $i++ ) {
                                foreach($keys as $k=>$v) {
                                    $data[$i][$k] = $tmpData[$v][$i]['ofct_value'];
                                }
                            }
                            $attribute[$key]['title'] = $keys;
                            $attribute[$key]['data'] = $data;
                        }
                        $config[1][] = $attribute[$key];
                    } else {
                        $configRow = Service_OtherFeeConfig::getByCondition( array('fee_id'=>$id,'ofa_id'=>$value['ofa_id']));
                        $attribute[$key]['config'] = $configRow[0];
                        $config[0][] = $attribute[$key];
                    }
                }
            }
        }
        //print_r($config);exit;
        $this->view->item = $item;
        $this->view->config = $config;
        echo EC::renderTpl( $this->tplDirectory.'view-config.tpl', 'layout');
        exit;
    }

    public function editConfigAction() {
        $params = $this->_request->getParams();
        $obj = new Service_OtherFeeProcess();
        $result = $obj->editConfig( $params );
        die(json_encode($result));
    }

    public function importTemplateAction(){
        $file = trim( $this->_request->getParam('file',''));

        $fullPath = APPLICATION_PATH."/../data/file/fee-item/region-insurance-price.csv";
        $filename = basename($fullPath);

        if($file === '' || !file_exists($fullPath)) {
            echo '文件不存在！';
        } else {
            header("Content-Type: APPLICATION/OCTET-STREAM");
            header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
            header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . 'GMT');
            header('Cache-Control: no-cache, must-revalidate');
            header('Pragma: no-cache');
            header("Content-Disposition: attachment; filename=".$filename.";");
            echo file_get_contents($fullPath);
        }
        exit;
    }

}