<?php
class Merchant_CustomerController extends Ec_Controller_Action{
	public function preDispatch()
	{
		$this->tplDirectory = "merchant/views/customer/";
		$params = self::getFrontController()->getRequest()->getParams();
		$this->view->ac = $params['action'];
	}
	public function showAction(){		
		echo Ec::renderTpl($this->tplDirectory . "showedit.tpl",'noleftlayout');
		//echo $this->view->render($this->tplDirectory . "showedit.tpl");
	}
	
	public function baseinfoAction(){
		
		$user	= $this->_customerAuth;
		//print_r($user);
		
		$userInfo = Service_Customer::getByField($user['id']);
		if($userInfo['customer_logo']!='' && @file_get_contents($userInfo['customer_logo'])!==false){
			$userInfo['customer_logo_url'] = $userInfo['customer_logo'];
		}
		
		$this->view->currency	= Common_DataCache::getCurrency();
		$this->view->country	= Common_DataCache::getCountry();
		$this->view->userInfo	= $userInfo;
		$customerAddressInfo = Service_CustomerAddressBook::getByField($userInfo['customer_code'],'customer_code');
		$this->view->customerAddress = $customerAddressInfo;
		echo Ec::renderTpl($this->tplDirectory . "baseinfo.tpl",'noleftlayout');
		//echo $this->view->render($this->tplDirectory . "edit.tpl"); 
	}
	/*联系人信息编辑*/
	public function editAction(){
		
		$user	= $this->_customerAuth;
		//print_r($user);
		if($this->_request->isPost()){			
			$cab_firstname			= $this->_request->getParam('cab_firstname','');
			$cab_lastname			= $this->_request->getParam('cab_lastname','');
			$cab_phone				= $this->_request->getParam('cab_phone','');
			$cab_fax				= $this->_request->getParam('cab_fax','');
			$cab_country			= $this->_request->getParam('country','');
			$cab_state				= $this->_request->getParam('cab_state','');
			$cab_city				= $this->_request->getParam('cab_city','');
			$postcode				= $this->_request->getParam('postcode','');
			$cab_street_address1	= $this->_request->getParam('cab_street_address1','');
			$cab_id					= $this->_request->getParam('id');
			
			$logo					= $this->_request->getParam('logo','');
						
			$data['cab_firstname']		= $cab_firstname;
			$data['cab_id']				= $cab_id;
			$data['cab_lastname']		= $cab_lastname;
			$data['cab_country']		= $cab_country;			
			$data['cab_phone']			= $cab_phone;
			$data['cab_fax']			= $cab_fax;
			$data['cab_state']			= $cab_state;
			$data['cab_city']			= $cab_city;
			$data['postcode']			= $postcode;
			$data['cab_street_address1']= $cab_street_address1;

			$data['cab_id']				= $cab_id;
			$data['customer_id']		= $user['id'];
			
			$imgs	= array();
			$fields	= empty($_FILES) ? '' : array_keys($_FILES);
			//$path	= './upload/images';
			$path = APPLICATION_PATH.'/../data/images/register/'.$user['code'];
				
			$isDir	= Common_Common::createPath($path);
			if ($isDir && !empty($fields)) {
				foreach ($fields as $field) {
					$state	= Common_Common::uploadImg($_FILES, $field, $path);
					if ($state['error']) {
						$msg	= strip_tags($state['msg']);
						$imageresult['ask']='1';
						$imageresult['message']=$msg;
						die(Zend_Json_Encoder::encode($imageresult));
					}
					$imgs[$field]	= $state['msg']['file_name'];
				}
			}
			$data['customer_logo']		= empty($logo) ? '' : $logo;
			$data['customer_license']	= empty($imgs['license']) ? '' : $imgs['license'];
			$data['customer_idcard']	= empty($imgs['identity']) ? '' : $imgs['identity'];
			
			$result = Service_CustomerProcess::updateCustomerTransaction($data,$user['id']);			
			/*
			if($result['ask']=='1'){
				die("<script>document.write('{$result['message']}');setTimeout('window.history.back();', 2000);</script>");
			}else{
				die("<script>document.write('{$result['message']}');setTimeout('window.history.back();', 2000);</script>");
			}
			*/
			die(Zend_Json_Encoder::encode($result));
		}
		
		$userInfo = Service_Customer::getByField($user['id']);
		if($userInfo['customer_logo']!='' && @file_get_contents($userInfo['customer_logo'])!==false){
			$userInfo['customer_logo_url'] = $userInfo['customer_logo'];
		}
		
		$this->view->currency	= Common_DataCache::getCurrency();
		$this->view->country	= Common_DataCache::getCountry();
		$this->view->userInfo	= $userInfo;
		
		$customerAddressInfo = Service_CustomerAddressBook::getByField($userInfo['customer_code'],'customer_code');
		$this->view->customerAddress = $customerAddressInfo;
		echo Ec::renderTpl($this->tplDirectory . "edit.tpl",'noleftlayout');
		//echo $this->view->render($this->tplDirectory . "edit.tpl"); 
	}
	/**
	 * @author william-fan
	 * @todo 用于获取用户的图片信息
	 */
	public function imageAction(){
		$user	= $this->_customerAuth;
		$path = APPLICATION_PATH.'/../data/images/register/'.$user['code'];
		$userInfo = Service_Customer::getByField($user['id']);
		$imagetype = $this->_request->getParam('imagetype','');
		switch($imagetype){
			case 'license':
				header('Content-Type: image/jpeg');
				echo file_get_contents($path.'/'.$userInfo['customer_license']);
				break;
			case 'idcard':
				header('Content-Type: image/jpeg');
				echo file_get_contents($path.'/'.$userInfo['customer_idcard']);
				break;	
		}
	}
	/*密码修改*/
    public function changePasswordAction(){
        if($this->_request->isPost()){
            $customer_code = $this->_request->getParam("customer_code","");
            $new_password1 = $this->_request->getParam("new_password1","");
            $account_id = (int) $this->_request->getParam('account_id', 0);
            $pwd = md5($new_password1);

            // 先做修改拦截，$account_id为0则表示为主账号，否则为子账号
            if ($account_id) {
              $row = array(
                'account_password' => $pwd,
                'password_updated_time' => date('Y-m-d H:i:s')
              );
              $result = array(
                'ask' => 0,
                'message' => '密码修改失败'
              );

              if (Service_Account::update($row, $account_id)) { // 子账号密码修改成功
                $result = array(
                  'ask' => 1,
                  'message' => '密码修改成功'
                );
              }

              exit(Zend_Json::encode($result));
            } // 拦截不住，执行以下旧时代码

            $row = array(
                'customer_password'=>$pwd,
				'password_update_time'=>date('Y-m-d H:i:s',time()),
            );
            if(Service_Customer::update($row,$customer_code,'customer_code')){
                $result = array(
                    'ask'=>1,
                    'message'=>'密码修改成功'
                );
                die(json_encode($result));
                /*die("<script>document.write('密码修改成功');setTimeout('window.history.back();', 2000);</script>");
				*/
            }
        }else{
            $session	= new Zend_Session_Namespace('customerAuth');
            $data = $session->data;
            $this->view->customer_code = $data['code'];
            $this->view->account_id = $data['account_id']; // 子账号，0为主账号，其他为子账号ID
			echo Ec::renderTpl($this->tplDirectory . "change-password.tpl",'noleftlayout');
            //echo $this->view->render($this->tplDirectory . "change-password.tpl","layout");
        }
    }
    public function checkpwdAction(){
        $customer_code = $this->_request->getParam('customer_code','');
        $oldPassword = $this->_request->getParam('password','');
        $account_id = (int) $this->_request->getParam('account_id', 0);
        $current_password = '';

        if ($account_id) { // 子账号的信息应该从这里提取
          $account = Service_Account::getByCondition(array('account_id' => $account_id));
          $current_password = $account ? $account['account_password'] : '';
        }
        else {
          $customer = Service_Customer::getByField($customer_code,'customer_code',"*");
          $current_password = $customer ? $customer['customer_password'] : '';
        }
        /*$pw = md5($oldPassword);
        $row = array(
            'customer_password'=>$pw
        );
        Service_Customer::update($row,$customer_code,'customer_code');*/
        if(md5($oldPassword)==$current_password){
            die("1");
        }else{
            die("0");
        }
    }

