<?php
class flow_customer_listClassModel extends flowModel
{
	public function initModel()
	{
		$this->statearr		 = c('array')->strtoarray('停用|#888888,启用|green');
		$this->statarr		 = c('array')->strtoarray('否|#888888,是|#ff6600');
	}
	
	//高级搜索下
	public function flowsearchfields()
	{
		$arr[] = array('name'=>'所属人...','fields'=>'uid');
		$arr[] = array('name'=>'创建人...','fields'=>'createid');
		return $arr;
	}
	
	public function flowrsreplace($rs, $lx=0)
	{
		if(isset($rs['status'])){
			if($rs['status']==0)$rs['ishui'] = 1;
			$zt 	= $this->statearr[$rs['status']];
			$rs['statuss']	= $rs['status'];
			$rs['status']	= '<font color="'.$zt[1].'">'.$zt[0].'</font>';
		}
		
		if(isset($rs['isstat'])){
			$stat 	= $this->statarr[$rs['isstat']];
			$rs['isstat']	= '<font color="'.$stat[1].'">'.$stat[0].'</font>';
		}
		
		if(isset($rs['isgys'])){
			$gys 	= $this->statarr[$rs['isgys']];
			$rs['isgys']	= '<font color="'.$gys[1].'">'.$gys[0].'</font>';
		}
		if($this->rock->arrvalue($rs,'htshu','0')==0)$rs['htshu']='';
		if($this->rock->arrvalue($rs,'moneyz','0')==0)$rs['moneyz']='';
		if($this->rock->arrvalue($rs,'moneyd','0')==0)$rs['moneyd']='';
		
		if($lx==1){
			$rs['suoname'] = $this->adminmodel->getmou('name','id='.$rs['uid'].'');
			
		}
		
		//详情时，移动端
		if($lx==1 && $this->rock->ismobile()){
			if(!isempt($rs['mobile']))$rs['mobile']='<a onclick="return callPhone(this)" href="tel:'.$rs['mobile'].'">'.$rs['mobile'].'</a>';
			if(!isempt($rs['tel']))$rs['tel']='<a onclick="return callPhone(this)" href="tel:'.$rs['tel'].'">'.$rs['tel'].'</a>';
		}
	    if($rs['group']){
	    	$data=$this->db->getone('oa_option',"num='".$rs['group']."'");
	    	$rs['group']=$data['name'];
	    }
	     if($rs['company_classify']){
	    	$data=$this->db->getone('oa_option',"num='".$rs['company_classify']."'");
	    	$rs['company_classify']=$data['name'];
	    }
	     if($rs['company_nature']){
	    	$data=$this->db->getone('oa_option',"num='".$rs['company_nature']."'");
	    	$rs['company_nature']=$data['name'];
	    }
	     if($rs['company_scale']){
	    	$data=$this->db->getone('oa_option',"num='".$rs['company_scale']."'");
	    	$rs['company_scale']=$data['name'];
	    }
	      if($rs['correspond_orgid']){
	    	$data=$this->db->getone('oa_option',"num='".$rs['correspond_orgid']."'");
	    	$rs['correspond_orgid']=$data['name'];
	    }
		
		return $rs;
	}

	      protected function flowoptmenu($ors, $crs)
        {
                $zt  = $ors['statusvalue'];
                $num = $ors['num'];
                if($num=='ztqh'){
                        $this->update('`status`='.$zt.'', $this->id);
                }
                
                //共享
                if($num=='shate'){
                        $cname          = $crs['cname'];
                        $cnameid = $crs['cnameid'];
                        $this->update(array(
                                'shateid'         => $cnameid,
                                'shate'         => $cname,
                        ), $this->id);
                        $this->push($cnameid, '客户管理', ''.$this->adminname.'将一个客户【{name}】共享给你');
                }
                
                //取消共享
                if($num=='unshate'){
                        $this->update(array(
                                'shateid'         => '',
                                'shate'         => '',
                        ), $this->id);
                }
                
                //放入公海
                if($num=='ghnoup'){
                        $this->update(array(
                                'isgh'         => '1',
                                'uid'         => 0,
                        ), $this->id);
                }
        }


