<?php
class Service_CustomerProcess
{
    static $HuanQiu = 'E0843';//环球的代码
	/**
	 * 生成料件号
	 * @author solar
	 * @param int $customer_id
	 * @return string
	 */
	public static function generateGoodsId($customer_id, $has_invoice=1) {
        $customer = Service_Customer::getByField($customer_id,'customer_id',"*");
        $aCustomer = Service_Customer::getCustomerByShortCode($customer['customer_short']);
		//$aCustomer = Service_Customer::getLockInShareMode($customer_id);
		$goods_serial = ++$aCustomer['goods_serial'];
		Service_Customer::update(array('goods_serial'=>$goods_serial), $customer['customer_short'],'customer_short');//有客户共用customer_short
        if(strlen($aCustomer['customer_short'])==3){
            $customer_short = $has_invoice==2 ? substr($aCustomer['customer_short'], 0, 2).'B' : $aCustomer['customer_short'];
        }else{
            $customer_short = $has_invoice==2 ? substr($aCustomer['customer_short'], 0, 3).'B' : $aCustomer['customer_short'];
        }
		return $customer_short.str_pad($goods_serial, 6, '0', STR_PAD_LEFT);
	}
	
	/**
	 * @author william-fan
	 * @todo 用于检测输入
	 */
	private function validator($row){
		$error = array();
		if($row['customer_email']==''){
			$error[] = '邮箱不能为空';
		}else if(!preg_match("/^([\.a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/",$row['customer_email'])){
		
			$error[] = '邮箱格式不对';
		}		
		else{
			//判断邮箱的重复性
			$checkEmail = Service_Customer::getByField($row['customer_email'], 'customer_email');
			if(!empty($checkEmail)){
				$error[] = '该邮箱已经被注册';
			}else{
                $checkEmail = Service_Account::getByField($row['customer_email'], 'account_email');
                if(!empty($checkEmail)){
                    $error[] = '该邮箱已经被注册';
                }
            }
		}
		
		if(strlen($row['customer_password'])<6){
			$error[] = '密码必须6位以上(包含6位)';
		}
		
		if($row['customer_password']!=$row['re_password']){
			$error[] = '密码必须相同';
		}
        if($row['check_verify']){
            if($row['verify']==''){
                $error[] = '验证码必填';
            } else {
                if (! $this->Verifycode ( $row ['verify'] )) {
                    $error [] = '验证码不对';

                }
            }
        }
		return $error;
	}
	/**
	 *
	 * @author william-fan
	 * @todo 用于检测验证码
	 */
	public function Verifycode($verifyCode) {
		$verify = new Common_Verifycode ();
		return $verify->is_true ( $verifyCode );
	}
	/**
	 * @author colin-yang
	 * @todo 用于检测输入
	 */
	private function completestepvalidator($row){
		
		$error = array();		
		if(!preg_match('/^\d{10,10}$/',$row['trade_co'])){
			$error[] = '经营单位编码必须为10位的数字';		
		}		
		return $error;
	}

