<?php

class flow_oayfkClassModel extends flowModel

{
    public function flowrsreplace($rs)
    {
        if($rs['contractNumber']) $rs['contractNumber'] = $this->getContractByTag($rs['contractNumber']);
        return $rs;
    }



	//二级 或一级审批同意之后进行预扣款
	protected function flowcheckbefore($zt, $sm){
		$id=$this->rs['id'];
        $sql = " mid ='$id' and `table`='c_fininfom_oayfk' ";
	    $flow_bill = m('flow_bill')->getone($sql,'allcheckid');


	    $allcheckid=explode(',',$flow_bill['allcheckid']);
        $option = m('option')->getall('pid = 1531 and num =1 order by sort desc','num,name,value,sort');
        foreach ($option as $key => $value) {
        	if(in_array($value['value'], $allcheckid)){
        		$checkid= $value['value'];
        		break;
        	}
        }

	    if(empty($checkid)){
            $option = m('option')->getall('pid = 1531 and num =2 order by sort desc','num,name,value,sort,`explain`');
            foreach ($option as $key => $value) {
        	if(in_array($value['value'], $allcheckid)){
        		$checkid= $value['value'];
        		$explain= $value['explain'];
        		break;
        	}
          }
	    }

		//zt 1代表同意
        if($zt==1){

 		$flowid=$this->getflow();
        if($explain){

        if($flowid['nowcheckid']==$checkid &&  $flowid['nowcourseid']==$explain){
		      $data = m('c_fund_details_yfk')->getall('mid='.$this->rs['id'], 'id,cbzx_code,charge_amount');
		      foreach ($data as $key => $vo) {
		      	 $cbzx_code=$vo['cbzx_code'];
		         $sql = " cost_id='$cbzx_code' and status = 1 and  is_default=1";
		      	 $cost = m('c_fund_account')->getone($sql, 'id,type,freeze_amount,account_balance');//查询账户表成本中心
		      	 if($cost['type']=='1'){		      	 
		      	 if(($cost['account_balance']-$cost['freeze_amount'])<$vo['charge_amount']){
		      	 	 return "账户余额不足";die;
		      	 }
		      	}
				 $id=$cost['id'];

				 $c_withhold = array(
				   	'fund_account_id' => $id,
				   	'docnum' => $this->rs['docnum'],
				    'cost_id' => $vo['cbzx_code'],
				    'amount' =>  $vo['charge_amount'],
				    'status' => 1,
				    'create_time' => date("Y-m-d H:i:s"),
				    'uid' => $this->rs['uid'],
				  );
				 m('c_withhold_yfk')->insert($c_withhold);

				//修改冻结余额
				 $freeze = array(
				  'freeze_amount' => $cost['freeze_amount'] + $vo['charge_amount'],
				);
			
				m('c_fund_account')->update($freeze, "`id`='$id'");
		      }
		    }
        }else{
        		if($flowid['nowcheckid']==$checkid){
		      $data = m('c_fund_details_yfk')->getall('mid='.$this->rs['id'], 'id,cbzx_code,charge_amount');
		      foreach ($data as $key => $vo) {
		      	 $cbzx_code=$vo['cbzx_code'];
		         $sql = " cost_id='$cbzx_code' and status = 1 and  is_default=1";
		      	 $cost = m('c_fund_account')->getone($sql, 'id,type,freeze_amount,account_balance');//查询账户表成本中心
		      	 if($cost['type']=='1'){		      	 
		      	 if(($cost['account_balance']-$cost['freeze_amount'])<$vo['charge_amount']){
		      	 	 return "账户余额不足";die;
		      	 }
		      	}
				 $id=$cost['id'];
				 $c_withhold = array(
				   	'fund_account_id' => $id,
				   	'docnum' => $this->rs['docnum'],
				    'cost_id' => $vo['cbzx_code'],
				    'amount' =>  $vo['charge_amount'],
				    'status' => 1,
				    'create_time' => date("Y-m-d H:i:s"),
				    'uid' => $this->rs['uid'],
				  );
				 m('c_withhold_yfk')->insert($c_withhold);

				//修改冻结余额
				 $freeze = array(
				  'freeze_amount' => $cost['freeze_amount'] + $vo['charge_amount'],
				);
			
				m('c_fund_account')->update($freeze, "`id`='$id'");
		      }
		    }
          }
         }else{
                 $docnum=$this->rs['docnum'];
                 //将单据状态作废余额
                
		         $withhold_cost = m('c_withhold_yfk')->getall("docnum='$docnum' and status =1", 'id,cost_id,amount');
       
		         foreach ($withhold_cost as $key => $vo) {
                 //减去冻结金额
                 $cost_id=$vo['cost_id'];
				 $sql = " cost_id='$cost_id' and status = 1 and  is_default=1";
		      	 $fund_account_cost = m('c_fund_account')->getone($sql, 'id,freeze_amount');
              
                 $id=$fund_account_cost['id'];
				 $freeze = array(
				  'freeze_amount' => $fund_account_cost['freeze_amount'] - $vo['amount'],
				);
			   
				m('c_fund_account')->update($freeze, "`id`='$id'");
              
			    }


				 $status = array(
				  'status' => 0,
				 );
				 m('c_withhold_yfk')->update($status, "docnum='$docnum'");
         }
     }
    


