<?php
/**
 * 客户接口
 */
class Service_CustomerApiProcess
{
	/**
	 * @todo 用于处理注册保存
	 */
	public function createTransaction($regRow, $regCustomerCode) {
		$result = array('ask' => 0, 'message' => '注册失败', 'error' => array());
		$db = Common_Common::getAdapter();
		$db->beginTransaction();
		try{
			$error = $this->validator($regRow);
			if(!empty($error) && is_array($error)){
				if(isset($error['customerCode'])){
					$result['customerCode'] = $error['customerCode'];
					$result['customerId'] = $error['customerId'];
					unset($error['customerCode']);
					unset($error['customerId']);
				}
				$result['error'] = $error;
				return $result;
			}
			//插入基础数据
			$baseData = $this->addBaseData($regRow, $regCustomerCode);
			//发送注册邮件
			//$this->sendEmail($regRow);
			//完善信息
			$this->completeCustomer($baseData, $regRow);
			//$db->rollback();
			$db->commit();
			$result['ask']='1';
			$result['message']='注册成功';
			$result['customerCode'] = $baseData['customerCode'];
			$result['customerId'] = $baseData['customerId'];
			return $result;
		}catch(Exception $e){
	       $db->rollback();
	       $result = array('ask' => 0, 'message' => $e->getMessage(), 'errorCode' => $e->getCode());
		}
		return $result;
	}

