<?php

class Default_IndexController extends Ec_Controller_DefaultAction
{

    public function preDispatch()
    {
        $this->view->errMsg = '';
        $this->tplDirectory = "default/views/default/";
    }

    public function indexAction()
    {
    	$this->_redirect('/login');
    	exit;
        $wh=Service_Warehouse::getAll();
        $this->view->msg = 'www.oms.com';
       // echo $this->view->render($this->tplDirectory . 'index.tpl');//不使用布局文件
        echo Ec::renderTpl($this->tplDirectory . "index.tpl", 'layout');//使用布局文件
    }

    public function getFreightAction()
    {
        $countries = Service_Country::getAll();

        $this->view->countries = $countries;
        echo $this->view->render($this->tplDirectory . 'getFreight.tpl');
    }

    public function calculateShippingFreightAction()
    {
        if($this->_request->isPost())
        {
            $result = array('status'=>false,'error'=>array(),'data'=>array(),'st'=>array());
            $param = $this->_request->getParams();
            $errArr = $this->validateParams($param);

            if(!empty($errArr))
            {
                $result['error'] = $errArr;
                echo json_encode($result);exit;
            }
            $cityWhere = array('country_id'=>$param['toCountry'],'city_name'=>$param['toCity']);
            $city = Service_City::getByWhere($cityWhere);

            if(empty($city))
            {
                $result['error'] = "国家或城市不存在";
                echo json_encode($result);exit;
            }
            $resultData = array();
            foreach ($param['logistics-express-item'] as $key => $value) {
                $apiParams = array();
                $smCodeModel = Service_ShippingMethod::getByField($value,"sm_code");

                if(empty($smCodeModel))
                {
                    continue;
                }

                $apiParams['warehouseId'] = 1;
                $apiParams['countryId']   = $param['toCountry'];
                $apiParams['smId']        = $smCodeModel['sm_id'];
                $apiParams['smCode']      = $smCodeModel['sm_code'];
                $apiParams['weight']      = $param['packageWeight'];
                $apiParams['length']      = $param['packageLength'];
                $apiParams['width']       = $param['packageWidth'];
                $apiParams['height']      = $param['packageHeight'];
                $apiParams['cityId']      = $city['city_id'];
                $apiParams['postcode']    = trim($param['toPostCode']);

                $objCalculate = new Common_CalculateShipping( $apiParams );
                $cost = $objCalculate->getRate();
                $data = array();
                if(($cost['state'] == 1) && ($cost['data']['cost']['totalCost']>0))
                {
                    $data['sm_code']           = $cost['data']['sm']['sm_code'];
                    $data['cost']              = $cost['data']['cost']['totalCost'];
                    $data['delivery_time_min'] = $cost['data']['sm']['sm_delivery_time_min'];
                    $data['delivery_time_max'] = $cost['data']['sm']['sm_delivery_time_max'];
                    $data['limit_weight']      = $cost['data']['sm']['sm_limit_weight'];
                    $result['data'][] = $data;
                }
            }

            if(empty($result['error']) && empty($result['data']))
            {
                $result['st'][] = "暂时没有数据";
            }
            if(!empty($result['data']))
            {
                $result['status'] = true;
            }

            echo json_encode($result);
        }

    }
    private function validateParams($params)
    {
        $err = array();

        if(!isset($params['toCountry']) || !is_numeric($params['toCountry']))
        {
            $err[] = "请选择正确的国家";
        }
        else
        {
            $country = Service_Country::getByField($params['toCountry']);
            if(empty($country))
            {
                $err[] = "国家不存在";
            }
        }

        if(!isset($params['toCity']) || empty($params['toCity']))
        {
            $err[] = "请选城市不能为空";
        }

        if(!isset($params['logistics-express-item']) || empty($params['logistics-express-item']) || !is_array($params['logistics-express-item']))
        {
            $err[] = "运输方式必须填写";
        }

        if(is_array($params['logistics-express-item']))
        {
            $tag = false;
            foreach ($params['logistics-express-item'] as $key => $value) {
                if(!in_array($value, array("UPS-GY","BH-HKDHL")))
                {
                    $tag = true;
                }
            }
            if($tag){
                $err[] = "运输方法必须是UPS或DHL";
            }
        }

        if(!isset($params['packageLength']) || !is_numeric($params['packageLength']))
        {
            $err[] = "请填写正确的长度";
        }
        if(!isset($params['packageWidth']) || !is_numeric($params['packageWidth']))
        {
            $err[] = "请填写正确的宽度";
        }
        if(!isset($params['packageHeight']) || !is_numeric($params['packageHeight']))
        {
            $err[] = "请填写正确的高度";
        }
        if(!isset($params['packageWeight']) || !is_numeric($params['packageWeight']))
        {
            $err[] = "请填写正确的重量";
        }
        return $err;

    }