        //是否有查看权限
	protected function flowisreadqx()
	{
		$bo = false;
		$shateid = ','.$this->rs['shateid'].',';
		if(contain($shateid,','.$this->adminid.','))$bo=true;
		return $bo;
	}
	
	protected function flowgetfields_qiyong($lx)
	{
		$arr = array();
		if($this->uid==$this->adminid){
			$arr['mobile'] 		= '手机号';
			$arr['tel'] 		= '电话';
			$arr['email'] 		= '邮箱';
			$arr['routeline'] 	= '交通路线';
		}
		return $arr;
	}
	
	protected function flowbillwhere($uid, $lx)
	{
		return array(
			'order' => 'a.status desc,a.optdt desc',
			'table'	=> '`[Q]'.$this->mtable.'` a left join `[Q]admin` b on a.`uid`=b.id',
			'asqom' => 'a.',
			'fields'=> 'a.*,b.name as suoname'
		);
	}
      

			//审核完成后调用
	protected function flowcheckafter($zt, $sm){
	

 	 $data=$this->db->getrows('oa_customer_bank_info',"mid='".$this->rs['id']."'");
		  
   $arr=[];
   foreach ($data as $k=>  $value) {
   	   foreach ($value as $key => $val) {
   	      switch ($key) {
   	      	case 'open_bank_name':
   	      		
   	      		$arr['FT_BD_CUSTBANK'][$k]['FOPENBANKNAME']=$val;

   	      	break;
   	      	case 'bank_code':
   	      		
   	      		$arr['FT_BD_CUSTBANK'][$k]['FBANKCODE']=$val;

   	      		break;
   	      	case 'bank_holder':
   	      		
   	      		$arr['FT_BD_CUSTBANK'][$k]['FACCOUNTNAME']=$val;

   	      		break;
   	      	case 'open_address':
   	      		
   	      		$arr['FT_BD_CUSTBANK'][$k]['FOpenAddressRec']=$val;


   	      }
   	   }
   }
			$cloudUrl = "http://192.168.1.211/k3cloud/";
			//登陆参数
			$data = array(
			'5e64f6ff0bd47f',//帐套Id
			'Administrator',//用户名
			'666666',//密码
			'2052'//语言标识359010087
			);
			//定义记录Cloud服务端返回的Session
			$cookie_jar = tempnam('/tmp','CloudSession');
			$post_content = self::create_postdata($data);
			$result = self::invoke_login($cloudUrl,$post_content,$cookie_jar);
			header("Content-type: text/html; charset=utf8");
			$starttime = microtime(true);
			$name=$this->rs['name'];
			$tax_register_code = $this->rs['tax_register_code'];//纳税登记号
			$openbank = $this->rs['openbank'];//开户银行
			$cardid = $this->rs['cardid'];//银行账号
			
			$invoice_address = $this->rs['invoice_address'];//开户地址
			$company_nature = $this->rs['company_nature']; //公司性质
			$company_classify = $this->rs['company_classify']; //公司类别
			$company_scale = $this->rs['company_scale']; //公司规模
			$group = $this->rs['group']; //客户分组
			$data_model ='{
		    "Creator": "",
		    "NeedUpDateFields": [],
		    "NeedReturnFields": [],
		    "IsDeleteEntry": "true",
		    "SubSystemId": "",
		    "IsVerifyBaseDataField": "false",
		    "IsEntryBatchFill": "true",
		    "ValidateFlag": "true",
		    "NumberSearch": "true",
		    "InterationFlags": "",
		    "IsAutoSubmitAndAudit": "false",
		    "Model": {
		        "FCUSTID": 0,
		        "FCreateOrgId": {
		            "FNumber": "0000"
		        },
		        "FUseOrgId": {
		            "FNumber": "0000"
		        },
		        "FName": "",
		        "FShortName": "",
		        "FCOUNTRY": {
		            "FNumber": "China"
		        },
		        "FCompanyClassify": {
		            "FNumber": ""
		        },
		        "FCompanyNature": {
		            "FNumber": ""
		        },
		        "FCompanyScale": {
		            "FNumber": ""
		        },
		        "FINVOICETITLE": "",
		        "FTAXREGISTERCODE": "",
		        "FINVOICEBANKNAME": "",
		        "FINVOICEBANKACCOUNT": "",
		        "FINVOICEADDRESS": "",
		        "FIsDefPayer": false,
		        "FIsGroup": false,
		        "FCustTypeId": {
		            "FNumber": "KHLB001_SYS"
		        },
		        "FTRADINGCURRID": {
		            "FNumber": "PRE001"
		        },

				"FGroup": {
				"FNumber": ""
				},
		        "FISCREDITCHECK": true,
		        "FIsTrade": true,
		        "FT_BD_CUSTOMEREXT": {
		            "FEnableSL": false
		        }
		     
		    }
		}';
		$model=json_decode($data_model,true);
		
