<?php

class flow_oayfkClassModel extends flowModel

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

protected function flowcheckafter($zt, $sm){
    $flowid=$this->getflow();
   
    if($flowid['nowcheckid']=='1085'){
       


    }




}


 static function getkxlx($name)
    {

        $data = m('option')->getone("num='kxtype'", 'id,name');
        $kxlxlist = m('option')->getone("pid='".$data['id']."' and  name='".$name."'", 'name,num');
        return $kxlxlist['num'];
    }
     static function getorg($name)
    {

        $data = m('option')->getone("num='organization'", 'id,name');
        $orglist = m('option')->getone("pid='".$data['id']."' and  name='".$name."'", 'name,num');
        return $orglist['num'];
    }
  public static function dept($data)
    {
        $sql="  name= '$data'";
        $data = m('tmp_department')->getone($sql, 'id,number');//查询账户表成本中心id
        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);

    }

    //二级 或一级审批同意之后进行预扣款
    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']);
        $optionid = m('option')->getone("num = 'oayfk_manager' ",'id');
        $optionid=$optionid['id'];

        $option = m('option')->getall("pid = '$optionid' 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 = '$optionid' 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 $v){
                    if(!isset($ret[$v['cbzx_code']])){
                        $ret[$v['cbzx_code']] = $v;
                    }else{
                        $ret[$v['cbzx_code']]['charge_amount'] += $v['charge_amount'];
                    }
                }
               $ret = array_values($ret);
              foreach ($ret 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,name,type,freeze_amount,account_balance');//查询账户表成本中心
                             
                 if(($cost['account_balance']-$cost['freeze_amount'])<$vo['charge_amount']){
                     return $cost['name']."余额不足";die;
                 }
               
              }
              foreach ($data as $ke => $ve) {
                $cbzx_code=$ve['cbzx_code'];
                $sql = " cost_id='$cbzx_code' and status = 1 and  is_default=1";
                $cost = m('c_fund_account')->getone($sql, 'id,name,type,freeze_amount,account_balance');//查询账户表成本中心
                $id=$cost['id'];

                 $c_withhold = array(
                    'fund_account_id' => $id,
                    'docnum' => $this->rs['docnum'],
                    'cost_id' => $ve['cbzx_code'],
                    'amount' =>  $ve['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'] + $ve['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 $v){
                    if(!isset($ret[$v['cbzx_code']])){
                        $ret[$v['cbzx_code']] = $v;
                    }else{
                        $ret[$v['cbzx_code']]['charge_amount'] += $v['charge_amount'];
                    }
                }
               $ret = array_values($ret);
              foreach ($ret 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,name,type,freeze_amount,account_balance');//查询账户表成本中心 
                 if(($cost['account_balance']-$cost['freeze_amount'])<$vo['charge_amount']){
                     return $cost['name']."余额不足";die;
                 }
              
              }

              foreach ($data as $ke => $ve) {
                $cbzx_code=$ve['cbzx_code'];
                $sql = " cost_id='$cbzx_code' and status = 1 and  is_default=1";
                $cost = m('c_fund_account')->getone($sql, 'id,name,type,freeze_amount,account_balance');//查询账户表成本中心 
                $id=$cost['id'];
                $c_withhold = array(
                    'fund_account_id' => $id,
                    'docnum' => $this->rs['docnum'],
                    'cost_id' => $ve['cbzx_code'],
                    'amount' =>  $ve['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'] + $ve['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'");
         }
     }
    






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

        $data_model ="{
             'CreateOrgId': 0,
             'Numbers': [],
             'Ids': $id,
             'SelectedPostId': 0
         }";
        $data = array(
            'AP_PAYBILL',//业务对象标识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;

    }



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

}