    public function loginAction()
    {
        die('login');
    }

    public function logoutAction()
    {
        $session = new Zend_Session_Namespace('customerAuth');
        $session->unsetAll();
        session_destroy();
    }

    /*
     * @输出验证码
     */
    public function verifyCodeAction()
    {
        $verifyCode = new Common_Verifycode();
        $verifyCode->set_sess_name('AdminVerifyCode');
        echo $verifyCode->render();
    }
    /**
     * @author william-fan
     * @todo 条码
     */
    public function barcodeAction(){
      $option = array();

      if (NULL !== $this->_request->getParam('height', NULL)) {
        $option['height'] = $this->_request->getParam('height');
      }

      if (NULL !== $this->_request->getParam('width', NULL)) {
        $option['width'] = $this->_request->getParam('width');
      }

      if (NULL !== $this->_request->getParam('show', NULL)) {
        $option['show'] = (bool) $this->_request->getParam('show');
      }

      if (NULL !== $this->_request->getParam('type', NULL)) {
        $option['type'] = $this->_request->getParam('type');
      }
       if (NULL !== $this->_request->getParam('codeType', NULL)) {
        $option['codeType'] = $this->_request->getParam('codeType');
      }
      if (!empty($option)) {
        Common_Barcode::render($this->_request->code, $option);
      }
      else {
        Common_Barcode::barcode($this->_request->code);
      }

    	exit;
    }
    /**
     * author william-fan
     * @todo 用于改变语言
     */
    public function changeLangAction(){
    	if($this->_request->isPost()){
    		$langCode = $this->_request->getParam('langCode');
    		if($langCode){
    			$sessionUser = new Zend_Session_Namespace("userAuthorization");
    			$sessionUser->lang = $langCode;
                setcookie('LANGUAGE',$langCode,0,'/');
    			echo json_encode('1');
    			die();
    		}
    	}

    }
    public function headerInnerAction(){
        echo $this->view->render($this->tplDirectory . 'header-inner.tpl');
    }
    public function headerAction(){
        //$session			= new Zend_Session_Namespace('RegisterStep');
        //$session->step = '4';
        //$this->view->step = $session->step;
        echo $this->view->render($this->tplDirectory ."header.tpl");
    }

    /* 上传图片查看 */
    public function viewUploadImageAction ()
    {
        $fileName = $this->_request->getParam('fileName', "");
		$customerCode = $this->_request->getParam('customerCode', "");
        $path = APPLICATION_PATH . "/../data/images/register/" .$customerCode.'/'. $fileName;
   //echo $path;exit;
        if (file_exists($path)) {
            header('Content-Type: image/jpeg');
            echo file_get_contents($path);

        } else {
            header("Location: /images/noimg.jpg");
        }

        exit();
    }

	/*客人LOGO*/
    public function viewLogoImageAction(){
		$customerCode = $this->_request->getParam('customerCode', "");
		if(empty($customerCode)){ exit;}
		$customer_array = Service_Customer::getByField($customerCode, 'customer_code');
		$fileName = $customer_array['customer_logo'];
        $path = APPLICATION_PATH . "/../data/images/register/" .$customerCode.'/'. $fileName;
   //echo $path;exit;
        if (file_exists($path)) {
            header('Content-Type: image/jpeg');
            echo file_get_contents($path);

        } else {
            header("Location: /images/noimg.jpg");
        }

        exit();
    }

    /**
     * @查看产品图片
     * @desc WMS 全站使用
     */
    public function viewProductImgAction()
    {
        $productId = $this->_request->getParam('id', "");
        if ($productId) {
            $productAttach = Service_ProductAttached::getByField($productId, 'product_id');
            if ($productAttach) {
                if ($productAttach['pa_file_type'] == 'link') {
                    header("Location: " . $productAttach ['pa_path']);
                    exit ();
                }
                if ($productAttach['pa_file_type'] == 'img') {
                    header("Location: http://develop-oms.ez-wms.com/product-image/view-attach/productId/" . $productId);
                    exit ();
                }
            }
        }
        header("Location: /images/noimg.jpg");
        exit ();
    }