    public function changeTokenAction(){
        $id = $this->_request->getParam('id',"");
        $customerRow = Service_Customer::getByField($id,'customer_id',"*");
        $ca_key = md5($customerRow['customer_code'].date("Y-m-d H:i:s"));
        $ca_token = strtoupper(substr(md5(substr($ca_key,0,16).$customerRow['customer_code']),0,16));
        $row = array(
            'ca_token'=>$ca_token,
            'ca_key'=>$ca_key,
            'ca_update_time'=>date("Y-m-d H:i:s")
        );
        if(Service_CustomerApi::update($row,$id,'customer_id')){
            $return['state'] = "1";
            $data = array(
                'token'=>$ca_token,
                'key'=>$ca_key
            );
            $return['data'] = $data;
        }else{
            $return['state'] = "0";
            $data = array(
                'token'=>'',
                'key'=>''
            );
            $return['data'] = $data;
        }
        die(json_encode($return));
    }
    public function requireTokenAction(){
        $id = $this->_request->getParam("id","");
        $customerRow = Service_Customer::getByField($id,'customer_id',"*");
        $ca_key = md5($customerRow['customer_code'].date("Y-m-d H:i:s"));
        $ca_token = strtoupper(substr(md5(substr($ca_key,0,16).$customerRow['customer_code']),0,16));
        $row = array(
            'customer_id'=>$id,
            'customer_code'=>$customerRow['customer_code'],
            'ca_status'=>'1',
            'ca_token'=>$ca_token,
            'ca_key'=>$ca_key,
            'ca_add_time'=>date("Y-m-d H:i:s"),
            'ca_update_time'=>date("Y-m-d H:i:s")
        );
        if(Service_CustomerApi::add($row)){
            $return['state'] = "1";
            $data = array(
                'token'=>$ca_token,
                'key'=>$ca_key
            );
            $return['data'] = $data;
        }else{
            $return['state'] = "0";
            $data = array(
                'token'=>'',
                'key'=>''
            );
            $return['data'] = $data;
        }
        die(json_encode($return));
    }
	
}