<?php
class flow_finfybxClassModel extends flowModel
{
    public function flowcheckname($num)
    {
        $arr = [];
        if ($num == 'abc')
        {
            $arr["$sid"] = "982";
            $arr["$sna"] = "ÎµÑàéª";
        }
        return $arr;
    }

   

    //二级 或一级审批同意之后进行预扣款
    protected function flowcheckbefore($zt, $sm){


        if($this->rs['dikouid']){
            $dikouid = $this->rs['dikouid'];
            if(strpos($dikouid,',') !== false){

                $jk_num=explode(",",$dikouid);


                foreach ($jk_num  as $key => $value ){
                    if($this->rs['money'] ==0 ){
                        break;
                    }

                    $jk_num=substr($value,0,strrpos($value,'金'));



                    $sql = " docnum ='$jk_num'  ";
                    $fininfom_jk = m('c_fininfom_jk')->getone($sql,'amount');//金额


                        $docnum=$this->rs['docnum'];
                        if($this->rs['money'] >= $fininfom_jk['amount']){
                            $jkbalance = array(
                                'balance' => 0,
                            );
                            $dk_amount=$fininfom_jk['amount'];

                        }else{
                            $jkbalance = array(
                                'balance' =>   $fininfom_jk['amount']-$this->rs['money'],
                            );
                            $dk_amount=$this->rs['money'];
                        }

                        $this->rs['money']=$this->rs['money']-$dk_amount;
                        $jkbalance = array(
                            'balance' => $fininfom_jk['amount']-$this->rs['money'],
                        );
                        m('c_fininfom_jk')->update($jkbalance, "`docnum`='$jk_num'");


                        $deduct_detail = array(
                            'jk_num' => $jk_num,
                            'bx_num' => $docnum,
                            'dk_amount' =>$dk_amount,
                            'status' =>0,
                            'create_time' => date("Y-m-d H:i:s"),
                        );
                        m('c_deduct_detail')->insert($deduct_detail);
                }
                echo 11;
            }else{
                $jk_num=substr($dikouid,0,strrpos($dikouid,'金'));
            }




//
//            if($this->rs['money'] <= $fininfom_jk['amount']) {
//            }


//            if($this->rs['money'] > $fininfom_jk['amount']){
//
//            }

        }







        $id=$this->rs['id'];
        $sql = " mid ='$id' and `table`='fininfom' ";
        $flow_bill = m('flow_bill')->getone($sql,'allcheckid');


        $allcheckid=explode(',',$flow_bill['allcheckid']);
        $option = m('option')->getall('pid = 1546 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 = 1546 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('fininfom')->getall('id='.$this->rs['id'], 'id,cbxmid,money');
              foreach ($data as $key => $vo) {
                 $cbzx_code=$vo['cbxmid'];
                 $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['money']){
                     return "账户余额不足";die;
                 }
                }
                 $id=$cost['id'];
 
                 $c_withhold = array(
                    'fund_account_id' => $id,
                    'docnum' => $this->rs['docnum'],
                    'cost_id' => $vo['cbxmid'],
                    'amount' =>  $vo['money'],
                    'status' => 1,
                    'create_time' => date("Y-m-d H:i:s"),
                    'uid' => $this->rs['uid'],
                  );
                 m('c_withhold_fininform')->insert($c_withhold);

                //修改冻结余额
                 $freeze = array(
                  'freeze_amount' => $cost['freeze_amount'] + $vo['money'],
                );
            
                m('c_fund_account')->update($freeze, "`id`='$id'");
              }
            }
        }else{
                if($flowid['nowcheckid']==$checkid){
              $data = m('fininfom')->getall('id='.$this->rs['id'], 'id,cbxmid,money');
              foreach ($data as $key => $vo) {
                 $cbzx_code=$vo['cbxmid'];
                 $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['money']){
                     return "账户余额不足";die;
                 }
                }
                 $id=$cost['id'];

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

                //修改冻结余额
                 $freeze = array(
                  'freeze_amount' => $cost['freeze_amount'] + $vo['money'],
                );
            
                m('c_fund_account')->update($freeze, "`id`='$id'");
              }
            }
          }
         }else{
                 $docnum=$this->rs['docnum'];
                 //将单据状态作废余额
                
                 $withhold_cost = m('c_withhold_fininform')->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'];
                 if($fund_account_cost['freeze_amount']==0){
                      $freeze = array(                
                     'freeze_amount' =>  $vo['amount'],
                      ); 
                 }else{
                     $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_fininform')->update($status, "docnum='$docnum'");
         }



      // 金蝶
       $id=$this->rs['id'];
      $sql = " mid ='$id' and `table`='fininfom' ";
      $option = m('option')->getall('pid = 1568','`explain`');
      foreach ($option as $key => $value) {
        $allcheckid[]=$value['explain'];
      }
      //查询流程为财务确认
      $flowid = $this->getflow();


     if(in_array($flowid['nowcourseid'],$allcheckid)){

     if($flowid['nowcheckid']=='992'){
      $data=$this->db->getone('oa_personfile',"name='".$this->rs['applicant']."'");     
      $gonncode=$data['gonncode'];
      // $data['pfbanknum'];//对方银行卡号
      // $data['gonncode'];//员工编号

        //明细
        $oa_fininfos=$this->db->getrows('oa_fininfos',"mid='".$this->rs['id']."'");
     
   
        $arr=[];
         foreach ($oa_fininfos as $k=>  $value) {
               foreach ($value as $key => $val) {
                  switch ($key) {
                     case 'bxType':
                        
                        $arr['FPAYAPPLYENTRY'][$k]['FCOSTID']['FNUMBER']=self::getbxlx($val);

                     break;
                     case 'money':
                        
                        $arr['FPAYAPPLYENTRY'][$k]['FAPPLYAMOUNTFOR']=$val;

                        break;
                     case 'sm':
                        
                        $arr['FPAYAPPLYENTRY'][$k]['FDescription']=$val;
                        break;
                          default:
                              $arr['FPAYAPPLYENTRY'][$k]['FSETTLETYPEID']['FNumber']='JSFS04_SYS';
                              $arr['FPAYAPPLYENTRY'][$k]['FPAYPURPOSEID']['FNumber']='SFKYT10_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['pfbanknum'];
                         
                           break;
                  }
               }
         }
         
         $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'];//申请人
         $applicationdpt=$this->rs['applicationdpt'];//申请部门
         $applydt=$this->rs['applydt'];//申请日期
         $cbxmid=$this->rs['cbxmid'];//成本中心
         
         $cbxmid=substr($cbxmid,0,strpos($cbxmid, "（"));



         $money=$this->rs['money'];//合计金额
         // $applydt=$this->rs['applydt'];//发票日期
         // $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'];// *说明
      
         
         
         $data_model ='{
                      "Creator": "",
                      "NeedUpDateFields": [],
                      "NeedReturnFields": [],
                      "IsDeleteEntry": "true",
                      "SubSystemId": "",
                      "IsVerifyBaseDataField": "false",
                      "IsEntryBatchFill": "true",
                      "ValidateFlag": "true",
                      "NumberSearch": "true",
                      "InterationFlags": "",
                      "IsAutoSubmitAndAudit": "false",
                      "Model": {
                          "FID": 0,
                          "FBILLTYPEID": {
                              "FNUMBER": "FKSQ005_SYS"
                          },
                          "FDATE": "2020-02-11 00:00:00",
                          "FCONTACTUNITTYPE": "BD_Empinfo",
                          "FCONTACTUNIT": {
                              "FNumber": "GONN-0002"
                          },
                          "FRECTUNITTYPE": "BD_Empinfo",
                          "FRECTUNIT": {
                              "FNumber": "GONN-0002"
                          },
                          "FCURRENCYID": {
                              "FNumber": "PRE001"
                          },
                          "FPAYORGID": {
                              "FNumber": "1000"
                          },
                          "FSETTLEORGID": {
                              "FNumber": "1000"
                          },
                          "FDEPARTMENT": {
                              "FNumber": ""
                          },
                          "F_PAEZ_OADJBH": "123321",
                          "FDOCUMENTSTATUS": "Z",
                          "FCANCELSTATUS": "A",
                          "FMAINBOOKID": {
                              "FNUMBER": "PRE001"
                          },
                          "FIsCredit": false,
                          "FAPPLYORGID": {
                              "FNumber": "1000"
                          },
                          "FSETTLECUR": {
                              "FNUMBER": "PRE001"
                          },
                          "FISCARRYRATE": false,
                          "F_PAEZ_Cbzx": {
                              "FNUMBER": " GS.BJ.B1"
                          }
                       
                      }
                  }';
         $model=json_decode($data_model,true);

         $model['Model']['F_PAEZ_Cbzx']['FNUMBER']=$cbxmid;
         $model['Model']['FDATE']=$applydt;
         $model['Model']['FCONTACTUNIT']['FNumber']=$gonncode;
         $model['Model']['F_PAEZ_OADJBH']=$this->rs['docnum'];;
         $model['Model']['FRECTUNIT']['FNumber']=$gonncode;
         $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']);
                           
                  $erp_log=array(
                        'sericnum'=> $this->rs['docnum'],
                        'table'=>'fininfom',
                        'name' => '保存成功',
                        'remark' => json_encode($array),
                        'optdt'  =>date("Y-m-d H:i:s"),
                        'level'=>2,
                        'fbillno'=>$num,
                        'fbillnoid'=>$array['Result']['Id'],
                        'fbillno_type'=>1,

                    );
                   m('erplog')->insert($erp_log);

            if($this->supplier_submit($cloudUrl,$cookie_jar,$array['Result']['Id'],$array['Result']['Number'])){
                $erp_log=array(
                        'sericnum'=> $this->rs['docnum'],
                        'table'=>'fininfom',
                        'name' => '提交成功',
                        'remark' => json_encode($array),
                        'optdt'  =>date("Y-m-d H:i:s"),
                        'level'=>2,
                        'fbillno'=>$num,
                        'fbillnoid'=>$array['Result']['Id'],
                        'fbillno_type'=>2,
                    );
                   m('erplog')->insert($erp_log);
                 }else{
                    $erp_log=array(
                        'sericnum'=> $this->rs['docnum'],
                        'table'=>'fininfom',
                        'name' => '提交失败',
                        'remark' => json_encode($array),
                        'optdt'  =>date("Y-m-d H:i:s"),
                        'level'=>1,
                        'fbillno'=>$num,
                        'fbillnoid'=>$array['Result']['Id'],
                        'fbillno_type'=>2,

                    );
                   m('erplog')->insert($erp_log);
                 }
                 if($this->supplier_audit($cloudUrl,$cookie_jar,$array['Result']['Id'],$array['Result']['Number'])){
                         $erp_log=array(
                        'sericnum'=> $this->rs['docnum'],
                        'table'=>'fininfom',
                        'name' => '审核成功',
                        'remark' => json_encode($array),
                        'optdt'  =>date("Y-m-d H:i:s"),
                        'level'=>2,
                        'fbillno'=>$num,
                        'fbillnoid'=>$array['Result']['Id'],
                        'fbillno_type'=>3,

                    );
                   m('erplog')->insert($erp_log);
                 }else{
                   $erp_log=array(
                        'sericnum'=> $this->rs['docnum'],
                        'table'=>'fininfom',
                        'name' => '审核失败',
                        'remark' => json_encode($array),
                        'optdt'  =>date("Y-m-d H:i:s"),
                        'level'=>1,
                        'fbillno'=>$num,
                        'fbillnoid'=>$array['Result']['Id'],
                        'fbillno_type'=>3,

                    );
                   m('erplog')->insert($erp_log);
                 }
            
            
         }else{
                 $erp_log=array(
                        'sericnum'=> $this->rs['docnum'],
                        'table'=>'fininfom',
                        'name' => '保存失败',
                        'remark' => json_encode($array),
                        'optdt'  =>date("Y-m-d H:i:s"),
                        'level'=>1,
                        'fbillno'=>$num,
                        'fbillnoid'=>$array['Result']['Id'],
                        'fbillno_type'=>1,

                    );
                   m('erplog')->insert($erp_log);
         }
         
        }  
      
      }






     }
    

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

//            $docnum=$this->rs['docnum'];
//            $withhold_cost = m('c_withhold_fininform')->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['applicant'],
//            'trans_amount' =>$vo['amount'],
//            'business_type' =>11,
//            '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);
//         }






    }

    
      
  
 



   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)
    {

        $data = m('c_bxlx')->getone("name='".$name."'", 'name,number');
        return $data['number'];
    }

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

}