    public function taxRebateImageAction(){
        $trId = $this->_request->getParam("tr_id","");
        $trRow = Service_TaxRebate::getByField($trId,'tr_id',"*");
        $path = APPLICATION_PATH.'/../data/images/taxrebate/'.$trRow['customer_code']."/".$trRow['filename'] ;
        if(empty($trRow)||$trRow['filename']==""){
            header("Location: /images/noimg.jpg");
            exit();
        }
        if (file_exists($path)) {
            header('Content-Type: image/jpeg');
            echo file_get_contents($path);

        } else {
            header("Location: /images/noimg.jpg");
        }
        exit();
    }

    public function downloadTaxImageAction(){
        $trId = $this->_request->getParam("tr_id","");
        $trRow = Service_TaxRebate::getByField($trId,'tr_id',"*");
        //方法2
        $fullPath = APPLICATION_PATH.'/../data/images/taxrebate/'.$trRow['customer_code']."/".$trRow['filename'] ;

        if(empty($trRow)||$trRow['filename']==""){
            header('Content-Type: image/jpeg');
            header("Location: /images/noimg.jpg");
            //header($header );
            exit;
        }

        $fileArray = explode(".",$trRow['filename']);

        if($fileArray[1]!="pdf"){
            header('Content-Type: application/pdf; charset=utf-8');
            header("Content-Disposition:inline; filename=".$trRow['taxrebate_code'].".pdf");
            echo file_get_contents($fullPath);
            exit;
        }else{
            header('Content-Type: image/'.$fileArray[1]);
            //Force the download
            $header="Content-Disposition: attachment; filename=".$trRow['taxrebate_code'].".".$fileArray[1];
            header($header );
            // 	header("Content-Transfer-Encoding: binary");
            // 	header("Content-Length: ".$len);
            echo file_get_contents($fullPath);
            exit;
        }
    }

    /**
     * @author william-fan
     * @todo 签名
     */
    public function signatureAction(){
    	/* echo APPLICATION_PATH;
    	exit; */
    	$ttfPath = APPLICATION_PATH.'/../data/font/english111 .ttf';
    	$name = $this->_request->getParam('name','');
    	Header("Content-type: image/gif");
    	$im = imagecreate(150,20);
    	$black = ImageColorAllocate($im, 255,255,255);
    	$white = ImageColorAllocate($im, 0,0,0);
    	imagettftext($im, 20, 0, 10, 20, $white, $ttfPath, $name);
    	ImageGif($im);
    	ImageDestroy($im);
    }

    /**
     * @desc 返回运输方式代码
     * @use 打印机设置
     */
    public function setupPrinterAction() {
        $result = array('state' => 1, 'data' => array('A4'));
        if ($this->_request->isPost()) {
            $smArr = Service_ShippingMethod::getByCondition(array('sm_status'=>1),"*");
            $sm = array();
            $sm[] = 'A4';
            foreach($smArr as $row){
                $sm[] = $row['sm_code'];
            }
            if (!empty($smArr)) {
                $result = array('state' => 1, 'data' => $sm);
            }
        }
        die(Zend_Json::encode($result));
    }