 //        //流程全部完成后调用
	protected function flowcheckfinsh($zt){

			$docnum=$this->rs['docnum'];
			$withhold_cost = m('c_withhold_yfk')->getall("docnum='$docnum' and status =1", 'id,cost_id,amount');
       
		    foreach ($withhold_cost as $key => $vo) {
           // 扣除账户余额 c_fund_account account_balance
           
			$cbzxid= $vo['cost_id'];
			$model = 'c_fund_account';
			$sql = " cost_id ='$cbzxid' and status = 1 and  is_default=1";
			$data = m($model)->getone($sql,'id,name,account_balance,freeze_amount');

			$zfarr = array(
			'account_balance'        =>$data['account_balance']-$vo['amount'],
			);
			$id=$data['id'];
			m('c_fund_account')->update($zfarr,"`id`='$id'");
            
            $freeze = array(
		    'freeze_amount' => $data['freeze_amount'] - $vo['amount'],
				);
			   
		    m('c_fund_account')->update($freeze, "`id`='$id'");

			   // 成本中心 amount 变更
			$cbzx = substr($cbzxid,0,strrpos($cbzxid,"（"));
			$cbzxsql = " code ='$cbzx' and status = 1";

			$cbzxdata = m('c_cbzx')->getone($cbzxsql,'id,amount');
			$cbarr = array(
			'amount'        =>$cbzxdata['amount']+$vo['amount'],
			);
            m('c_cbzx')->update($cbarr,"`code`='$cbzx'");
             //账户明细 c_account_detail
			$account_detail=array(
			'account' => $data['name'],
			'opt_type' => 2,
			'amount' =>$vo['amount'],
			'trans_numb' => $this->rs['docnum'],
			'account_balance' => $data['account_balance']-$vo['amount'],
			'create_time'  =>date("Y-m-d H:i:s"),
			'uid'  =>$this->rs['uid'],
			);

			m('c_account_detail')->insert($account_detail);

			 // 业务付款8业务预付款10费用报销11 oa_c_fund_detail


          $fund_detail=array(
			'trans_numb' =>$this->rs['docnum'],
			'account' =>  $data['name'],
			'toaccount' =>$this->rs['payee'],
			'trans_amount' =>$vo['amount'],
			'business_type' =>10,
			'opt_type' =>2,
			'account_balance'=>$data['account_balance']-$vo['amount'],
			 'create_time'  =>date("Y-m-d H:i:s"),
			'uid'  =>$this->rs['uid'],
			);
			m('c_fund_detail')->insert($fund_detail);

		 }
	}

