<?php

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

class openoafkClassAction extends openapiAction
{




    public function listAction(){

        $sql  = 'select id,fbillno,status from [Q]c_fininfom_oafk  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_fk_paymentflow',"`fbillno`='".$new_array[$ke]['FBillNo']."'",'id,fbillno');
                        $fbillno=$new_array['FBillNo'];
                        $datalist = $this->db->getone('[Q]c_fininfom_oafk',"`fbillno`='".$value['fbillno']."'",'id,docnum,payee,fbillno,amountOfThisPayment');

                            $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_fk_paymentflow')->insert($paymentflow);


                    }
                }

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

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

                    $addarr = array(
                        'table'     => 'c_fininfom_oafk',
                        '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')->getall("docnum='$docnum' and status =1", 'id,uid,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' => $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' =>$docnum,
                        'account' =>  $data['name'],
                        'toaccount' =>$datalist['payee'],
                        'trans_amount' =>$vo['amount'],
                        'business_type' =>8,
                        '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]c_fininfom_oafk',"`fbillno`='".$fbillno."'",'id,docnum,payee,fbillno,amountOfThisPayment');
                if($new_array['FDOCUMENTSTATUS']=='C'){
                    $payflow = $this->db->getone('[Q]c_fk_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_fk_paymentflow')->insert($paymentflow);

                    }



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

                        $addarr = array(
                            'table'     => 'c_fininfom_oafk',
                            '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')->getall("docnum='$docnum' and status =1", 'id,uid,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' => $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' =>$docnum,
                        'account' =>  $data['name'],
                        'toaccount' =>$datalist['payee'],
                        'trans_amount' =>$vo['amount'],
                        'business_type' =>8,
                        '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 static function dept($data)
    {
        $sql="  id= '$data'";
        $cbzxid = m('tmp_department')->getone($sql, 'id,cost');//查询账户表成本中心id
        return $cbzxid['cost'];
    }


    public static function project($project_code){

        $url = getconfig('base_url'). 'v2/project/list?key=';
        $key = substr(md5(getconfig('openkey').date('Y-m-d')),0,12);
        $url = $url.$key;
        $url .= '&project_code='.$project_code;
        $res = json_decode(curlGet($url),true);
        return $res;
    }

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


}