    public function printLabelAction() {
        $logisticsCode = $this->_request->getParam("logisticsCode","");
        if(empty($logisticsCode)) exit('error parameter');
        $aOrder = Service_LogisticsOrder::getByField($logisticsCode, 'logistics_code');
        if(empty($aOrder)) exit('error parameter');
        $smInfo = Service_ShippingMethod::getByField($aOrder['sm_code'],"sm_code","*");
        //平邮
        //if($smInfo['sm_class_code']=="CPS") $aOrder['ref_tracking_number'] = "";
        //$aOrder['tracking_number'] = Service_ServiceTrackingNumber::getTrackingNumber($aOrder['sm_code'], $aOrder['ref_tracking_number']);
        $aAddress = Service_LogisticsOrderAddress::getByWhere(array('logistics_code'=>$logisticsCode, 'loa_type'=>0));
        $country = Service_Country::getByField($aAddress['loa_country'],'country_id',"*");
        $aAddress['country_name_en'] = $country['country_name_en'];
        $aAddress['country_name'] = $country['country_name'];
        $hsList = Service_LogisticsOrderHs::getByCondition(array('logistics_code'=>$logisticsCode));
        $total_price = 0.00;
        foreach($hsList as $hsRow) $total_price += $hsRow['loh_total_price'];
        $aOrder['counthsList'] = count($hsList)>5?5:count($hsList);
        $this->view->totalPrice = $total_price;
        $this->view->aOrder = $aOrder;
        $this->view->aAddress = $aAddress;
        $this->view->hsList = $hsList;
        $this->view->smInfo = $smInfo;
        $this->view->country = $country;
        $this->view->area = '';
        $this->view->packNo = '';

        if ('HKPG' == $aOrder['sm_code']) {
            // 获取国家映射区域代码
            $smCountryMap = Service_SmCountryMap::getByInCondition(array(
                'warehouse_id_arr' => array(0, $aOrder['warehouse_id']),
                'sm_code' => $aOrder['sm_code'],
                'country_code' => $country['country_code']
            ));
            if ($smCountryMap) {
                $this->view->area = $smCountryMap[0]['area'];
            }
        }
        elseif ('HKPP' == $aOrder['sm_code']) {
            // 获取包袋号
            $this->view->packNo = Service_ChangePack::getPackNo($country['country_code'], $aAddress['loa_zipcode']);
            // 获取国家映射区域代码
            $smCountryMap = Service_SmCountryMap::getByInCondition(array(
                'warehouse_id_arr' => array(0, $aOrder['warehouse_id']),
                'sm_code' => $aOrder['sm_code'],
                'country_code' => $country['country_code']
            ));
            if ($smCountryMap) {
                $this->view->area = $smCountryMap[0]['area'];
            }
        }
        $tplDirectory = "merchant/views/logistics/";
        if($aOrder['sm_code']=='HKDHL' || 'SZY-EMS' == $aOrder['sm_code'] || 'AUP' == $aOrder['sm_code'])
            echo $this->view->render($tplDirectory . "/label/F4.tpl");
        elseif($aOrder['sm_code']=='BH-SGG' || $aOrder['sm_code']=='BH-SGP'){
            echo $this->view->render($tplDirectory . "/label/sg.tpl");
        }
        elseif($aOrder['sm_code']=="BZAM"){
            echo $this->view->render($tplDirectory."/label/bzam.tpl");
        }
        elseif ('BH-MPPG' == $aOrder['sm_code']) {
            echo $this->view->render($tplDirectory . '/label/bh-mppg.tpl');
        }
        elseif ('HKPG' == $aOrder['sm_code']) {
            echo $this->view->render($tplDirectory . '/label/hkpg.tpl');
        }
        elseif ('HKPP' == $aOrder['sm_code']) {
            echo $this->view->render($tplDirectory . '/label/hkpp.tpl');
        }
        elseif ('CJ-DGMG' == $aOrder['sm_code']) {
            echo $this->view->render($tplDirectory . '/label/cj-dgmg.tpl');
        }
        elseif ('CJ-DGMP' == $aOrder['sm_code']) {
            echo $this->view->render($tplDirectory . '/label/cj-dgmp.tpl');
        }else{
            echo $this->view->render($tplDirectory . "/label/sw.tpl");
        }
    }