		$model['Model']['FT_BD_CUSTBANK']=$arr['FT_BD_CUSTBANK'];
		$model['Model']['FName']=$name;
		$model['Model']['FShortName']=$name;
		$model['Model']['FCompanyClassify']['FNumber']=isset($company_classify)?$company_classify:'';
		$model['Model']['FCompanyNature']['FNumber']=isset($company_nature)?$company_nature:'';
		$model['Model']['FCompanyScale']['FNumber']=isset($company_scale)?$company_scale:'';
		$model['Model']['FINVOICETITLE']=$name;
		$model['Model']['FTAXREGISTERCODE ']=isset($tax_register_code)?$tax_register_code:'';
		$model['Model']['FINVOICEBANKNAME ']=$openbank;
		$model['Model']['FINVOICEBANKACCOUNT  ']=$cardid;
		$model['Model']['FINVOICEADDRESS  ']=$invoice_address;
		$model['Model']['FGroup']['FNumber']=$group;
	    $data_model=json_encode($model);
   
			$data = array(
			'BD_Customer',//业务对象标识FormId
			$data_model//具体Json字串
			);
		
			$post_content = self::create_postdata($data);
			$result = self::invoke_add($cloudUrl,$post_content,$cookie_jar);
            
			$array = json_decode($result,true);
			
