<?php

/**
 * Created by PhpStorm.
 * User: chouchou
 * Date: 2020-4-2
 * Time: 0:17
 */

class openfinfybxClassAction extends openapiAction
{




    public function listAction(){

        $sql  = 'select id,fbillno,status from [Q]fininfom  where status=0 and fbillno is NOT null';

        $dataarr = $this->db->getall($sql);
    
        foreach ($dataarr as $key => $value) {

            $cloudUrl = "http://36.110.39.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);
            $data_model='{
                "FormId": "AP_PAYBILL",
                "FieldKeys": "FBillNo,FDOCUMENTSTATUS,FPAYTOTALAMOUNTFOR,FPOSTDATE",
                "FilterString": "",
                "OrderString": "",
                "TopRowCount": 0,
                "StartRow": 0,
                "Limit": 0
                }';
            $model=json_decode($data_model,true);
            $model['FilterString']="FBillNo ="."'".$value['fbillno']."'";

            $data_model=json_encode($model);

            $data = array(
                $data_model//具体Json字串
            );

            $post_content = self::create_postdata($data);
            $result = self::invoke_save($cloudUrl,$post_content,$cookie_jar);
            $array = json_decode($result,true);

            if(count($array)>1){

                $key = ['FBillNo','FDOCUMENTSTATUS','FPAYTOTALAMOUNTFOR','FPOSTDATE' ];
                $new_array = array();
                foreach($array as $k=>$v) {
                    $new_array[$k] = array_combine($key,$v);
                }

                // 计算金钱
                $sum = 0;
                foreach($new_array as $ke =>$item){
                    if($item['FDOCUMENTSTATUS']=='C'){
                        $sum += (int)$item['FPAYTOTALAMOUNTFOR'];

                        $payflow = $this->db->getone('[Q]c_fininfom_paymentflow',"`fbillno`='".$new_array[$ke]['FBillNo']."'",'id,fbillno');
                        $fbillno=$new_array['FBillNo'];
                        $datalist = $this->db->getone('[Q]fininfom',"`fbillno`='".$value['fbillno']."'",'id,docnum,applicant,fbillno,money');

                            $paymentflow=array(
                                'docnum'        =>$datalist['docnum'],
                                'fbillno'        =>$new_array[$ke]['FBillNo'],
                                'fpaytotalamountfor'        =>$new_array[$ke]['FPAYTOTALAMOUNTFOR'],
                                'mid'        =>$datalist['id'],
                                'date'        =>substr($new_array[$ke]['FPOSTDATE'],0,strpos($new_array[$ke]['FPOSTDATE'], 'T')),
                                'create_time'        =>date("Y-m-d H:i:s"),
                            );
                            m('c_fininfom_paymentflow')->insert($paymentflow);


                    }
                }

                if($datalist['money']==$sum){

                    m('fininfom')->update('`status`=1',$datalist['id']);
                    $zfarr = array(
                        'status'        =>1,
                        'nowcourseid'       => 0,
                        'nowcheckid'       => NULL,
                        'nowcheckname'    => NULL,
                        'nstatustext'  => '尹再伟处理同意',
                    );
                    m('flow_bill')->update($zfarr,"`table`='fininfom' and  mid=".$datalist['id']);

                    $addarr = array(
                        'table'     => 'fininfom',
                        'mid'       => $datalist['id'],
                        'status' => 1,
                        'statusname'   => '同意',
                        'name'     => '出纳付款',
                        'courseid'  => 310,
                        'optdt'    => date("Y-m-d H:i:s"),
                        'explain'  => '系统自动确认',
                        'ip'        => '0.0.0.0',
                        'web'       =>'Chrome',
                        'checkname'    =>'尹再伟',
                        'checkid'    =>1085,
                        'modeid'    =>103,
                        'color'    =>'green',
                        'valid'    =>1,
                        'step'    =>5,
                        'qmimg'    =>NULL,
                        'iszb'    =>0
                    );
                    m('flow_log')->insert($addarr);
                    $docnum= $datalist['docnum'];
                        $withhold_cost = m('c_withhold_fininform')->getall("docnum='$docnum' and status =1", 'id,cost_id,uid,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' => $datalist['docnum'],
                            'account_balance' => $data['account_balance']-$vo['amount'],
                            'create_time'  =>date("Y-m-d H:i:s"),
                            'uid'  =>$vo['uid'],
                            );

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

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


                          $fund_detail=array(
                            'trans_numb' =>$datalist['docnum'],
                            'account' =>  $data['name'],
                            'toaccount' =>$datalist['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'  =>$vo['uid'],
                            );
                            m('c_fund_detail')->insert($fund_detail);
                         }
                }



            }else{

                $key = ['FBillNo','FDOCUMENTSTATUS','FPAYTOTALAMOUNTFOR','FPOSTDATE' ];
                $new_array = array();
                foreach($array as $k=>$v) {
                    $new_array= array_combine($key,$v);
                }
                $fbillno=$new_array['FBillNo'];
                $datalist = $this->db->getone('[Q]fininfom',"`fbillno`='".$fbillno."'",'id,docnum,applicant,fbillno,money');
              
                if($new_array['FDOCUMENTSTATUS']=='C'){
                    $payflow = $this->db->getone('[Q]c_fininfom_paymentflow',"`fbillno`='".$new_array['FBillNo']."'",'id,fbillno');
                    if(!$payflow ){
                        $paymentflow=array(
                            'docnum'        =>$datalist['docnum'],
                            'fbillno'        =>$new_array['FBillNo'],
                            'fpaytotalamountfor'        =>$new_array['FPAYTOTALAMOUNTFOR'],
                            'mid'        =>$datalist['id'],
                            'date'        =>substr($new_array['FPOSTDATE'],0,strpos($new_array['FPOSTDATE'], 'T')),
                            'create_time'        =>date("Y-m-d H:i:s"),
                        );
                        m('c_fininfom_paymentflow')->insert($paymentflow);

                    }



                    if($datalist['money']==$new_array['FPAYTOTALAMOUNTFOR']){
                        m('fininfom')->update('`status`=1',$datalist['id']);
                        $zfarr = array(
                            'status'        =>1,
                            'nowcourseid'       => 0,
                            'nowcheckid'       => NULL,
                            'nowcheckname'    => NULL,
                            'nstatustext'  => '尹再伟处理同意',
                        );
                        m('flow_bill')->update($zfarr,"`table`='fininfom' and  mid=".$datalist['id']);

                        $addarr = array(
                            'table'     => 'fininfom',
                            'mid'       => $datalist['id'],
                            'status' => 1,
                            'statusname'   => '同意',
                            'name'     => '出纳付款',
                            'courseid'  => 310,
                            'optdt'    => date("Y-m-d H:i:s"),
                            'explain'  => '系统自动确认',
                            'ip'        => '0.0.0.0',
                            'web'       =>'Chrome',
                            'checkname'    =>'尹再伟',
                            'checkid'    =>1085,
                            'modeid'    =>103,
                            'color'    =>'green',
                            'valid'    =>1,
                            'step'    =>5,
                            'qmimg'    =>NULL,
                            'iszb'    =>0
                        );
                        m('flow_log')->insert($addarr);
                        $docnum= $datalist['docnum'];
                        $withhold_cost = m('c_withhold_fininform')->getall("docnum='$docnum' and status =1", 'id,cost_id,uid,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' => $datalist['docnum'],
                            'account_balance' => $data['account_balance']-$vo['amount'],
                            'create_time'  =>date("Y-m-d H:i:s"),
                            'uid'  =>$vo['uid'],
                            );

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

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


                          $fund_detail=array(
                            'trans_numb' =>$datalist['docnum'],
                            'account' =>  $data['name'],
                            'toaccount' =>$datalist['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'  =>$vo['uid'],
                            );
                            m('c_fund_detail')->insert($fund_detail);
                         }
                     }

                }
            }
        }



    }

    public function finfybxaddAction(){
         $sql  = "select sericnum from [Q]erplog  where `table`='fininfom' and level =1 ";

        $dataarr = $this->db->getall($sql);
        foreach ($dataarr as $key => $value) {
            $fininfomlist = $this->db->getone('[Q]fininfom',"`docnum`='".$value['sericnum']."'");

            $cbxmid=substr($fininfomlist['cbxmid'],0,strpos($fininfomlist['cbxmid'], "（"));
            $data=$this->db->getone('oa_personfile',"name='".$fininfomlist['applicant']."'");
            $gonncode=$data['gonncode'];

            //明细
            $oa_fininfos=$this->db->getrows('oa_fininfos',"mid='".$fininfomlist['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]['F_KXType']['FNUMBER']="00";
                            $arr['FPAYAPPLYENTRY'][$k]['F_PAEZ_CBZX1']['FNUMBER']=$cbxmid;
                            $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(
         '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");
         $applicant=$fininfomlist['applicant'];//申请人
         $applydt=$fininfomlist['applydt'];//申请日期
         
         $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": "GS.BM.08"
                          },
                          "F_PAEZ_OADJBH": "123321",
                          "FDOCUMENTSTATUS": "Z",
                          "FCANCELSTATUS": "A",
                          "FMAINBOOKID": {
                              "FNUMBER": "PRE001"
                          },
                          "FIsCredit": false,
                          "FAPPLYORGID": {
                              "FNumber": "1000"
                          },
                          "FSETTLECUR": {
                              "FNUMBER": "PRE001"
                          },
                          "FISCARRYRATE": false,
                          "F_PAEZ_CBZX1": {
                              "FNUMBER": " GS.BJ.B1"
                          }
                       
                      }
                  }';
         $model=json_decode($data_model,true);

         
         $model['Model']['FDATE']=$applydt;
         $model['Model']['FDEPARTMENT']['FNumber']=self::dept($fininfomlist['applicationdpt']);
         $model['Model']['FCONTACTUNIT']['FNumber']=$gonncode;
         $model['Model']['F_PAEZ_OADJBH']=$fininfomlist['docnum'];
         $model['Model']['FRECTUNIT']['FNumber']=$gonncode;
         $model['Model']['FPAYAPPLYENTRY1']=$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);

        try {
              $result = self::invoke_add($cloudUrl,$post_content,$cookie_jar);
              $array = json_decode($result,true);
              if(empty($array)){
                  throw new Exception("付款申请单保存失败");
              }else{
                  throw new Exception("付款申请单保存成功");
              }
        } catch (Exception $e) {
                echo $e->getMessage();
        }
         // $num=$array['Result']['Number'];
         //  if($array['Result']['ResponseStatus']['IsSuccess']){
              
         //             $this->update("`fsrcbillno`='$num'", $this->rs['id']);
         //             $this->erplog($this->rs['docnum'],'fininfom','付款申请单保存成功',json_encode($array),date("Y-m-d H:i:s"),2,$num,$array['Result']['Id'],1);

         //    if($this->apply_submit($cloudUrl,$cookie_jar,$array['Result']['Id'],$array['Result']['Number'])){
               
         //             $this->erplog($this->rs['docnum'],'fininfom','付款申请单提交成功',json_encode($array),date("Y-m-d H:i:s"),2,$num,$array['Result']['Id'],2);
         //         }else{
                   
         //             $this->erplog($this->rs['docnum'],'fininfom','付款申请单提交失败',json_encode($array),date("Y-m-d H:i:s"),1,$num,$array['Result']['Id'],2);
         //         }
         //         if($this->apply_audit($cloudUrl,$cookie_jar,$array['Result']['Id'],$array['Result']['Number'])){
                   
         //             $this->erplog($this->rs['docnum'],'fininfom','付款申请单审核成功',json_encode($array),date("Y-m-d H:i:s"),2,$num,$array['Result']['Id'],3);
         //         }else{
                 
         //             $this->erplog($this->rs['docnum'],'fininfom','付款申请单审核失败',json_encode($array),date("Y-m-d H:i:s"),1,$num,$array['Result']['Id'],3);
         //         }
         //  }else{
         //             $this->erplog($this->rs['docnum'],'fininfom','付款申请单保存失败',json_encode($array),date("Y-m-d H:i:s"),1,$num,$array['Result']['Id'],1);
         //  }


        }
    }

   public static function dept($data)
    {
        $sql="  name= '$data'";
        $data = m('tmp_department')->getone($sql, 'id,number');//查询账户表成本中心id
        return $data['number'];
    }
   public function apply_submit($cloudUrl,$cookie_jar,$id,$number){
         $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 apply_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 getbxlx($name)
    {

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

    private function erplog($sericnum,$table,$name,$remark,$optdt,$level,$fbillno,$fbillnoid,$fbillno_type){
        $erp_log=array(
            'sericnum'=> $sericnum,
            'table'=>$table,
            'name' => $name,
            'remark' => $remark,
            'optdt'  =>$optdt,
            'level'=>$level,
            'fbillno'=>$fbillno,
            'fbillnoid'=>$fbillnoid,
            'fbillno_type'=>$fbillno_type,

        );

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

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


}