    public function batchPrintLabelAction(){
        $orderCodeStr = $this->_request->getParam("orderCodes","");
        $orderCodeArr = explode(",",$orderCodeStr);

        if(empty($orderCodeStr)){
            $receivingCode = $this->_request->getParam("receiving_code","");
            $receivingCodeArr = explode(",",$receivingCode);
            foreach ($receivingCodeArr as $value) {
                if($value == '')continue;
                $rod = Service_ReceivingOrderDetail::getByCondition(array('receiving_code'=>$value),array('order_code'));
                if(!empty($rod)){
                    foreach($rod AS $val){
                        $orderCodeArr[] =   $val['order_code'];
                    }
                }
            }
        }

        $orderList = array();
        foreach($orderCodeArr as $orderCode){
            if($orderCode=="") continue;
            $o = array();
            $totalWeight=0;
            $totalValue=0;
            $orderInfo = Service_Orders::getByField($orderCode,'order_code',"*");
            $orderAddress = Service_OrderAddressBook::getByField($orderInfo['order_code'],"order_code","*");
            $country = Service_Country::getByField($orderAddress['oab_country_id'],'country_id',"*");
            $orderAddress['country'] = $country;
            $orderInfo['address'] = $orderAddress;
            $products = Service_OrderProduct::getByCondition(array('order_code'=>$orderCode),"*");
            foreach($products as $keyp=>$valuep){
                $product = Service_Product::getByField($valuep['product_id']);
                $products[$keyp]['product_weight'] = $product['product_weight'];
                $products[$keyp]['hs_code'] = $product['hs_code'];

                // PNLG PNLP运输方式，需要把目的海关申报价值转换为EUR欧元
                if ('PNLG' === trim($orderInfo['sm_code']) || 'PNLP' === trim($orderInfo['sm_code']) || 'PNLN' === trim($orderInfo['sm_code'])) {
                    $revertToEur = Service_Currency::converByCode('USD', 'EUR', $valuep['op_purpose_declared_value']);
                    $products[$keyp]['op_purpose_declared_value'] = $revertToEur;
                }
                $totalValue+=floatval($valuep['op_purpose_declared_value']*$valuep['op_quantity']);
                $totalWeight+=floatval($product['product_weight']*$valuep['op_quantity']);
            }
            $orderInfo['orderProduct'] = $products;
            $orderInfo['totalWeight']=$totalWeight;
            $orderInfo['totalValue']=$totalValue;
            if ('HKPP' === trim($orderInfo['sm_code'])) { // HKPP运输方式需要计算包袋号
                $orderInfo['pack_no'] = Service_ChangePack::getPackNo($country['country_code'], $orderAddress['oab_postcode']);
                $smCountryMap = Service_SmCountryMap::getByInCondition(array(
                    'warehouse_id_arr' => array(0, $orderInfo['warehouse_id']),
                    'sm_code' => $orderInfo['sm_code'],
                    'country_code' => $country['country_code']
                ));

                if ($smCountryMap) {
                    $orderInfo['country_area'] = $smCountryMap[0]['area'];
                }
                else {
                    $orderInfo['country_area'] = '';
                }
            }
            elseif ('HKPG' == trim($orderInfo['sm_code'])) { // 获取国家映射区域代码
                $smCountryMap = Service_SmCountryMap::getByInCondition(array(
                    'warehouse_id_arr' => array(0, $orderInfo['warehouse_id']),
                    'sm_code' => $orderInfo['sm_code'],
                    'country_code' => $country['country_code']
                ));

                if ($smCountryMap) {
                    $orderInfo['country_area'] = $smCountryMap[0]['area'];
                }
                else {
                    $orderInfo['country_area'] = '';
                }
            }
            elseif ('PNLG' === trim($orderInfo['sm_code']) || 'PNLP' === trim($orderInfo['sm_code']) || 'PNLN' === trim($orderInfo['sm_code'])) {
                $currency = Service_Currency::getByField('EUR', 'currency_code');
                $orderInfo['currency_symbol'] = $currency ? $currency['currency_symbol_left'] : '';
            }
            if(in_array($orderInfo['sm_code'],array('TWPG','TWPP'))){
                $orderInfo['change_code']=  Service_HjtwApi::getCode($orderAddress['oab_country_id'], $orderAddress['oab_postcode'],$orderInfo['sm_code']);
                if(empty($orderInfo['print_no'])){
                    $printNo=Service_OrderProcess::getPrintNo();
                    $orderInfo['print_no']=$printNo;
                    $updateOrder=array(
                        'print_no'=>$printNo
                    );
                    Service_Orders::update($updateOrder,$orderInfo['order_id']);
                }
            }
            //$serviceTracking=Service_ServiceTrackingNumber::getByField($orderCode,'order_code');
            if(!in_array($orderInfo['sm_code'],array('SWPT','BH-MMP'))){
                $trackingNumber = $orderCode;
            }else{
                $trackingNumber = $orderInfo['ref_tracking_number'];
            }
            /*if(!empty($serviceTracking)){
                $trackingNumber = $serviceTracking['stn_code'];
                $trackingNumber=Service_ServiceTrackingNumber::getTrackingNumber($orderInfo['sm_code'], $trackingNumber);
            }*/
            $orderInfo['ship']['tracking_number'] = $trackingNumber;
            $tpaRows = Service_TransportPickArea::getByCondition(array('sm_code' => $orderInfo['sm_code'], 'country' => $orderInfo['address']['country']['country_code']), array('area_code'));
            $orderInfo['pick_area'] = isset($tpaRows[0]['area_code'])?$tpaRows[0]['area_code']:'';

            $smInfo = Service_ShippingMethod::getByField($orderInfo['sm_code'],"sm_code","*");
            if($smInfo['sm_class_code']=='CRP'){
                if($orderInfo['ref_tracking_number']!=''){
                    $orderInfo['ship']['tracking_number'] = $orderInfo['ref_tracking_number'];
                }
            }
            $o['orderInfo'] = $orderInfo;
            $o['smInfo'] = $smInfo;
            $orderList[] = $o;
            //$this->view->orderInfo = $orderInfo;
            //$this->view->smInfo = $smInfo;

        }
        $this->view->orderList = $orderList;
        echo $this->view->render("merchant/views/order/print-label.tpl");
    }