	/**
	 *
	 * @author william-fan
	 * @todo 用于处理注册保存
	 */
	public function createTransaction($row) {
		$result = array("ask"=>0,"message"=>"注册失败",'error'=>array());
		/*
		$error=$this->completestepvalidator($parms);
		if(!empty($error)){						
			$result['error'] = $error;
			return $result;
		}
		*/		
		$db = Common_Common::getAdapter();
		$db->beginTransaction();
		try{
			$time	= date('Y-m-d H:i:s',time());
			$mark	= new Common_Customer();
            if($row['customer_type']=="1"){
                $customerCode	= $mark->markCustomCode('register',4,'S');
            }else{
                $customerCode	= $mark->markCustomCode('register');
            }
			
			//$customerCode = Common_GetNumbers::getCode('customer', '', 'E');
			
			/* var_dump($customerCode);
			echo 'sfff';
			exit; */
			$error=$this->validator($row);
			if(!empty($error)){
				if(in_array('验证码不对',$error)){
					$result['authcodeError'] = 1;
				}			
				$result['error'] = $error;

				return $result;
			}
			
			
			$customerRow = array(
					'customer_code'			=> $customerCode,
					'customer_password'		=> md5($row['customer_password']),
					'customer_email'		=> $row['customer_email'],
					'customer_activate_code'=> substr(md5($time),0,12),
                    'customer_type'=>$row['customer_type'],
					'reg_step'				=> 1,
					'customer_reg_time'		=> $time,
                    'customer_platform'=>isset($row['customer_platform'])?$row['customer_platform']:"OMS",
			);
            if($customerRow['customer_platform']=="FX"){
                $customerRow['cash_type'] = "2";
            }
			$customerId=Service_Customer::add($customerRow);

            //初始化余额
            $balanceRow['customer_code'] = $customerCode;
            $balanceRow['customer_id'] = $customerId;
            Service_CustomerBalance::add($balanceRow);

			if(!$customerId){
				throw new Exception("注册失败,写入数据库错误");
			}
			$activeurl = 'http://'.$_SERVER['HTTP_HOST'].'/register/activate?code='.substr(md5($time),0,12);

			$activeHtml = "<a href='$activeurl' target='_blank'>请点击此链接激活您的账户</a>";
			$params = array(
           		'bodyType' => 'html',
            	'email' => array($row['customer_email']),
            	'subject' => '[招海]账号激活通知',
            	'body' => "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;您注册的邮箱是：{$row['customer_email']},<br/>感谢您的注册，{$activeHtml}。<br/>或者复制以下链接到浏览器进行激活：{$activeurl}",
        	);
            if($row['check_verify']){
                if(!Common_Email::sendMail($params)){
                    throw new Exception("注册失败,发送邮件失败");
                }
            }
			//$db->rollback();
			$db->commit();
			$result['ask']='1';
			$result['message']='注册成功,请到邮箱里面查看邮件进行激活';
			$result['customer_code'] = $customerCode;
			$result['customer_id'] = $customerId;
			return $result;
		}catch(Exception $e){
	       $db->rollback();
	       $result = array("ask"=>0,"message"=>$e->getMessage(),'errorCode'=>$e->getCode());
	   }
	    return $result;	 
	}
	/**
	 * @author william-fan
	 * @todo 完成注册
	 */
	public function completeTransaction($parms,$imgs){
		
		$session	= new Zend_Session_Namespace('register');
					
		$result = array("ask"=>0,"message"=>"资料完善失败",'error'=>array());
		$db = Common_Common::getAdapter();
		$db->beginTransaction();
		try{	
			$id		= $session->data['id'];
			$code	= $session->data['code'];
			$email	= $session->data['email'];
            $customerRow = Service_Customer::getByField($id,'customer_id',"*");
			$base	= array(
					'customer_company_name'		=> $parms['companyname'],
					'trade_name'	=> isset($parms['trade_name'])?$parms['trade_name']:"",
					'trade_co'	=> isset($parms['trade_co'])?$parms['trade_co']:"",
					'customer_currency'			=> isset($parms['currency'])?$parms['currency']:"",
					'customer_license'			=> empty($imgs['license']) ? '' : $imgs['license'],					
					'customer_idcard'			=> empty($imgs['identity']) ? '' : $imgs['identity'],
					'customer_customlsn'			=> empty($imgs['customlsn']) ? '' : $imgs['customlsn'],
					'customer_logo'			=> empty($imgs['logo']) ? '' : $imgs['logo'],
					'customer_license_save_site'=>WEB_URL,
					'customer_idcard_save_site'=>WEB_URL,
					'customer_logo_save_site'=>WEB_URL,
					'customer_customlsn_save_site'=>WEB_URL,				
					'customer_firstname'		=> empty($parms['firstname']) ? '' : $parms['firstname'],
					'customer_lastname'			=> empty($parms['lastname']) ? '' : $parms['lastname'],
					'customer_telephone'		=> empty($parms['telphone']) ? '' : $parms['telphone'],
					'customer_fax'				=> empty($parms['fax']) ? '' : $parms['fax'],
					'customer_province'				=> empty($parms['province']) ? '' : $parms['province'],
					'customer_city'				=> empty($parms['city']) ? '' : $parms['city'],
					'customer_fax'				=> empty($parms['fax']) ? '' : $parms['fax'],
					'customer_postno'				=> empty($parms['postno']) ? '' : $parms['postno'],
					'customer_address'				=> empty($parms['address']) ? '' : $parms['address'],
					'customer_country'				=> empty($parms['country']) ? '' : $parms['country'],
					'customer_provision'				=> empty($parms['provision']) ? '' : $parms['provision'],
					'customer_signature'				=> empty($parms['signature']) ? '' : $parms['signature'],					
					'reg_step'					=> 3,
					'customer_status'			=>$customerRow['customer_type']=="1"?'2':'1',
					'customer_activate_code'	=> 0,
			);
			$book	= array(
					'customer_id'				=> $id,
					'customer_code'				=> $code,
					'cab_company'				=> $parms['companyname'],
					'cab_firstname'		=> empty($parms['firstname']) ? '' : $parms['firstname'],
					'cab_lastname'			=> empty($parms['lastname']) ? '' : $parms['lastname'],
					'cab_country_id'			=> $parms['country'],
					'cab_state'					=> empty($parms['state']) ? '' : $parms['state'],
					'cab_city'					=> empty($parms['city']) ? '' : $parms['city'],
					'cab_postcode'				=> empty($parms['postcode']) ? '' : $parms['postcode'],
					'cab_street_address1'		=> empty($parms['address']) ? '' : $parms['address']
			);
			$state	= Service_Customer::update($base, $id);
			if (!empty($state)) {
				$state	= Service_CustomerAddressBook::add($book);
			}
			
			
			if (empty($state)) {
				die("<script>alert('提交信息出错，请重新填写！');window.history.back();</script>");
			}{
				$session->data	= array(
						'id'		=> $id,
						'code'		=> $code,
						'email'		=> $email,
						'current'	=> 4
				);
				$db->commit();
				$result['ask']='1';
				$result['message']='完善资料成功';
				$result['customer_code'] = $code;
				$result['customer_id'] = $id;
				$result['email'] = $email;
				return $result;
			}
			return $result;
		}catch(Exception $e){
			$db->rollback();
			$result = array("ask"=>0,"message"=>$e->getMessage(),'errorCode'=>$e->getCode());
		}
		return $result;
	}
	
