<?php
class Service_CustomerProcess
{
    public static $HuanQiu = 'E0843';//环球的客户代码
    public static $formType = array( 'I211' => '分送集报' );
    //public static $formType = array( 'I211' => '分送集报', 'IJ2' => '入区即退税');
    protected $_error = array();
    protected $_customer;
	/**
	 * 生成料件号
	 * @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);
	}

    public static function getDefaultSignCompany() {
        return array(1=>'招海签约',2=>'香港签约');
    }
	
	/**
	 * @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[] = '该邮箱已经被注册';
			}
		}
		
		if(strlen($row['customer_password'])<6){
			$error[] = '密码必须6位以上(包含6位)';
		}
		
		if($row['customer_password']!=$row['re_password']){
			$error[] = '密码必须相同';
		}
		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();
			$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),
					'reg_step'				=> 1,
					'customer_reg_time'		=> $time
			);
			$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(!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'];
			$base	= array(
					'customer_company_name'		=> $parms['companyname'],
					'trade_name'	=> $parms['trade_name'],
					'trade_co'	=> $parms['trade_co'],
					'customer_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'			=> '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'];
    }

    public function edit( $operation, $data ) {
        switch( $operation ) {
            case 'audit':
                $this->auditCustomer( $data );
                break;
            case 'edit':
                $this->editCustomer( $data );
                break;
        }
        return $this->getReturn();
    }

    protected function getReturn() {
        $result = array('state' => 0, 'message' => '操作失败', 'errorMessage' => array());
        if( !empty( $this->_error ) ) {
            $result['errorMessage'] = $this->_error;
        } else {
            $result['state'] = 1;
            $result['message'] = '操作成功';
        }
        return $result;
    }
    /*@todo:审核用户
     *
     */
    public function auditCustomer( $data ) {
        $result = array('state' => 0, 'message' => '审核失败', 'errorMessage' => array());
        $this->checkAuditData( $data );
        if( $this->_error ) {
            $result['errorMessage'] = $this->_error;
            return $result;
        }
        $adapter = Common_Common::getAdapter();
        $adapter->beginTransaction();
        try{
            $this->updateAudit( $data );
            $this->updateSignCompany( $this->_customer['customer_code'], $data['sign_company'] );
            $result['state'] = 1;
            $result['message'] = '审核成功';
            $adapter->commit();
        } catch( Exception $e ) {
            $this->_error[] = $e->getMessage();
            $result['errorMessage'][] = $e->getMessage();
            $adapter->rollBack();
        }
        return $result;
    }