    public function barcode39Action(){
        error_reporting(E_ALL);
        $barcode = $this->_request->getParam("code","");
        $height = $this->_request->getParam('height', 50);
        $width = $this->_request->getParam('width', 200);
        $quality = $this->_request->getParam('quality', 2);
        $format = $this->_request->getParam('format', NULL);
        $text = $this->_request->getParam('text', NULL);
        //$barcode, $width, $height, $quality, $format, $text
        $obj = new Service_Barcode();
        $obj->Barcode39($barcode, $width, $height, $quality, $format, $text);
        exit;
    }

    public function barcode128Action(){
        $orderCode = $this->_request->getParam("code","");
        $BarThinWidth = $this->_request->getParam("BarThinWidth","");
        $usps   =   new Service_UspsInterface();
        $config = new Zend_Config(array(
            'barcode'=>'code128',
            'barcodeParams' =>array('text'=>$orderCode,'BarThinWidth'=>2),
            'renderer'=>'image',
            'rendererParams'=>array('imageType'=>'gif'),
        ));
        $renderer = Zend_Barcode::factory($config);
        return $renderer->render();
        /*try {
            $usps->buildLabelBarcode($orderCode);
        } catch (Exception $exc) {
            echo $exc->getMessage();
        }*/
    }

    public function aliNotifyAction(){
        require_once APPLICATION_PATH . '/../libs/Alipay/alipay.config.php';
        require_once APPLICATION_PATH . '/../libs/Alipay/lib/alipay_notify.class.php';

        $alipayNotify = new AlipayNotify($alipay_config);
        $verify_result = $alipayNotify->verifyNotify();

        if($verify_result) {//验证成功
            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //请在这里加上商户的业务逻辑程序代
            //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
            //获取支付宝的通知返回参数，可参考技术文档中服务器异步通知参数列表

            //商户订单号
            $out_trade_no = $_POST['out_trade_no'];

            //支付宝交易号
            $trade_no = $_POST['trade_no'];

            //交易状态
            $trade_status = $_POST['trade_status'];


            if($_POST['trade_status'] == 'TRADE_FINISHED'||$_POST['trade_status'] == 'TRADE_SUCCESS') {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知

                //调试用，写文本函数记录程序运行情况是否正常
                //logResult("这里写入想要调试的代码变量值，或其他运行的结果记录");

                $chargeRow = Service_Charge::getByField($out_trade_no,'charge_code',"*");
                if($chargeRow['charge_status']=="1"){
                    echo "支付完成并支付成功,支付宝订单号是".$trade_no."充值订单号是".$out_trade_no.",充值金额是".$chargeRow['amount'].",充值标题是".$chargeRow['charge_body'];
                }else{
                    $db = Service_Customer::getModelInstance()->getAdapter();
                    $db->beginTransaction();
                    try{
                        $updateChargeRow = array(
                            'charge_status'=>'1',
                            'to_time'=>date("Y-m-d H:i:s"),
                            'trade_no'=>$trade_no
                        );
                        Service_Charge::update($updateChargeRow,$chargeRow['charge_id'],'charge_id');
                        $customerBalance = Service_CustomerBalance::getByField($chargeRow['customer_id'],'customer_id',"*");
                        if(empty($customerBalance)){
                            $customerBalance = array(
                                'customer_code'=>$chargeRow['customer_code'],
                                'customer_id'=>$chargeRow['customer_id'],
                                'cb_value'=>$chargeRow['amount'],
                                'cb_hold_value'=>0,
                                'cb_update_time'=>date("Y-m-d H:i:s"),
                                'frozen_tax_amount'=>0,
                            );
                            Service_CustomerBalance::add($customerBalance);
                        }else{
                            $customerBalance = Service_CustomerBalance::getForUpdate($customerBalance['cb_id']);
                            $updateCusteomerBalance = array(
                                'cb_value'=>$customerBalance['cb_value']+$chargeRow['amount'],
                                'cb_update_time'=>date("Y-m-d H:i:s"),
                            );
                            Service_CustomerBalance::update($updateCusteomerBalance,$customerBalance['cb_id'],'cb_id');
                        }
                        $logArr = array(
                            'customer_code'=>$chargeRow['customer_code'],
                            'customer_id'=>$chargeRow['customer_id'],
                            'cbl_type'=>'3',
                            'cbl_transaction_value'=>$chargeRow['amount'],
                            'cbl_value'=>$chargeRow['amount'],
                            'currency_rate'=>'1',
                            'currency_code'=>'RMB',
                            'cbl_note'=>'通过支付宝充值'.$chargeRow['amount']."RMB",
                            'cbl_current_value'=>$customerBalance['cb_value'],
                            'cbl_current_hold_value'=>$customerBalance['cb_hold_value'],
                            'application_code'=>'',
                            'cbl_refer_code'=>$out_trade_no,
                            'cbl_add_time'=>date("Y-m-d H:i:s"),
                            'transaction_number'=>$trade_no,
                            'arrive_time'=>date("Y-m-d H:i:s"),
                            'un_cbl_id'=>'0',
                            'cbl_refer_type'=>'0',
                            'cbl_cus_code'=>'',
                        );
                        Service_CustomerBalanceLog::add($logArr);
                        $db->commit();
                        echo "支付完成并支付成功,支付宝订单号是".$trade_no."充值订单号是".$out_trade_no.",充值金额是".$chargeRow['amount'].",充值标题是".$chargeRow['charge_body'];
                    }catch (Exception $e){
                        $db->rollBack();
                        echo "充值失败:".$e->getMessage()."请联系客服！";
                    }

                }

            }
        }else {
            //验证失败
            echo "充值失败："."trade_status=".$_GET['trade_status'];

            //调试用，写文本函数记录程序运行情况是否正常
            //logResult("这里写入想要调试的代码变量值，或其他运行的结果记录");
        }

    }