	/**
	 * @author william-fan
	 * @todo 用于更新客户信息
	 */
	public static function updateCustomerTransaction($data,$customerId){
		$result = array("ask"=>0,"message"=>"更改信息失败",'error'=>array());
		$db = Common_Common::getAdapter();
		$db->beginTransaction();
		try{
				$cab_id	= $data['cab_id'];
				$customerAddress = Service_CustomerAddressBook::getByField($cab_id);
				if(empty($customerAddress)){
					$result['message'] = '地址无效';
					return $result;
				}
				if($customerAddress['customer_id']!=$customerId){
					$result['message'] = '无权操作';
					$db->rollback();
					return $result;
				}
				$addressBook['cab_firstname']		= $data['cab_firstname'];
				$addressBook['cab_lastname']		= $data['cab_lastname'];
				$addressBook['cab_phone']			= $data['cab_phone'];
				$addressBook['cab_fax']				= $data['cab_fax'];
				$addressBook['cab_state']			= $data['cab_state'];
				$addressBook['cab_city']			= $data['cab_city'];
				$addressBook['cab_postcode']		= $data['postcode'];
				$addressBook['cab_street_address1']	= $data['cab_street_address1'];
				/* echo $cab_id;
				print_r($addressBook);
				exit; */
				Service_CustomerAddressBook::update($addressBook, $cab_id);
	

			
								
				
				$customerRow = array();
				if(isset($data['customer_logo']) && $data['customer_logo']!=''){
					$customerRow['customer_logo'] = $data['customer_logo'];
				}
				if(isset($data['customer_license']) && $data['customer_license']!=''){
					$customerRow['customer_license'] = $data['customer_license'];
				}
				if(isset($data['customer_idcard']) && $data['customer_idcard']!=''){
					$customerRow['customer_idcard'] = $data['customer_idcard'];
				}
				$customerRow['customer_firstname'] = $data['cab_firstname'];
				$customerRow['customer_lastname'] = $data['cab_lastname'];
				$customerRow['customer_telephone'] = $data['cab_phone'];				
				$customerRow['customer_country'] = $data['cab_country'];
				$customerRow['customer_fax'] = $data['cab_fax'];
				$customerRow['customer_province'] = $data['cab_state'];
				$customerRow['customer_city'] = $data['cab_city'];
				$customerRow['customer_postno'] = $data['postcode'];
				$customerRow['customer_address'] = $data['cab_street_address1'];				
				
				if(!empty($customerRow)){
				//print_r($customerRow);
					Service_Customer::update($customerRow, $data['customer_id']);
				}
				
				$db->commit();
				$result['ask']='1';
				$result['message']='更新资料成功';
				return $result;
			}catch(Exception $e){
				$db->rollback();
				$result = array("ask"=>0,"message"=>$e->getMessage(),'errorCode'=>$e->getCode());
			}
		return $result;
	}

    public static function getOwner( $customerCode ) {
        if( empty( $customerCode ) )
            return '';
        $row = Service_CustomerRegister::getByField( $customerCode, 'customer_code' );
        if( empty( $row ) )
            return '';
        else
            return $row['regis_customer_code'];
    }

	
}