	 protected function flowcheckafter($zt, $sm, $nowcourse)
    {
        $flowid = $this->getflow();
        if ($flowid['nowcheckid'] == 1085) {
            $cloudUrl = "http://36.110.39.211/k3cloud/";
            //登陆参数
           $data = array(
	         '5ef2c166ad1afa',//帐套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);
            $applicant = $this->rs['applicant'];//申请人
            $FCREATORID = $this->db->getone('oa_personfile', "name='" . $this->rs['applicant'] . "'");
            $gonncode = $FCREATORID['gonncode'];  //申请人编号
            $applicationdpt = $this->rs['applicationdpt'];//申请部门
            $applydt = $this->rs['optdt'];//申请日期
            $amountOfThisPayment = $this->rs['amountOfThisPayment'];//金额
            $contractNumber = $this->rs['contractNumber'];//合同编号
            $contracta = (strpos($contractNumber, "("));
            $contractb = (strrpos($contractNumber, ")"));
            $b = mb_strpos($contractNumber, "(") + mb_strlen("(");
            $e = mb_strpos($contractNumber, ")") - $b;
            $contractNumber = mb_substr($contractNumber, $b, $e);

            $contract = $this->db->getone('oa_c_contract', 'numb = "' . $contractNumber . '"');
            if ($contract['receive'] == 2) {
                $suppliername = $contract['partb_name'];//供应商名称
            } else {
                $suppliername = $contract['parta_name'];//供应商名称
            }
            $sql = 'bank_code = ' . $contract['bankcode'];
            $data = $this->db->getone('oa_supplier_bank_info', $sql);
            $paymentMethod = $this->rs['paymentMethod'];//付款方式
            $cbxmid = $this->rs['cbzxid'];//成本中心
            $cbxmid = substr($cbxmid, 0, strpos($cbxmid, "（"));

            $oafk_details=$this->db->getrows('oa_c_fund_details_yfk',"mid='".$this->rs['id']."'");
     
   
        $arr=[];
         foreach ($oafk_details as $k=>  $value) {
               foreach ($value as $key => $val) {
                  switch ($key) {
                     
                     case 'charge_amount':
                        
                        $arr['FPAYAPPLYENTRY'][$k]['FAPPLYAMOUNTFOR']=$val;

                        break;
                   
                        break;
                          default:
                                    $arr['FPAYAPPLYENTRY'][$k]['FSETTLETYPEID']['FNumber']='JSFS04_SYS';
                                    $arr['FPAYAPPLYENTRY'][$k]['FPAYPURPOSEID']['FNumber']='SFKYT09_SYS';
                                    $arr['FPAYAPPLYENTRY'][$k]['FENDDATE']=$this->rs['applydt'].' 00:00:00';
                                    $arr['FPAYAPPLYENTRY'][$k]['FEXPECTPAYDATE']=$this->rs['applydt'].' 00:00:00';
                                    $arr['FPAYAPPLYENTRY'][$k]['FEACHBANKACCOUNT'] = $data['bank_code'];
                                    $arr['FPAYAPPLYENTRY'][$k]['FEACHCCOUNTNAME'] = $data['bank_holder'];
                                    $arr['FPAYAPPLYENTRY'][$k]['FEACHBANKNAME'] = $data['open_bank_name'];
                         
                           break;
                  }
               }
         }
            $data_model = '{
                        "Creator": "",
                        "NeedUpDateFields": [],
                        "NeedReturnFields": [],
                        "IsDeleteEntry": "true",
                        "SubSystemId": "",
                        "IsVerifyBaseDataField": "false",
                        "IsEntryBatchFill": "true",
                        "ValidateFlag": "true",
                        "NumberSearch": "true",
                        "InterationFlags": "",
                        "IsAutoSubmitAndAudit": "false",
                        "Model": {
                            "FID": 0,
                            "FBILLTYPEID": {
                                "FNUMBER": "FKSQ009"
                            },
                            "FDATE": "2020-06-29 00:00:00",
                            "FCONTACTUNITTYPE": "BD_Supplier",
                            "FCONTACTUNIT": {
                                "FNumber": "GDGYS-0003"
                            },
                            "FRECTUNITTYPE": "BD_Supplier",
                            "FRECTUNIT": {
                                "FNumber": "GDGYS-0003"
                            },
                            "FCURRENCYID": {
                                "FNumber": "PRE001"
                            },
                            "FAPPLYORGID": {
                                "FNumber": "1000"
                            },
                            "FPAYORGID": {
                                "FNumber": "1000"
                            },
                            "FSETTLEORGID": {
                                "FNumber": "1000"
                            },
                            "FPURCHASEORGID": {
                                "FNumber": "1000"
                            },
                            "FDOCUMENTSTATUS": "Z",
                            "FCANCELSTATUS": "A",
                            "FMAINBOOKID": {
                                "FNUMBER": "PRE001"
                            },
                            "FIsCredit": false,
                            "FSETTLECUR": {
                                "FNUMBER": "PRE001"
                            },
                            "FISCARRYRATE": false,
                            "F_PAEZ_Cbzx": {
                                "FNUMBER": "GS.BJ.B01.02"
                            },
                            "F_PAEZ_OADJBH": "213123213"
                           
                        }
                    }';

            

            $model = json_decode($data_model, true);
            // $model['Model']['F_PAEZ_Cbzx']['FNUMBER'] = $cbxmid;
            $model['Model']['FCREATORID']['FNUMBER'] = $gonncode;
            $model['Model']['FDATE'] = $applydt;
            $model['Model']['F_PAEZ_OADJBH'] = $this->rs['docnum'];;
            // $model['Model']['FCONTACTUNIT']['FNumber']=$suppliername;
            // $model['Model']['FRECTUNIT']['FNumber']=$suppliername;
            $model['Model']['FPAYAPPLYENTRY'] = $arr['FPAYAPPLYENTRY'];


            $data_model = json_encode($model);
            $data = array(
                'CN_PAYAPPLY',//业务对象标识FormId
                $data_model//具体Json字串
            );

            $post_content = self::create_postdata($data);
            $result = self::invoke_add($cloudUrl, $post_content, $cookie_jar);
            $array = json_decode($result, true);
            var_dump($array);
            if ($array['Result']['ResponseStatus']['IsSuccess']) {
                $num = $array['Result']['Number'];
                $this->update("`fbillno`='$num'", $this->rs['id']);
                var_dump($this->supplier_submit($cloudUrl, $cookie_jar, $array['Result']['Id'], $array['Result']['Number']));
                var_dump($this->supplier_audit($cloudUrl, $cookie_jar, $array['Result']['Id'], $array['Result']['Number']));
            }
        }
    }

