<?php
class flow_supplierClassModel 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($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['supplier_group']){
	    	$data=$this->db->getone('oa_option',"num='".$rs['supplier_group']."'");
	    	$rs['supplier_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_org_id']){
	    	$data=$this->db->getone('oa_option',"num='".$rs['correspond_org_id']."'");
	    	$rs['correspond_org_id']=$data['name'];
	    }
	    
	      if($rs['pay_currency']){
	    	$data=$this->db->getone('oa_option',"num='".$rs['pay_currency']."'");
	    	$rs['pay_currency']=$data['name'];
	    }

	     if($rs['settle_type']){
	    	$data=$this->db->getone('oa_option',"num='".$rs['settle_type']."'");
	    	$rs['settle_type']=$data['name'];
	    }
	     if($rs['pay_condition']){
	    	$data=$this->db->getone('oa_option',"num='".$rs['pay_condition']."'");
	    	$rs['pay_condition']=$data['name'];
	    }
	    if($rs['tax_type']){
	    	$data=$this->db->getone('oa_option',"num='".$rs['tax_type']."'");
	    	$rs['tax_type']=$data['name'];
	    }
	     if($rs['tend_type']){
	    	$data=$this->db->getone('oa_option',"num='".$rs['tend_type']."'");
	    	$rs['tend_type']=$data['name'];
	    }
	     if($rs['tax_rate']){
	    	$data=$this->db->getone('oa_option',"num='".$rs['tax_rate']."'");
	    	$rs['tax_rate']=$data['name'];
	    }
	     if($rs['bank_currency']){
	    	$data=$this->db->getone('oa_option',"num='".$rs['bank_currency']."'");
	    	$rs['bank_currency']=$data['name'];
	    }
            if($rs['trade']){
                $data=$this->db->getone('oa_option',"num='".$rs['trade']."'");
                $rs['trade']=$data['name'];
            }


		
		return $rs;
	}

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

		$data=$this->db->getrows('oa_supplier_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]['FBankHolder']=$val;

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


		   	      }
		   	   }
		   }

        	$cloudUrl = "http://192.168.1.211/k3cloud/";
			//登陆参数
			$data = array(
			'5d64e2f4ecb139',//帐套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'];//供应商名称
			$supply_classify=$this->rs['supply_classify'];//供应类别
			$supplier_group=$this->rs['supplier_group'];//供应商分组
			$company_classify=$this->rs['company_classify'];//公司类别
			$company_nature=$this->rs['company_nature'];//公司性质
			$company_scale=$this->rs['company_scale'];//公司规模
			$web_site=$this->rs['web_site'];//公司网址
			$settle_type=$this->rs['settle_type'];//结算方式
			$pay_condition=$this->rs['pay_condition'];// 付款条件
			$tend_type=$this->rs['tend_type'];// *经营类型
			$tax_type=$this->rs['tax_type'];// 税分类
			$pay_advance_amount=$this->rs['pay_advance_amount'];// 单次预付额度
			$tax_register_code=$this->rs['tax_register_code'];// 税务登记号
			$finance_desc=$this->rs['finance_desc'];// 描述
			$found_date=$this->rs['found_date'];// 创立日期
			$legal_person=$this->rs['legal_person'];// 法人代表
			$register_fund=$this->rs['register_fund'];// 注册资金（万元）	
			$register_code=$this->rs['register_code'];// 工商登记号
			$tend_permit=$this->rs['tend_permit'];// 生产经营许可证
			$social_cre_code=$this->rs['social_cre_code'];// 统一社会信用代码
			$register_address=$this->rs['register_address'];// *注册地址
	
			
			
			$data_model ='{
				    "Creator": "",
				    "NeedUpDateFields": [],
				    "NeedReturnFields": [],
				    "IsDeleteEntry": "true",
				    "SubSystemId": "",
				    "IsVerifyBaseDataField": "false",
				    "IsEntryBatchFill": "true",
				    "ValidateFlag": "true",
				    "NumberSearch": "true",
				    "InterationFlags": "",
				    "IsAutoSubmitAndAudit": "false",
				    "Model": {
				        "FSupplierId": 0,
				        "FCreateOrgId": {
				            "FNumber": "0000"
				        },
				        "FUseOrgId": {
				            "FNumber": "0000"
				        },
				        "FName": "供应商名称",
				        "FShortName": "供应商简称",
				        "FBaseInfo": {
				            "FWebSite": "",
				            "FFoundDate": "2019-12-26 00:00:00",
				            "FLegalPerson": "",
				            "FRegisterFund": 100.0,
				            "FRegisterCode": "2019gongshang",
				            "FSOCIALCRECODE": "2019shehui",
				            "FTendPermit": "2019shengchan",
				            "FRegisterAddress": "注册地址",
				            "FSupplyClassify": "CG",
				            "FCompanyClassify": {
				                "FNumber": "GSLL01_SYS"
				            },
				            "FCompanyNature": {
				                "FNumber": "GSXZ001_SYS"
				            },
				            "FCompanyScale": {
				                "FNumber": "GSGM01_SYS"
				            }
				        },
				        "FBusinessInfo": {
				            "FSettleTypeId": {
				                "FNumber": "JSFS02_SYS"
				            },
				            "FVmiBusiness": false,
				            "FEnableSL": false
				        },
				        "FFinanceInfo": {
				            "FPayCurrencyId": {
				                "FNumber": "PRE001"
				            },
				            "FPayCondition": {
				                "FNumber": "FKTJ01_SYS"
				            },
				            "FPayAdvanceAmount": 1111.0,
				            "FTaxType": {
				                "FNumber": "SFL02_SYS"
				            },
				            "FTaxRegisterCode": "111111",
				            "FInvoiceType": "1",
				            "FTaxRateId": {
				                "FNUMBER": "SL02_SYS"
				            },
				            "FFinanceDesc": "描述"
				        }
				       
				    }
				}';
		$model=json_decode($data_model,true);

		// $supplier_group//供应商分组
		// 	// $tend_type// *经营类型
		$model['Model']['FBankInfo']=$arr['FT_BD_CUSTBANK'];
		$model['Model']['FName']=$name;
		$model['Model']['FShortName']=$name;

		// $model['Model']['FBaseInfo']['FSupplyClassify']=$supply_classify;
		$model['Model']['FBaseInfo']['FCompanyClassify']['FNumber']=isset($company_classify)?$company_classify:'';
	    $model['Model']['FBaseInfo']['FCompanyNature']['FNumber']=isset($company_nature)?$company_nature:'';
	
	   
		$model['Model']['FBaseInfo']['FCompanyScale']['FNumber']=isset($company_scale)?$company_scale:'';

      $model['Model']['FBaseInfo']['FWebSite']=isset($web_site)?$web_site:'';
	
		$model['Model']['FBusinessInfo']['FSettleTypeId']['FNumber']=isset($settle_type)?$settle_type:'';
		$model['Model']['FFinanceInfo']['FPayCondition']['FNumber']=isset($pay_condition)?$pay_condition:'';


		
		$model['Model']['FFinanceInfo']['FTaxType']['FNumber']=isset($tax_type)?$tax_type:'';
		if($pay_advance_amount=='不适用'){
           $model['Model']['FFinanceInfo']['FPayAdvanceAmount']=0;
		}else{
		   $model['Model']['FFinanceInfo']['FPayAdvanceAmount']=$pay_advance_amount;
		}
		$model['Model']['FFinanceInfo']['FTaxRegisterCode']=isset($tax_register_code)?$tax_register_code:'';		
		$model['Model']['FFinanceInfo']['FFinanceDesc']=isset($finance_desc)?$finance_desc:'';	
		
		$model['Model']['FBaseInfo']['FFoundDate']=isset($found_date)?$found_date:'';	
		$model['Model']['FBaseInfo']['FLegalPerson']=isset($legal_person)?$legal_person:'';	
		if($register_fund=='不适用'){
    		$model['Model']['FBaseInfo']['FRegisterFund']=0;
		}else{
			$model['Model']['FBaseInfo']['FRegisterFund']=$register_fund;
		}
	    $model['Model']['FBaseInfo']['FRegisterCode']=isset($register_code)?$register_code:'';	
		$model['Model']['FBaseInfo']['FTendPermit']=isset($tend_permit)?$tend_permit:'';	
		$model['Model']['FBaseInfo']['FSOCIALCRECODE']=isset($social_cre_code)?$social_cre_code:'';		
		$model['Model']['FBaseInfo']['FRegisterAddress']=isset($register_address)?$register_address:'';		
	    $data_model=json_encode($model);
	   
	    	$data = array(
			'BD_Supplier',//业务对象标识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);
				$num=$array['Result']['Number'];
			        $this->update("`number`='$num'", $this->rs['id']);
				$log='供应商编号：'.$array['Result']['Number'].'保存接口成功  '.'执行时间：'.($endtime-$starttime).' s'."\r\n";
	
				$file_write = file_put_contents('supplier.txt',$log,FILE_APPEND);
					$num=$array['Result']['Number'];
					
				$this->supplier_submit($cloudUrl,$cookie_jar,$array['Result']['Id'],$array['Result']['Number']);
			  
				$this->supplier_audit($cloudUrl,$cookie_jar,$array['Result']['Id'],$array['Result']['Number']);
				
				
			}else{
				$log='供应商名称：'.$name.'保存接口失败  '.$array['Result']['ResponseStatus']['Errors'][0]['Message'];
				$file_write = file_put_contents('supplier.txt',$log,FILE_APPEND);
			}


		
	}


	public function supplier_submit($cloudUrl,$cookie_jar,$id,$number){
			$start_time = microtime(true);
		  
			$data_model ="{
			    'CreateOrgId': 0,
			    'Numbers': [],
			    'Ids': $id,
			    'SelectedPostId': 0
			}";
			$data = array(
			'BD_Supplier',//业务对象标识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('supplier.txt',$log,FILE_APPEND);
			
			
	}

	public function supplier_audit($cloudUrl,$cookie_jar,$id,$number){
			$start_time = microtime(true);
			$data_model ="{
			    'CreateOrgId': 0,
			    'Numbers': [],
			    'Ids': $id,
			    'InterationFlags': ''
			}";
			$data = array(
			'BD_Supplier',//业务对象标识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('supplier.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;
        }
	 
}