	/**
	 * [addBaseData 插入基础数据]
	 *
	 * @param [type] $regRow [description]
	 */
	private function addBaseData($regRow, $regCustomerCode){
		$time = date('Y-m-d H:i:s', time());
		$mark = new Common_Customer();
        if($regRow['customer_type']=="1"){
            $customerCode = $mark->markCustomCode('register',4,'S');
        }else{
            $customerCode = $mark->markCustomCode('register');
        }
        $countryRow = Service_Country::getByField($regRow['customer_country'], 'country_code', array('country_id'));
        $countryId = empty($countryRow) ? 0 : $countryRow['country_id'] ;
		$customerRow = array(
			'customer_code'				=> $customerCode,
			'customer_password'			=> md5($regRow['customer_password']),
			'customer_email'			=> $regRow['customer_email'],
			'customer_activate_code'	=> substr(md5($time),0,12),
            'customer_type'				=> $regRow['customer_type'],
            'customer_country'			=> $countryId,
			'reg_step'					=> 1,
			'customer_reg_time'			=> $time,
            'customer_platform'			=> isset($regRow['customer_platform']) ? $regRow['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;
        $balanceRes = Service_CustomerBalance::add($balanceRow);
        if(!$balanceRes){
        	throw new Exception("初始化余额失败", '6005');
        }
		if(!$customerId){
			throw new Exception("写入数据错误", '6001');
		}
		//填写客户代码-注册客户代码
		if(!empty($regCustomerCode)){
			$regCustomerRow = Service_Customer::getByField($regCustomerCode, 'customer_code');
			if(empty($regCustomerRow) || !is_array($regCustomerRow)){
				throw new Exception("注册客户代码不合法", '7002');
			}
			$regCustomerRow = array(
				'customer_code' => $customerCode,
				'regis_customer_code' => $regCustomerCode,
				'add_time' => $time,
			);
			$regCustomerRowRes = Service_CustomerRegister::add($regCustomerRow);
			if(!$regCustomerRowRes){
				throw new Exception("写入注册关系数据错误", '7001');
			}
            if( $regCustomerCode == Service_CustomerProcess::$HuanQiu ) {
                $uResult = Service_Customer::update( array('customer_platform'=>'GS'), $customerCode, 'customer_code');
                if( !$uResult )
                    throw new Exception("写入注册关系数据错误", '7003');
            }
		}
		$return = array(
			'customerCode' => $customerCode,
			'customerId' => $customerId,
			'email' => $regRow['customer_email']
		);
		return $return;
	}

	/**
	 * [sendEmail 发送注册邮件]
	 *
	 * @param  [type] $regRow [description]
	 *
	 * @return [type]         [description]
	 */
	private function sendEmail($regRow){
		$time = date('Y-m-d H:i:s',time());
		$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($regRow['customer_email']),
        	'subject' => '[保宏]账号激活通知',
        	'body' => "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;您注册的邮箱是：{$regRow['customer_email']},<br/>感谢您的注册，{$activeHtml}。<br/>或者复制以下链接到浏览器进行激活：{$activeurl}",
    	);
        if($regRow['check_verify']){
            if(!Common_Email::sendMail($params)){
                throw new Exception("注册失败,发送邮件失败", '6002');
            }
        }
	}

	/**
	 * [completeCustomer 完善信息]
	 *
	 * @param  [type] $regRow [description]
	 *
	 * @return [type]         [description]
	 */
	private function completeCustomer($baseData, $regRow){
		$country = Service_Country::getByField($regRow['customer_country'], 'country_code');
        $regRow['country_id'] = empty($country) ? '' : $country['country_id'];
		$regRow['customer_country'] = empty($country) ? '' : $country['country_id'];
        $customerRow = Service_Customer::getByField($baseData['customerId'], 'customer_id', "*");
		$base = array(
			'customer_company_name' => $regRow['customer_company_name'],
			'trade_name' => isset($regRow['trade_name']) ? $regRow['trade_name'] : '',
			'trade_co' => isset($regRow['trade_co']) ? $regRow['trade_co'] : '',
			'customer_currency' => isset($regRow['customer_currency']) && $regRow['customer_currency'] ? $regRow['customer_currency'] : '',
			'customer_license' => isset($regRow['customer_license']) &&$regRow['customer_license']  ? $regRow['customer_license'] : '',
			'customer_idcard' => isset($regRow['customer_idcard']) && $regRow['customer_idcard']  ? $regRow['customer_idcard']: '' ,
			'customer_customlsn' => isset($regRow['customer_customlsn']) && $regRow['customer_customlsn'] ? $regRow['customer_customlsn'] :'' ,
			'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' => !(isset($regRow['customer_firstname'])&&$regRow['customer_firstname']) ? '' : $regRow['customer_firstname'],
			'customer_lastname' => !(isset($regRow['customer_lastname'])&&$regRow['customer_lastname']) ? '' : $regRow['customer_lastname'],
			'customer_telephone' => !(isset($regRow['customer_telephone'])&&$regRow['customer_telephone']) ? '' : $regRow['customer_telephone'],
			'customer_province' => !(isset($regRow['customer_province'])&&$regRow['customer_province']) ? '' : $regRow['customer_province'],
			'customer_city' => !(isset($regRow['customer_city']) && $regRow['customer_city']) ? '' : $regRow['customer_city'],
			'customer_postno' => !(isset($regRow['customer_postno']) && $regRow['customer_postno']) ? '' : $regRow['customer_postno'],
			'customer_address' => !(isset($regRow['customer_address']) && $regRow['customer_address']) ? '' : $regRow['customer_address'],
			'customer_country' => !(isset($regRow['customer_country']) && $regRow['customer_country']) ? '' : $regRow['customer_country'],
			'reg_step' => 3,
			'customer_status' =>$customerRow['customer_type'] == "1" ? '2' : '1',
			'customer_activate_code' => 0,
		);
		$book = array(
			'customer_id' => $baseData['customerId'],
			'customer_code' => $baseData['customerCode'],
			'cab_company' => $regRow['customer_company_name'],
			'cab_firstname' => empty($regRow['customer_firstname']) ? '' : $regRow['customer_firstname'],
			'cab_lastname' => empty($regRow['customer_lastname']) ? '' : $regRow['customer_lastname'],
			'cab_country_id' => $regRow['country_id'],
			'cab_city' => empty($regRow['customer_city']) ? '' : $regRow['customer_city'],
			'cab_postcode' => empty($regRow['customer_postno']) ? '' : $regRow['customer_postno'],
			'cab_street_address1' => empty($regRow['customer_address']) ? '' : $regRow['customer_address']
		);
		$state	= Service_Customer::update($base, $baseData['customerId']);
		if(!$state){
			throw new Exception("完善数据错误", '6003');
		}
		$bookState	= Service_CustomerAddressBook::add($book);
		if (empty($bookState)) {
			throw new Exception("地址信息写入错误", '6004');
		}
	}

	/**
	 *
	 * @todo 注册检测数据
	 */
	private function validator($regRow){
		$error = array();
		if($regRow['customer_email']==''){
			$error[] = array('errorCode'=>'9001', 'errorMessage' => '邮箱不能为空');
		}else if(!preg_match("/^([\.a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/",$regRow['customer_email'])){
			$error[] = array('errorCode'=>'9002', 'errorMessage' => '邮箱格式不对');
		}else {
			//判断邮箱的重复性
			$checkEmail = Service_Customer::getByField($regRow['customer_email'], 'customer_email');
			if(!empty($checkEmail)){
				$error[] = array('errorCode'=>'9003', 'errorMessage' => '该邮箱已经被注册');
				$error['customerCode'] = $checkEmail['customer_code'];
				$error['customerId'] = $checkEmail['customer_id'];
			}else{
                $checkEmail = Service_Account::getByField($regRow['customer_email'], 'account_email');
                if(!empty($checkEmail)){
                    $error[] = array('errorCode'=>'9004', 'errorMessage' => '该邮箱已经被子账号注册');
                    $error['customerCode'] = $checkEmail['account_code'];
                    $error['customerId'] = $checkEmail['account_id'];
                }
            }
		}
		if(strlen($regRow['customer_password'])<6){
			$error[] = array('errorCode'=>'9005', 'errorMessage' => '密码必须6位以上(包含6位)');
		}
		if($regRow['customer_password']!=$regRow['re_password']){
			$error[] = array('errorCode'=>'9006', 'errorMessage' => '两次密码必须相同');
		}
		//验证码接口不需要
        if($regRow['check_verify']){
            if($regRow['verify'] == ''){
                $error[] = array('errorCode'=>'9007', 'errorMessage' => '验证码必填');
            }else {
                if (! $this->Verifycode ( $regRow ['verify'] )) {
                    $error [] = array('errorCode'=>'9008', 'errorMessage' => '验证码不对');
                }
            }
        }
        if(!preg_match('/^[0-9A-Z]{10,10}$/', $regRow['trade_co'])){
			$error[] = array('errorCode'=>'9009', 'errorMessage' => '经营单位编码必须为10位的数字或者数字加字母');
		}
		if(!Service_Currency::getByField($regRow['customer_currency'], 'currency_code')){
			$error[] = array('errorCode'=>'9010', 'errorMessage' => '交易币种填写有误['.$regRow['customer_currency'].']');
		}
		if(Service_Country::getByField($regRow['customer_country'], 'country_code') === false){
			$error[] = array('errorCode'=>'9011', 'errorMessage' => '国家二字码填写有误['.$regRow['customer_country'].']');
		}
		return $error;
	}

	/**
	 * @todo 用于检测验证码
	 */
	public function Verifycode($verifyCode) {
		$verify = new Common_Verifycode ();
		return $verify->is_true ( $verifyCode );
	}

	/**
	 * [getRegsterInfo 查询客户备案状态]
	 *
	 * @param  [type] $customerCode [description]
	 *
	 * @return [type]               [description]
	 */
	public function getRegsterInfo($customerCode){
		$result = array('ask' => 0, 'message' => 'Failed', 'error' => array(), 'data'=>array());
		if(empty($customerCode)){
			$result['error'] = array('errorCode'=>'6006', 'errorMessage'=>'Customer code cannot be empty');
			return $result;
		}
		$customerData = Service_Customer::getByField($customerCode, 'customer_code', '*');
		if(empty($customerData) || !is_array($customerData)){
			$result['error'] = array('errorCode'=>'6007', 'errorMessage'=>'Customer does not exist');
			return $result;
		}
		$customerStatus = self::getCustomerStatus();
		//$retureStatus = isset($customerStatus[$customerData['customer_status']]) ? $customerStatus[$customerData['customer_status']] : 'Unknown';
		$countryCodeRow = Service_Country::getByField($customerData['customer_country'], 'country_id', array('country_code'));
		$customerCountryCode = empty($countryCodeRow) ? 'Unknown' : $countryCodeRow['country_code'];
		$result['ask'] = 1;
		$result['message'] = 'Success';
		$result['data'] = array(
			'customerCode' => $customerData['customer_code'],
			'status' => $customerData['customer_status'],
			'email' => $customerData['customer_email'],
			'companyName' => $customerData['customer_company_name'],
			'tradeName' => $customerData['trade_name'],
			'tradeCo' => $customerData['trade_co'],
			'currency' => $customerData['customer_currency'],
			'firstname' => $customerData['customer_firstname'],
			'lastname' => $customerData['customer_lastname'],
			'telphone' => $customerData['customer_telephone'],
			'countryCode' => $customerCountryCode,
			'province' => $customerData['customer_province'],
			'city' => $customerData['customer_city'],
			'postno' => $customerData['customer_postno'],
			'address' => $customerData['customer_address'],
		);
		return $result;
	}

	/**
     * @todo  客户状态
     */
    public static function getCustomerStatus($lang = 'zh_CN')
    {
        $tmpArr = array(
            'zh_CN' => array(
                '0' => '未完成注册',
                '1' => '待审核',
                '2' => '正常',
                '3' => '停用',
                '4' => '资料收集中状态',
                '5' => '合同待签订',
            ),
            'en_US' => array(
                '0' => '未完成注册',
                '1' => '待审核',
                '2' => '正常',
                '3' => '停用',
                '4' => '资料收集中状态',
                '5' => '合同待签订',
            )
        );
        if ($lang == 'auto') {
            $lang = Ec::getLang();
        }
        return isset($tmpArr[$lang]) ? $tmpArr[$lang] : $tmpArr;
    }
	/**
	 *
	 * @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>");
			}else {
				$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;
	}

	/**
	 *
	 * @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;
	}

	/**
     * [debug description]
     * @param  [type] $msg [description]
     * @return [type]      [description]
     */
    public static function debug($message = '', $preinfo = 'Debug:')
    {
        $filePath = APPLICATION_PATH.'/../data/log/'.'api-soap-register.php';
        //file_put_contents($filePath, $preinfo."\n".'['.date('Y-m-d H:i:s').']'."\n\t", FILE_APPEND);
        file_put_contents($filePath, $preinfo.'['.date('Y-m-d H:i:s').']'.var_export($message, true)."\n\t", FILE_APPEND);
        die();
    }
}