<?php
class Financial_RebillingController extends Ec_Controller_Action
{
    public function preDispatch()
    {
        $this->tplDirectory = "financial/views/rebilling/";
        $this->serviceClass = new Service_BilRebillingSetting();
    }

    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(
                    'brs_id',
                    'customer_code',
                    'sm_code',
                    'creater_id',
                    'creat_time',
                    'update_user',
                    'update_time',
                );
                $showFields = $this->serviceClass->getFieldsAlias($showFields);
                $rows = $this->serviceClass->getByCondition($condition,$showFields, $pageSize, $page, array('brs_id desc'));
                $return['data'] = $rows;
                $return['state'] = 1;
                $return['message'] = "";
            }
            $userData = Service_User::getAll();
            $userArr = array();
            foreach ($userData as $userRow) {
                $userArr[$userRow['user_id']] = $userRow['user_name'];
            }
            $return['user'] = $userArr;
            die(Zend_Json::encode($return));
        }
        echo Ec::renderTpl($this->tplDirectory . "list.tpl", 'layout');
    }

    public function editAction()
    {
        $return = array(
            'state' => 0,
            'message' => '',
            'errorMessage'=>array('Fail.')
        );
        if ($this->_request->isPost()) {
            $params = $this->_request->getParams();
            $row = array(
                'brs_id' => '',
                'customer_code'=>'',
                'sm_code'=>'',
            );
            $row = $this->serviceClass->getMatchEditFields($params, $row);
            $paramId = $row['brs_id'];
            if (!empty($row['brs_id'])) {
                unset($row['brs_id']);
            }
            $errorArr = $this->serviceClass->validator($row, $paramId);
            if (!empty($errorArr)) {
                $return = array(
                    'state' => 0,
                    'message'=>'',
                    'errorMessage' => $errorArr
                );
                die(Zend_Json::encode($return));
            }
            if (!empty($paramId)) {
                $row['update_user'] = $this->_userAuth->user['user_id'];
                $row['update_time'] = date('Y-m-d H:i:s');
                $result = $this->serviceClass->update($row, $paramId);
            } else {
                $row['creater_id'] = $row['update_user'] = $this->_userAuth->user['user_id'];
                $row['creat_time'] = $row['update_time'] = date('Y-m-d H:i:s');
                $result = $this->serviceClass->add($row);
            }
            if ($result) {
                $return['state'] = 1;
                $return['message'] = array('操作成功');
            }
        }
        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, 'brs_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'] = '操作成功';
                }
            }
        }
        die(Zend_Json::encode($result));
    }

    /**
     * [resetBillingAction 重新计费]
     * @return [type] [description]
     */
    public function resetBillingAction(){
        echo Ec::renderTpl($this->tplDirectory . "reset_billing.tpl", 'layout');
    }

    /**
     * @todo 批量重新计费 - 验证数据及展示结果
     */
    public function batchrefeeAction(){
        $orderUpload = new Zend_Session_Namespace('orderBillingResetFee');
        $field = 'orderBillingResetFee';
        $xlsData = Service_BilRebillingSetting::getData($field);
        $tableHeader = $xlsData[0];
        if(count($tableHeader) != 4 || $tableHeader[0] != '客户代码' || $tableHeader[1] != '运输方式' || $tableHeader[2] != '运单号' || $tableHeader[3] != '服务商重量(KGS)'){
            $xlsData['ask'] = 0;
            $xlsData['message'] = '上传表格表头错误，不是&nbsp;[客户代码|运输方式|运单号|服务商重量(KGS)]&nbsp;格式，请核对后重新上传；';
        }
        if(isset($xlsData['ask']) && $xlsData['ask']=='0'){
            $this->view->uploadinfo = $xlsData;
            echo Ec::renderTpl($this->tplDirectory . "reset_billing.tpl",'layout');
        }else {
            $orderRows = Service_BilRebillingSetting::getDataArr($xlsData);
            $orderUpload->uploadData = $orderRows;
            $doupload = true;
            if(!empty($orderRows)){
                foreach($orderRows as $key=>$order){
                    if($order['is_valid']=='0'){
                        $doupload = false;
                    }
                }
            }
            $this->view->doupload=false;
            $this->view->uploadData=$orderRows;
            echo Ec::renderTpl($this->tplDirectory . "reset_billing_fee_check.tpl",'layout');
        }
    }

    /**
     * @todo 处理批量重新计费
     */
    public function importfeeAction(){
        set_time_limit(900);
        ini_set('memory_limit', '2048M');
        //预定义变量
        $message = '';
        $success = 0;
        $fail = 0;
        $orderUpload = new Zend_Session_Namespace('orderBillingResetFee');
        $sessionData = $orderUpload->uploadData;
        $select = $this->_request->getParam('select','');
        $currentDate = date("Y-m-d H:i:s");
        if(!empty($select)){
            if(!empty($sessionData)){
                foreach($sessionData as $key=>$value){
                    $value['so_service_provider_weight'] = number_format($value['so_service_provider_weight'], 3, '.', '');
                    $db = Common_Common::getAdapter();
                    $db->beginTransaction();
                    try{
                        if(!in_array($value['order_code'], $select)){
                            throw new Exception('<div>单号：'.$value['order_code'].'&nbsp;未处理</div>');
                        }
                        if($value['is_valid']=='1'){
                            //更新服务商重量
                            $soData = Service_ShipOrder::getByField($value['order_code'], 'order_code', array('so_id', 'so_code', 'so_status', 'so_service_provider_weight'));
                            if(empty($soData) || !$soData){
                                throw new Exception('<div>单号：'.$value['order_code'].'&nbsp;物流单不存在</div>');
                            }
                            if($soData['so_service_provider_weight'] == $value['so_service_provider_weight']){
                                throw new Exception('<div>单号：'.$value['order_code'].'&nbsp;服务商收货复核的计费重量原重量['.$soData['so_service_provider_weight'].']等于新重量['.$value['so_service_provider_weight'].'], 重量未更改不需要重新计费</div>');
                            }
                            $logRow = array(
                                'so_id' => $soData['so_id'],
                                'so_code' => $soData['so_code'],
                                'so_status_start' => $soData['so_status'],
                                'so_status_end' => $soData['so_status'],
                                'user_id' => $this->_userAuth->user['user_id'],
                                'add_time' => $currentDate,
                                'note' => '修改服务商收货复核的计费重量:'.$soData['so_service_provider_weight']."=>".$value['so_service_provider_weight'],
                                'visit_ip' => Common_Common::getIP(),
                            );
                            $solRes = Service_ShipOrderLog::add($logRow);
                            if( !$solRes ){
                                throw new Exception('<div>单号：'.$soData['so_code'].'&nbsp;日志写入失败</div>');
                            }
                            //更新服务商重量
                            $updateRow = array('so_service_provider_weight'=> $value['so_service_provider_weight'], 'so_update_time'=> $currentDate);
                            $rboUpdateRes = Service_ShipOrder::update($updateRow, $soData['so_id'], 'so_id');
                            if(!$rboUpdateRes){
                                throw new Exception('<div>单号：'.$soData['so_code'].'&nbsp;服务商收货复核的计费重量更新失败</div>');   
                            }
                        }
                        $db->commit();
                    } catch (Exception $e) {
                        $db->rollBack();
                        $message .= $e->getMessage();
                        continue;
                    }
                    //重新计费
                    $param = array(
                        'refer_code' => $value['order_code'],
                        'ds_code' => 'so',
                    );
                    $obj = new Process_BusinessIncome();
                    $result = $obj->readjustmentTransaction($param, '1');
                    if($result['state'] == '1'){
                        $message.='<div>单号：'.$value['order_code']." : ".$result['message'].'</div>';
                        $success++;
                    }else{
                        $message.='<div>单号：'.$value['order_code']." : ".$result['message'].'</div>';
                        $fail++;
                    }
                }
                $message.="<div>合计：成功{$success}个,失败{$fail}个</div>";
            }else{
                $message .= '<div>数据失效, 请重新上传</div>';
            }
        }else{
            $message .= '<div>未选择数据</div>';
        }
        $this->view->uploadResult = $message;
        echo Ec::renderTpl($this->tplDirectory . "reset_billing.tpl",'layout');
    }
    /**
     * @todo 下载模板
     */
    public function downtempleAction(){
        $file = $this->_request->getParam('file','');
        $fullPath = APPLICATION_PATH."/../data/file".'/rebilling.xls';
        //方法2
        $filename = uniqid().'_'.basename($fullPath);
        header("Content-Type: APPLICATION/OCTET-STREAM");
        //Force the download
        $header="Content-Disposition: attachment; filename=".$filename.";";
        header($header );
        //  header("Content-Transfer-Encoding: binary");
        //  header("Content-Length: ".$len);
        echo file_get_contents($fullPath);
        exit;
    }
}