    protected function checkAuditData( $data ) {
        if( !isset( $data['customer_id'] ) || $data['customer_id'] === '' ) {
            $this->_error[]= '请输入客户ID';
        } else {
            $obj = new Service_Customer();
            $customer = $obj::getByField( $data['customer_id'] );
            if( empty( $customer ) ) {
                $this->_error[]='客户不存在';
            } else {
                if( $customer['customer_status'] != 1 ){
                    $this->_error[]='客户不是待审核状态';
                }
                $this->_customer = $customer;
            }
        }
        if( !isset( $data['customer_cser_user_id'] ) || $data['customer_cser_user_id'] === '' ) {
            $this->_error[]= '请选择客服代表';
        }
        if( !isset( $data['customer_saler_user_id'] ) || $data['customer_saler_user_id'] === '' ) {
            $this->_error[]= '请选择销售代表';
        }
        if( !isset( $data['sign_company'] ) || $data['sign_company'] === '' ) {
            $this->_error[]= '请选择签约主体';
        } else if( !in_array( $data['sign_company'], array( 1, 2 ) ) ) {
            $this->_error[]= '签约主不正确';
        }
        if( !isset( $data['cash_type'] ) || $data['cash_type'] === '' ) {
            $this->_error[]= '请选择结算方式';
        } else if( !in_array( $data['cash_type'], array( 1, 2 ) ) ) {
            $this->_error[]= '结算方式只有预付和月结';
        }
        if( !isset( $data['customer_short'] ) || $data['customer_short'] === '' ) {
            $this->_error[]= '料件号规则必须填写';
        } else  {
            $customer_short = $data['customer_short'];
            $check = true;
            if( strlen( $customer_short )==4){
                if(preg_match_all('/^([A-Z]{4})$/',$customer_short,$match)){
                    if(strtoupper($customer_short)!=$customer_short){
                        $check = false;
                    }
                    /*$searchShort = Service_Customer::getByField($customer_short,'customer_short');
                    if(!empty($searchShort)){
                        $shortcheck = false;
                    }*/
                    /* foreach (count_chars($customer_short, 1) as $i => $val) {
                        if($val>1){
                            $shortcheck = false;
                        }
                    } */
                }else{
                    $check = false;
                }
            }else{
                $check = false;
            }
            if(!$check){
                $this->_error[] = '料件号规则必须是大写的字母，长度为4位，并且3位字母不可以有重复';
            }
        }
        if( !isset( $data['cus_code'] ) || $data['cus_code'] === '' ) {
            $this->_error[]= '仓库使用企业编码必须填写';
        }
        if( !isset( $data['cus_name'] ) || $data['cus_name'] === '' ) {
            $this->_error[]= '仓库使用企业名称必须填写';
        }

        $formType = @$data['form_type'];
        if( $this->_customer ) {
            $formTypes = Service_CustomerProcess::$formType;
            $isHuanQiu = Service_CustomerProcess::$HuanQiu == Service_CustomerProcess::getOwner(  $this->_customer['customer_code'] );
            //环球的客户只能选月结
            if( $isHuanQiu ) {
                if( @$data['cash_type'] != 2 ) {
                    $this->_error[]='环球的客户结算方式只能选月结';
                }
                if( $formType ) {
                    if( !isset( $formTypes[ $formType ] ) ) {
                        $this->_error[] = '业务类型不正确';
                    }
                } else {
                    $this->_error[] = $aCustomer['customer_code'].'是环球的客户，必须要选业务类型，注意：请勿乱选，业务类型会影响客户结汇，不知道就去找业务人员。';
                }
            } else {
                if(  $this->_customer['customer_platform'] == 'OMS' && @$data['cash_type'] != 1 ) {
                    $this->_error[]='OMS的客户结算方式只能选预付';
                } else if(  $this->_customer['customer_platform'] == 'FX' && @$data['cash_type'] != 2 ) {
                    $this->_error[]='分销的客户结算方式只能选月结';
                }
                if( $formType && !isset( $formTypes[ $formType ] ) ) {
                    $this->_error[] = '业务类型不正确';
                }
            }
        }
        $allowedPlatform = self::getPlatform();
        if( !isset( $data['platform'] ) || $data['platform'] === '' ) {
            $this->_error[] = '请选择客户平台';
        } else if( !isset( $allowedPlatform[ $data['platform'] ] ) ) {
            $this->_error[] = '客户平台不存在';
        }
    }
    /*@todo 更新审核信息
     *
     */
    protected function updateAudit( $data ) {
        $update['customer_cser_user_id'] = $data['customer_cser_user_id'];
        $update['customer_saler_user_id'] = $data['customer_saler_user_id'];
        $update['cash_type'] = $data['cash_type'];
        $update['customer_status'] = 2;
        $update['customer_short'] = strtoupper( $data['customer_short'] );
        $update['cus_code'] = $data['cus_code'];
        $update['cus_name'] = $data['cus_name'];
        $update['form_type'] = $data['form_type'];
        $update['customer_update_time'] = date('Y-m-d H:i:s');
        $update['customer_platform'] = $data['platform'];
        $uResult = Service_Customer::update( $update, $this->_customer['customer_id'], 'customer_id' );
        if( !$uResult )
            throw new Exception( '审核失败' );
    }
    /* @todo 更新签约主体
     * @param string $customerCode 用户信息
     * @param string $value   值
     */
    public static function updateSignCompany( $customerCode, $value ) {
        $extraCol = Service_CustomerExtraCol::getByField( 'sign_company', 'cec_col_name' );
        if( empty( $extraCol ) )
            throw new Exception( '客户没有【签约主体】这个属性' );

        $extraValue = Service_CustomerExtraColVal::getByCondition( array( 'customer_code' => $customerCode, 'cec_id' => $extraCol['cec_id'] ) );
        if( $extraValue ) {
            $update = array();
            if( $value != $extraValue[0]['cecv_value'] ) {
                $update['cecv_value'] = $value;
            }
            if( $update ) {
                $result = Service_CustomerExtraColVal::update( $update, $extraValue[0]['cecv_id'], 'cecv_id' );
                if( !$result )
                    throw new Exception('更新签约主体失败');
            }
        } else {
            $customer = Service_Customer::getByField( $customerCode, 'customer_code');
            if( empty( $customer ) )
                throw new Exception('用户['.$customerCode.']不存在');
            $add = array(
                'customer_id' => $customer['customer_id'],
                'customer_code' => $customer['customer_code'],
                'cec_id' => $extraCol['cec_id'],
                'cecv_value' => $value
            );
            $result = Service_CustomerExtraColVal::add( $add );
            if( !$result )
                throw new Exception('更新签约主体失败');
        }
    }
    /*@todo 获取用户的签约主体
     *
     */
    public static function getSignCompany( $customerCode ) {
        $signCompany = '';
        $extraCol = Service_CustomerExtraCol::getByField( 'sign_company', 'cec_col_name' );
        if( $extraCol ) {
            $extraValue = Service_CustomerExtraColVal::getByCondition( array( 'customer_code' => $customerCode, 'cec_id' => $extraCol['cec_id'] ) );
            if( $extraValue ) {
                $signCompany = $extraValue[0]['cecv_value'];
            } else {
                $customer = Service_Customer::getByField( $customerCode, 'customer_code');
                if( $customer ) {
                    $add = array(
                        'customer_id' => $customer['customer_id'],
                        'customer_code' => $customer['customer_code'],
                        'cec_id' => $extraCol['cec_id']
                    );
                    Service_CustomerExtraColVal::add( $add );
                }
            }
        }
        return $signCompany;
    }