			if($array['Result']['ResponseStatus']['IsSuccess']){
				$endtime = microtime(true);
			   
				$log='客户编号：'.$array['Result']['Number'].'保存接口成功  '.'执行时间：'.($endtime-$starttime).' s'."\r\n";
	
				$file_write = file_put_contents('custmoer.txt',$log,FILE_APPEND);
					$num=$array['Result']['Number'];
					
			    $this->update("`contract_number`='$num'", $this->rs['id']);
				$this->custmoer_submit($cloudUrl,$cookie_jar,$array['Result']['Id'],$array['Result']['Number']);
			  
				$this->custmoer_audit($cloudUrl,$cookie_jar,$array['Result']['Id'],$array['Result']['Number']);
				
				
			}else{
				$log='客户名称：'.$name.'保存接口失败  '.$array['Result']['ResponseStatus']['Errors'][0]['Message'];
			
				$file_write = file_put_contents('custmoer.txt',$log,FILE_APPEND);
			}
		
	}

	public function custmoer_submit($cloudUrl,$cookie_jar,$id,$number){
			$start_time = microtime(true);
		  
			$data_model ="{
			    'CreateOrgId': 0,
			    'Numbers': [],
			    'Ids': $id,
			    'SelectedPostId': 0
			}";
			$data = array(
			'BD_Customer',//业务对象标识FormId
			$data_model//具体Json字串
			);
		
			$post_content = self::create_postdata($data);
		
			$result = self::invoke_submit($cloudUrl,$post_content,$cookie_jar);
	
			
			$array = json_decode($result,true);
            $end_time = microtime(true);
			if($array['Result']['ResponseStatus']['IsSuccess']){
				$log='客户编号：'.$number.'提交接口成功 '.' 执行时间：'.($end_time-$start_time).' s'."\r\n";
			}else{
				$log='客户编号：'.$number.'提交接口失败  '.$array['Result']['ResponseStatus']['Errors'][0]['Message'];
			
			}
			$file_write = file_put_contents('custmoer.txt',$log,FILE_APPEND);
			
			
	}

	public function custmoer_audit($cloudUrl,$cookie_jar,$id,$number){
			$start_time = microtime(true);
			$data_model ="{
			    'CreateOrgId': 0,
			    'Numbers': [],
			    'Ids': $id,
			    'InterationFlags': ''
			}";
			$data = array(
			'BD_Customer',//业务对象标识FormId
			$data_model//具体Json字串
			);
		
			$post_content = self::create_postdata($data);
		
			$result = self::invoke_audit($cloudUrl,$post_content,$cookie_jar);
			$end_time = microtime(true);
			$array = json_decode($result,true);
			if($array['Result']['ResponseStatus']['IsSuccess']){
				$log='客户编号：'.$number.'审核接口成功 '.' 执行时间：'.($end_time-$start_time).' s'."\r\n";
			}else{

				$log='客户编号：'.$number.'审核接口失败  '.$array['Result']['ResponseStatus']['Errors'][0]['Message'];
			
			}
			$file_write = file_put_contents('custmoer.txt',$log,FILE_APPEND);
			
	}


        //登陆
   static     function invoke_login($cloudUrl,$post_content,$cookie_jar)
        {
                $loginurl = $cloudUrl.'Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc';
                return self::invoke_post($loginurl,$post_content,$cookie_jar,TRUE);
        }
        //查询
    static    function invoke_save($cloudUrl,$post_content,$cookie_jar)
        {
                $invokeurl = $cloudUrl.'Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.View.common.kdsvc';
                return self::invoke_post($invokeurl,$post_content,$cookie_jar,FALSE);
        }
        //添加
    static    function invoke_add($cloudUrl,$post_content,$cookie_jar)
        {
                $invokeurl = $cloudUrl.'Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Save.common.kdsvc';
                return self::invoke_post($invokeurl,$post_content,$cookie_jar,FALSE);
        }
        //提交
    static    function invoke_submit($cloudUrl,$post_content,$cookie_jar)
        {
                $invokeurl = $cloudUrl.'Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Submit.common.kdsvc';
                return self::invoke_post($invokeurl,$post_content,$cookie_jar,FALSE);
        }

        //审核
   static     function invoke_audit($cloudUrl,$post_content,$cookie_jar)
        {
                $invokeurl = $cloudUrl.'Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Audit.common.kdsvc';
                return self::invoke_post($invokeurl,$post_content,$cookie_jar,FALSE);
        }

     static   function invoke_post($url,$post_content,$cookie_jar,$isLogin)
        {
                $ch = curl_init($url);

                $this_header = array(
                        'Content-Type: application/json',
                        'Content-Length: '.strlen($post_content)
                );

                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
                curl_setopt($ch, CURLOPT_HTTPHEADER, $this_header);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $post_content);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                if($isLogin){
                        curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_jar);
                }
                else{
                        curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_jar);
                }
                curl_setopt($ch, CURLOPT_TIMEOUT, 5);

                $result = curl_exec($ch);
                curl_close($ch);

                return $result;
        }

        //构造Web API请求格式
       static     function create_postdata($args) {
             $postdata = array(
                    'format'=>1,
                'useragent'=>'ApiClient',
                'rid'=>self::create_guid(),
                'parameters'=>$args,
                'timestamp'=>date('Y-m-d'),
                'v'=>'1.0'
            );
            return json_encode($postdata);
        }

        //生成guid
        static    function create_guid() {
            $charid = strtoupper(md5(uniqid(mt_rand(), true)));
            $hyphen = chr(45);// "-"
            $uuid = chr(123)// "{"
            .substr($charid, 0, 8).$hyphen
            .substr($charid, 8, 4).$hyphen
            .substr($charid,12, 4).$hyphen
            .substr($charid,16, 4).$hyphen
            .substr($charid,20,12)
            .chr(125);// "}"
            return $uuid;
        }
	
}
