<?php
class Common_CountryController extends Ec_Controller_Action
{
    public function preDispatch()
    {
        $this->tplDirectory = "common/views/country/";
        $this->serviceClass = new Service_Country();
    }

    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(
                    
                'country_name',
                'country_name_en',
                'country_local_name',
                'country_alias',
                'country_code',
                'country_sort',
                'country_short_name',
                'country_id',
                'country_area',
                );
                $showFields = $this->serviceClass->getFieldsAlias($showFields);
                $rows = $this->serviceClass->getByCondition($condition,$showFields, $pageSize, $page, array('country_id desc'));
                $return['data'] = $rows;
                $return['state'] = 1;
                $return['message'] = "";
            }
            die(Zend_Json::encode($return));
        }
        echo Ec::renderTpl($this->tplDirectory . "country_index.tpl", 'layout');
    }

    public function editAction()
    {
        $return = array(
            'state' => 0,
            'message' => '',
            'errorMessage'=>array('Fail.')
        );

        if ($this->_request->isPost()) {
            $params = $this->_request->getParams();
            $row = array(
                
              'country_id'=>'',
              'country_name'=>'',
              'country_name_en'=>'',
              'country_local_name'=>'',
              'country_alias'=>'',
              'country_code'=>'',
              'country_sort'=>'',
              'country_short_name'=>'',
              'country_area'=>'',
            );
            $row=$this->serviceClass->getMatchEditFields($params,$row);
            $paramId = $row['country_id'];
            if (!empty($row['country_id'])) {
                unset($row['country_id']);
            }
            $errorArr = $this->serviceClass->validator($row);
            //验证输入数据
            $errorArr = $this->serviceClass->validateInput($row,$errorArr);

            if (!empty($errorArr)) {
                $return = array(
                    'state' => 0,
                    'message'=>'',
                    'errorMessage' => $errorArr
                );
                die(Zend_Json::encode($return));
            }

            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));
    }

    public function getByJsonAction()
    {
        $result = array('state' => 0, 'message' => 'Fail', 'data' => array());
        $paramId = $this->_request->getParam('paramId', '');
        if (!empty($paramId) && $rows = $this->serviceClass->getByField($paramId, 'country_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 downloadsAreaAction()
    // {
    //     $quick = $this->_request->getParam('quick', 1);
    //     if($quick!=6){
    //         echo '无效地址！';exit();
    //     }
    //     set_time_limit(0);
    //     @ini_set('memory_limit','1024M');
    //     $csvTitle = array();
    //     $csvTitle[0] =   array(
    //     '国家名称','国际简称','区域');
    //     echo Common_Export::exportCsvForNotKey($csvTitle);
    //     unset($csvTitle);
    //     $index = 1;
    //     $country = Service_Country::getAll();
    //     $csvData = array();
    //     foreach ($country as $key => $value) {
            
    //         $csvData[$index][0]  =   $value['country_name'];
    //         $csvData[$index][1]  =   $value['country_code'];
    //         $csvData[$index][2]  =   $value['country_area'];
    //         ksort($csvData[$index]);  
    //         $index++;
    //     }
    //     echo Common_Export::exportCsvForNotKey($csvData);
    //     $csvData = array();
    //     header('Content-Type: application/vnd.ms-excel;charset=gbk');
    //     header("Content-Disposition: attachment;filename=downloadsArea".date("YmdHis").".csv");
    //     header('Cache-Control: max-age=0');
    //     die();
    // }

    public function uploadTemplateAreaAction()
    {
        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');
        $fullPath = APPLICATION_PATH."/../data/xls".'/upload-area-template.xls';
        $filename = basename($fullPath);
        header("Content-Type: APPLICATION/OCTET-STREAM");
        $header="Content-Disposition: attachment; filename=".$filename.";";
        header($header );
        echo file_get_contents($fullPath);
        exit;
    }

    // public function updateContryAreaAction()
    // {   
    //     $quick = $this->_request->getParam('quick', 1);
    //     if($quick!=6){
    //         echo '无效地址！';exit();
    //     }
    //     $resultArray = Common_Upload::readEXCELNew(APPLICATION_PATH.'/../data/xls/country_area.xlsx');
    //     if(empty($resultArray)){echo '数据不存在！';}
    //     $i = 1;
    //     $result = array();
    //     $return = array();
    //     foreach ($resultArray as $key => $value) {
    //         if($i==1){$i++;continue;}
    //         $data = array();
    //         $data = Service_Country::getByField($value['2'],'country_code');
    //         if(!empty($data)){
    //             $row['country_area'] = $value['4'];
    //             $db = Common_Common::getAdapter();
    //             $db->beginTransaction();
    //             try{
    //                 $paramId = $data['country_id'];
    //                 $result = $this->serviceClass->update($row, $paramId);
    //                 if($result){
    //                    $return['state'] = $result;
    //                    $return['message'] = 'Success'; 
    //                 }
    //                 $db->commit();
    //             }catch (Exception $e){
    //                 $db->rollBack();
    //                 $return['state'] = 0;
    //                 $return['message'] = $e->getMessage();
    //                 throw new Exception($return);
    //                 break;
    //             }
    //         }  
    //     }
    //     print_r($return);exit;
    // }

    /*导入修改国家区域值*/
    public function uplodeAreaValueAction(){
        $result = array("ask"=>1,"message"=>"",'error'=>array(),'data'=>array());
        $xlsData = Service_Country::getXLSData($_FILES,'file');
        if(count($xlsData[0])!=3||($xlsData[0][0]!="国家名称"||$xlsData[0][1]!="国家简称"||$xlsData[0][2]!="区域")){
            $result['ask'] = "0";
            $result['error'][] = "文件格式错误，首行不是按照file,国家简称,区域!";
            die(json_encode($result));
        }
        if(count($xlsData)<=1){
            $result['ask'] = "0";
            $result['error'][] = "请在模版中输入您想更新的数据!";
            die(json_encode($result));
        }
        // print_r($xlsData);exit;
            foreach($xlsData as $key=>$value){
                if($key==0) continue;
                $existError = 0;
                $country_name=trim($value[0]);
                $country_code=trim($value[1]);
                $country_area=trim($value[2]);
                $resultData = array(
                    'country_name'=>$country_name,
                    'country_code'=>$country_code,
                    'country_area'=>$country_area,
                    'ok'=>1
                );
                $resultData['message'] = "";
                if($country_name==""){
                    $existError = 1;
                    $resultData['message'] .= "国家名称为空;";
                }
                if($country_code==""){
                    $existError = 1;
                    $resultData['message'] .= "国家简称为空;";
                }
                if($country_area==""){
                    $existError = 1;
                    $resultData['message'] .= "区域为空;";
                }
                if($existError) {
                    $resultData['ok'] = '0';
                    $result['data'][] = $resultData;
                    continue;
                }
               
                $customer = Service_Country::getByField($country_name,'country_name',"*");
                if(empty($customer)){
                    $resultData['message'] .= "不存在国家名称".$country_name;
                    $resultData['ok'] = '0';
                    $result['data'][] = $resultData;
                    continue;
                }
                $p = Service_Country::getByCondition(array('country_name'=>$country_name,'country_code'=>$country_code),"*");
                if(empty($p)){
                    $resultData['message'] .= "国家名称:".$country_name."不存在国家简称:".$country_code;
                    $resultData['ok'] = '0';
                    $result['data'][] = $resultData;
                    continue;
                }
                // print_r($p[0]);exit;
                $countryInfo=$p[0];
                try {
                $db=Common_Common::getAdapter();
                $db->beginTransaction();
                    $updateArray=array(
                        'country_area'=>trim($country_area),
                    );
                    if(Service_Country::update($updateArray,$countryInfo['country_id'])){
                        $resultData['message']='更新成功';
                        $result['data'][] = $resultData;
                    }else{
                        throw new Exception('更新失败或者当前值未改变!');
                    }
                $db->commit();
            } catch (Exception $e) {
                $resultData['ok'] = '0';
                $resultData['message']= $e->getMessage();
                $result['data'][] = $resultData;
                $db->rollBack();
            }
        }
          die(json_encode($result));
    }
}