    /* @todo 获取税金税率
     *
     */
    public static function getTaxRate( $customerCode ) {
        $signCompany = self::getSignCompany( $customerCode );
        return $signCompany == 1 ? 0.06 : ( $signCompany == '' ? false : 0 );
    }
    /* @todo:获取税金的计算常量
     *
     */
    public static function getConstant() {
        $constant = 1.06;
        return $constant;
    }

    /*@todo 编辑客户
     *
     */
    public function editCustomer( $data) {
        $result = array('state' => 0, 'message' => '审核失败', 'errorMessage' => array());
        Common_Common::trim_blank( $data );
        $this->checkEditData( $data );
        if( $this->_error ) {
            $result['errorMessage'] = $this->_error;
            return $result;
        }
        $adapter = Common_Common::getAdapter();
        $adapter->beginTransaction();
        try{
            $updateFile = $this->updateImage( @$data['files'] );
            if($updateFile)
                $data = array_merge( $data, $updateFile );

            self::updateSignCompany( $this->_customer['customer_code'], $data['sign_company'] );
            $this->updateCustomer( $data );

            $result['state'] = 1;
            $result['message'] = '审核成功';
            $adapter->commit();
        } catch( Exception $e ) {
            $this->_error[] = $e->getMessage();
            $result['errorMessage'][] = $e->getMessage();
            $adapter->rollBack();
        }
        return $result;
    }