    public function aliReturnAction(){
        require_once APPLICATION_PATH . '/../libs/Alipay/alipay.config.php';
        require_once APPLICATION_PATH . '/../libs/Alipay/lib/alipay_notify.class.php';
        $alipayNotify = new AlipayNotify($alipay_config);
        $verify_result = $alipayNotify->verifyReturn();
        if($verify_result) {//验证成功
            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //请在这里加上商户的业务逻辑程序代码

            //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
            //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表

            //商户订单号

            $out_trade_no = $_GET['out_trade_no'];

            //支付宝交易号

            $trade_no = $_GET['trade_no'];

            //交易状态
            $trade_status = $_GET['trade_status'];


            if($_GET['trade_status'] == 'TRADE_FINISHED' || $_GET['trade_status'] == 'TRADE_SUCCESS') {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序
                $chargeRow = Service_Charge::getByField($out_trade_no,'charge_code',"*");
                if($chargeRow['charge_status']=="1"){
                    echo "success";
                }else{
                    $db = Service_Customer::getModelInstance()->getAdapter();
                    $db->beginTransaction();
                    try{
                        $updateChargeRow = array(
                            'charge_status'=>'1',
                            'to_time'=>date("Y-m-d H:i:s"),
                            'trade_no'=>$trade_no
                        );
                        Service_Charge::update($updateChargeRow,$chargeRow['charge_id'],'charge_id');
                        $customerBalance = Service_CustomerBalance::getByField($chargeRow['customer_id'],'customer_id',"*");
                        if(empty($customerBalance)){
                            $customerBalance = array(
                                'customer_code'=>$chargeRow['customer_code'],
                                'customer_id'=>$chargeRow['customer_id'],
                                'cb_value'=>$chargeRow['amount'],
                                'cb_hold_value'=>0,
                                'cb_update_time'=>date("Y-m-d H:i:s"),
                                'frozen_tax_amount'=>0,
                            );
                            Service_CustomerBalance::add($customerBalance);
                        }else{
                            $customerBalance = Service_CustomerBalance::getForUpdate($customerBalance['cb_id']);
                            $updateCusteomerBalance = array(
                                'cb_value'=>$customerBalance['cb_value']+$chargeRow['amount'],
                                'cb_update_time'=>date("Y-m-d H:i:s"),
                            );
                            Service_CustomerBalance::update($updateCusteomerBalance,$customerBalance['cb_id'],'cb_id');
                        }
                        $logArr = array(
                            'customer_code'=>$chargeRow['customer_code'],
                            'customer_id'=>$chargeRow['customer_id'],
                            'cbl_type'=>'3',
                            'cbl_transaction_value'=>$chargeRow['amount'],
                            'cbl_value'=>$chargeRow['amount'],
                            'currency_rate'=>'1',
                            'currency_code'=>'RMB',
                            'cbl_note'=>'通过支付宝充值'.$chargeRow['amount']."RMB",
                            'cbl_current_value'=>$customerBalance['cb_value'],
                            'cbl_current_hold_value'=>$customerBalance['cb_hold_value'],
                            'application_code'=>'',
                            'cbl_refer_code'=>$chargeRow['customer_code'],
                            'cbl_add_time'=>date("Y-m-d H:i:s"),
                            'transaction_number'=>$trade_no,
                            'arrive_time'=>date("Y-m-d H:i:s"),
                            'un_cbl_id'=>'0',
                            'cbl_refer_type'=>'0',
                            'cbl_cus_code'=>'',
                        );
                        Service_CustomerBalanceLog::add($logArr);
                        $db->commit();
                        //echo "success";
                        echo "支付完成并支付成功,支付宝订单号是".$trade_no."充值订单号是".$out_trade_no.",充值金额是".$chargeRow['amount'].",充值标题是".$chargeRow['charge_body'];
                    }catch (Exception $e){
                        $db->rollBack();
                        echo "充值失败:".$e->getMessage()."请联系客服！";
                    }

                }
            }
            else {
                echo "充值失败："."trade_status=".$_GET['trade_status'];
            }
        }
        else {
            //验证失败
            //如要调试，请看alipay_notify.php页面的verifyReturn函数
            echo "验证失败";
        }
    }
    public function cityAction() {
        $response = array();
        $country_id = $this->_request->getParam('country_id');
        if(!is_numeric($country_id)) exit(json_encode($response));
        $term = $this->_request->getParam('term');
        $condition = array('country_id'=>$country_id, 'city_name_like'=>$term);
        $list = Service_City::getByCondition($condition, 'city_name', 10);
        $is_exist = empty($list) && Service_City::getByWhere(array('country_id' => $country_id));
        if(empty($list) && empty($is_exist)){
            $condition = array('country_id'=>$country_id, 'city_name_like'=>$term);
            $list = Service_City::getByCondition($condition, 'city_name', 10);
        }
        foreach($list as $row){
            $response[] = $row['city_name'];
        }
        exit(json_encode($response));
    }