    public function supplier_submit($cloudUrl, $cookie_jar, $id, $number)
    {
        $start_time = microtime(true);

        $data_model = "{
             'CreateOrgId': 0,
             'Numbers': [],
             'Ids': $id,
             'SelectedPostId': 0
         }";
        $data = array(
            'CN_PAYAPPLY',//业务对象标识FormId
            $data_model//具体Json字串
        );

        $post_content = self::create_postdata($data);

        $result = self::invoke_submit($cloudUrl, $post_content, $cookie_jar);


        $array = json_decode($result, true);


        return $array;

    }


    public function supplier_audit($cloudUrl, $cookie_jar, $id, $number)
    {
        $data_model = "{
             'CreateOrgId': 0,
             'Numbers': [],
             'Ids': $id,
             'InterationFlags': ''
         }";
        $data = array(
            'CN_PAYAPPLY',//业务对象标识FormId
            $data_model//具体Json字串
        );

        $post_content = self::create_postdata($data);

        $result = self::invoke_audit($cloudUrl, $post_content, $cookie_jar);
        $array = json_decode($result, true);

        return $array;
    }

    //登陆
    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;
    }

    static function getbxlx($name)
    {
        if ($name == '现金') {
            return 'JSFS01_SYS';
        } else {
            return 'JSFS04_SYS';
        }

    }

    //构造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;
    }
}