    protected function checkEditData( $data ) {
        if( !isset( $data['customer_id'] ) || $data['customer_id'] === '' ) {
            $this->_error[] = '缺少客户ID';
        } else {
            $customerRow = Service_Customer::getByField( $data['customer_id'], "customer_id", "*");
            if( !$customerRow ) {
                $this->_error[] = '客户不存在';
            }
            $this->_customer = $customerRow;
        }
        if( !isset( $data['customer_firstname'] ) || $data['customer_firstname'] === '' ) {
            $this->_error[] = '姓氏必填';
        }
        if( !isset( $data['customer_lastname'] ) || $data['customer_lastname'] === '' ) {
            $this->_error[] = '名字必填';
        }
        if( !isset( $data['customer_telephone'] ) || $data['customer_telephone'] === '' ) {
            $this->_error[] = '电话必填';
        }
        if( !isset( $data['customer_company_name'] ) || $data['customer_company_name'] === '' ) {
            $this->_error[] = '公司名称必填';
        }
        if( !isset( $data['customer_country'] ) || $data['customer_country'] === '' ) {
            $this->_error[] = '国家必填';
        }
        if( !isset( $data['customer_province'] ) || $data['customer_province'] === '' ) {
            $this->_error[] = '省份必填';
        }
        if( !isset( $data['customer_city'] ) || $data['customer_city'] === '' ) {
            $this->_error[] = '城市必填';
        }
        if( !isset( $data['customer_postno'] ) || $data['customer_postno'] === '' ) {
            $this->_error[] = '邮编必填';
        }
        if( !isset( $data['customer_address'] ) || $data['customer_address'] === '' ) {
            $this->_error[] = '地址必填';
        }
        if( !isset( $data['sign_company'] ) || $data['sign_company'] === '' ) {
            $this->_error[]= '请选择签约主体';
        } else if( !in_array( $data['sign_company'], array( 1, 2 ) ) ) {
            $this->_error[]= '签约主体不正确';
        }
        if( $this->_customer ) {
            if( ( !isset( $data['customer_company_name'] ) || $data['customer_company_name'] === '') && $this->_customer['customer_type'] == 0 ){
                $this->_error[] = '销售电商平台必填';
            }
            if( ( !isset( $data['trade_co'] ) || $data['trade_co'] === '') && $this->_customer['customer_type'] == 0 ){
                $this->_error[] = '经营单位编码必填';
            }
            //原来是空时，才去更新，已经有业务类型的暂时限制不更新
            if( !$this->_customer['form_type'] && isset( $data['form_type'] ) && $data['form_type'] ) {
                $formTypes = Service_CustomerProcess::$formType;
                if( !isset( $formTypes[ $data['form_type'] ] ) ) {
                    $formType = '';
                    $this->_error[] = '业务类型不存在';
                }
            } else {
                $formType = '';
            }
            if( $formType ) {
                if( Service_CustomerProcess::$HuanQiu != Service_CustomerProcess::getOwner( $this->_customer['customer_code'] ) ) {
                    $this->_error[] = '非环球客户暂时不能设置业务类型，请勿选择.';
                }
            }
        }
    }