    public function postcodeAction() {
        $response = array();
        $country_id = trim($this->_request->getParam('country_id'));
        if(!is_numeric($country_id)) exit(json_encode($response));
        $city = trim($this->_request->getParam('city'));
        if(empty($city)) exit(json_encode($response));
        $aCity = Service_City::getByWhere(array('country_id'=>$country_id, 'city_name'=>$city), 'city_id');
        $term = $this->_request->getParam('term');
        // $sm_code = trim($this->_request->getParam('sm_code'));
        $cityInfo = Service_City::getByWhere(array('country_id' => $country_id, 'city_name'=>$city));
        if(!empty($cityInfo)) {
            unset($aCity);
            $aCity['city_id'] = $cityInfo['city_id'];
        }
        if(empty($aCity)) exit(json_encode($response));
        $condition = array('city_id'=>$aCity['city_id'], 'postcode_no_like'=>$term);

        $list = Service_Postcode::getByCondition($condition, '*', 10);
        $aPostcode = array();
        foreach($list as $row){
            if($row['postcode_no_end']==''){
                if(!in_array($row['postcode_no'],$aPostcode)){
                    $aPostcode[] = $row['postcode_no'];
                }
            }elseif($row['postcode_no_end']==$row['postcode_no']){
                if(!in_array($row['postcode_no'],$aPostcode)){
                    $aPostcode[] = $row['postcode_no'];
                }
            }else{
                if($row['postcode_no_end']!=$row['postcode_no']){
                    $length = strlen($row['postcode_no']);
                    for($postcode=$row['postcode_no'];$postcode<=$row['postcode_no_end'];$postcode++){
                        if(count($aPostcode)==10){
                            exit(json_encode($aPostcode));
                        }
                        if(!in_array($postcode,$aPostcode)){
                            $postcode = str_pad($postcode, $length, "0", STR_PAD_LEFT);
                            $aPostcode[] = strval($postcode);
                        }
                    }
                }
            }
        }
        exit(json_encode($aPostcode));
    }

}