    protected function updateCustomer( $data ){
        $update = array(
            'customer_firstname'                => $data['customer_firstname'],
            'customer_lastname'                 => $data['customer_lastname'],
            'customer_country'                  => $data['customer_country'],
            'customer_province'                 => $data['customer_province'],
            'customer_provision'                => isset( $data['customer_provision'] ) ? $data['customer_provision'] : '',
            'customer_city'                      => $data['customer_city'],
            'customer_address'                  => $data['customer_address'],
            'customer_telephone'                => $data['customer_telephone'],
            'customer_fax'                       => isset( $data['customer_fax'] ) ? $data['customer_fax'] : '',
            'customer_signature'                => isset( $data['customer_signature'] ) ? $data['customer_signature'] : '',
            'customer_postno'                    => $data['customer_postno'],
            'trade_co'                            => isset( $data['trade_co'] ) ? $data['trade_co'] : '',
            'trade_name'                          => isset( $data['trade_name'] ) ? $data['trade_name'] : '',
            'eshop_platform'                     => isset( $data['eshop_platform'] ) ? $data['eshop_platform'] : '',
            'eshop_name'                          => isset( $data['eshop_name'] ) ? $data['eshop_name'] : '',
            'customer_company_name'             => isset( $data['customer_company_name'] ) ? $data['customer_company_name'] : '',
            'customer_update_time'              => date('Y-m-d H:i:s')

        );
        if( @$data['is_deleted_logo'] == '1' ){
            $update['customer_logo'] = '';
            $update['customer_logo_save_site'] = '';
        } else if( isset( $data['customer_logo'] ) && $data['customer_logo'] ) {
            $update['customer_logo'] = $data['customer_logo'];
            $update['customer_logo_save_site'] = $data['customer_logo_save_site'];
        }

        if( @$data['is_deleted_license'] == '1' ){
            $update['customer_license']	= '';
            $update['customer_license_save_site'] = '';
        } else if( isset( $data['customer_license'] ) && $data['customer_license'] ) {
            $update['customer_license'] = $data['customer_license'];
            $update['customer_license_save_site'] = $data['customer_license_save_site'];
        }

        if( @$data['is_deleted_idcard'] == '1' ){
            $update['customer_idcard']	= '';
            $update['customer_idcard_save_site'] = '';
        } else if( isset( $data['customer_idcard'] ) && $data['customer_idcard'] ) {
            $update['customer_idcard'] = $data['customer_idcard'];
            $update['customer_idcard_save_site'] = $data['customer_idcard_save_site'];
        }

        if( @$data['is_deleted_customlsn'] == '1' ){
            $update['customer_customlsn']	= '';
            $update['customer_customlsn_save_site'] = '';
        } else if( isset( $data['customer_customlsn'] ) && $data['customer_customlsn'] ) {
            $update['customer_customlsn'] = $data['customer_customlsn'];
            $update['customer_customlsn_save_site'] = $data['customer_customlsn_save_site'];
        }

        if( isset( $data['form_type'] ) && $data['form_type'] ) {
            $update['form_type'] = $data['form_type'];
        }

        $result = Service_Customer::update( $update, $this->_customer['customer_id'], 'customer_id' );
        if( !$result )
            throw new Exception('更新用户信息失败');
    }
    /* @todo 更新照片
     *
     */
    protected function updateImage( $file ) {

        $customer = array();
        if( empty( $file ) )
            return $customer;

        $path = APPLICATION_PATH.'/../data/images/register/'.$this->_customer['customer_code'];

        Common_Common::createPath($path);

        if( $file['customer_license']['size'] ){
            $state	= Common_Common::uploadImg( $file, 'customer_license', $path);
            if ($state['error']) {
                $msg	= strip_tags($state['msg']);
                throw new Exception( $msg );
            }
            $customer['customer_license']	= $state['msg']['file_name'];
            $customer['customer_license_save_site'] = WMS_URL;

        }
        if($file['customer_idcard']['size']){
            $state	= Common_Common::uploadImg($file, 'customer_idcard', $path);
            if ($state['error']) {
                $msg	= strip_tags($state['msg']);
                throw new Exception( $msg );
            }
            $customer['customer_idcard']	= $state['msg']['file_name'];
            $customer['customer_idcard_save_site'] = WMS_URL;
        }


        if($file['customer_customlsn']['size']){
            $state	= Common_Common::uploadImg($file, 'customer_customlsn', $path);
            if ($state['error']) {
                $msg	= strip_tags($state['msg']);
                throw new Exception( $msg );
            }
            $customer['customer_customlsn']	= $state['msg']['file_name'];
            $customer['customer_customlsn_save_site'] = WMS_URL;

        }

        if($file['customer_logo']['size']){
            $state	= Common_Common::uploadImg($file, 'customer_logo', $path);
            if ($state['error']) {
                $msg	= strip_tags($state['msg']);
                throw new Exception( $msg );
            }
            $customer['customer_logo']	= $state['msg']['file_name'];
            $customer['customer_logo_save_site'] = WMS_URL;

        }
        return $customer;
    }

    public static function getPlatform() {
        return array(
            'OMS' => 'OMS',
            'GS' => '环球资源',
            'FX' => '分销',
            'LT' => 'light trade'
        );
    }
}