<?php

class flow_emfkClassModel extends flowModel
{
    const PAYMENT_STATUS = [
        0 => '待审核',
        1 => '未提交',
        2 => '审核中',
        3 => '已付款',
        4 => '已付款 缺发票',
        5 => '已付款 发票已上传',
        7 => '被驳回',
        8 => '已确收',
        9 => '审核失败',
    ];


    /**
     * 审核时触发
     * @param $zt 1同意 2拒绝
     * @param $sm
     */
    protected function flowcheckafter($zt, $sm){
        if($zt == 2){
            $this->updatestatus(5);
            $this->sendMess(0,9);
        }
            $flowid=$this->getflow();
           
            if($flowid['nowcheckid']=='1085'){


               $payee = $this->rs['payee'];//收款方
               $supplier = m('supplier')->getone("name = '$payee' ",'number');
                //明细
                $oa_fininfos=$this->db->getrows('oa_c_emfk_details',"mid='".$this->rs['id']."'");


                $arr=[];
                foreach ($oa_fininfos as $k=>  $value) {
                    foreach ($value as $key => $val) {
                        switch ($key) {
//                            case 'charge_type':
//
//                                $arr['FPAYBILLENTRY'][$k]['FCOSTID']['FNUMBER']=self::getbxlx($val);
//
//                                break;

                            case 'cbzxid':

                                $arr['FPAYBILLENTRY'][$k]['F_PAEZ_Cbzx']['FNUMBER']=$val;

                                 $arr['FPAYBILLENTRY'][$k]['F_XM_ID']['FNUMBER']=$val;

                                break;
                            case 'amount':

                                $arr['FPAYBILLENTRY'][$k]['FPAYTOTALAMOUNTFOR']=$val;
                                $arr['FPAYBILLENTRY'][$k]['FPAYAMOUNTFOR_E']=$val;
                                $arr['FPAYBILLENTRY'][$k]['FSETTLEPAYAMOUNTFOR']=$val;
                                $arr['FPAYBILLENTRY'][$k]['FREALPAYAMOUNTFOR_D']=$val;
                                $arr['FPAYBILLENTRY'][$k]['FPAYAMOUNT_E']=$val;
                                break;

                            default:
                                $arr['FPAYBILLENTRY'][$k]['FACCOUNTID']['FNumber']='10285000001001779';
                                $arr['FPAYBILLENTRY'][$k]['FSETTLETYPEID']['FNumber']='JSFS04_SYS';
                                $arr['FPAYBILLENTRY'][$k]['FPURPOSEID']['FNumber']='SFKYT001';

                                $arr['FPAYBILLENTRY'][$k]['FCostType']['FNUMBER']='CBLX0017';
                                $arr['FPAYBILLENTRY'][$k]['FCostModel']['FNUMBER']='00';
                                $arr['FPAYBILLENTRY'][$k]['F_KXType']['FNUMBER']='00';
                                $arr['FPAYBILLENTRY'][$k]['FENDDATE']=$this->rs['applydt'].' 00:00:00';
                                $arr['FPAYBILLENTRY'][$k]['FPOSTDATE']=$this->rs['applydt'].' 00:00:00';
                                $arr['FPAYBILLENTRY'][$k]['FOPPOSITEBANKACCOUNT']=$data['bank_code'];
                                $arr['FPAYBILLENTRY'][$k]['FOPPOSITECCOUNTNAME']=$data['bank_holder'];
                                $arr['FPAYBILLENTRY'][$k]['FOPPOSITEBANKNAME']=$data['open_bank_name'];
                                $arr['FPAYBILLENTRY'][$k]['FOpenAddressRec']=$data['open_address'];

                                break;
                        }
                    }
                }


                $cloudUrl = "http://36.110.39.211/k3cloud/";
                //登陆参数
                $data = array(
                   '5e64f6ff0bd47f',//帐套Id
                    // '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");
                $applicant=$this->rs['applicant'];//申请人
                $applicationdpt=$this->rs['applicationdpt'];//申请部门
                $applydt=$this->rs['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": "FKDLX08_SYS"
                            },
                            "FDATE": "2020-07-29 00:00:00",
                            "FCONTACTUNITTYPE": "BD_Supplier",
                            "FCONTACTUNIT": {
                                "FNumber": "GDGYS-0002"
                            },
                            "FRECTUNITTYPE": "BD_Supplier",
                            "FRECTUNIT": {
                                "FNumber": "GDGYS-0002"
                            },
                            "FISINIT": false,
                            "FCURRENCYID": {
                                "FNumber": "PRE001"
                            },
                            "F_YeWuLine": {
                            "FNUMBER": "001"
                            },
                            "FDepartment": {
                            "FNumber": "GS.BM.02.01"
                            },
                            "FEXCHANGERATE": 1.0,
                            "FSETTLERATE": 1.0,
                            "FSETTLEORGID": {
                                "FNumber": "1000"
                            },
                            "FDOCUMENTSTATUS": "Z",
                            "FCancelStatus": "A",
                            "FPAYORGID": {
                                "FNumber": "1000"
                            },
                            "FISSAMEORG": true,
                            "FIsCredit": false,
                            "FSETTLECUR": {
                                "FNUMBER": "PRE001"
                            },
                            "FIsWriteOff": false,
                            "FREALPAY": false,
                            "FISCARRYRATE": false,
                            "FSETTLEMAINBOOKID": {
                                "FNUMBER": "PRE001"
                            },
                            "F_PAEZ_OADJBH": "111111"
                          
                        }
                    }';
                $model=json_decode($data_model,true);


                $model['Model']['FDATE']=$applydt;
                $model['Model']['FCONTACTUNIT']['FNumber']=$supplier['number'];
                $model['Model']['F_PAEZ_OADJBH']=$this->rs['docnum'];;
                $model['Model']['FRECTUNIT']['FNumber']=$supplier['number'];
                $model['Model']['FPAYBILLENTRY']=$arr['FPAYBILLENTRY'];

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

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

                    $this->erplog($this->rs['docnum'],'c_emfk','保存成功',json_encode($array),date("Y-m-d H:i:s"),2,$num,$array['Result']['Id'],1);


                    if($this->emfk_submit($cloudUrl,$cookie_jar,$array['Result']['Id'],$array['Result']['Number'])){

                        $this->erplog($this->rs['docnum'],'c_emfk','提交成功',json_encode($array),date("Y-m-d H:i:s"),2,$num,$array['Result']['Id'],2);

                    }else{

                        $this->erplog($this->rs['docnum'],'c_emfk','提交失败',json_encode($array),date("Y-m-d H:i:s"),1,$num,$array['Result']['Id'],2);

                    }


                }else{

                    $this->erplog($this->rs['docnum'],'c_emfk','保存失败',json_encode($array),date("Y-m-d H:i:s"),1,$num,$array['Result']['Id'],1);
                    m('erplog')->insert($erp_log);
                }

            }




    }




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

    }

    /**
     * @param int $messType 动作
     * @param int $status 状态
     */
    private function sendMess($messType = 0,$status = 3){
        m('log')->addlog('电费付款','接口动作:'.$messType.'状态:'.$status,1);

        $url = getconfig('base_url'). 'v2/payment?key=';
        $key = substr(md5(getconfig('openkey').date('Y-m-d')),0,12);
        $url = $url.$key.'&action='.$messType; //接口地址
        $url .= '&numb='.$this->rs['docnum'];
        $url .= '&status='.$status;
        $url .= '&mes='.'';
        m('log')->addlog('电费付款','接口发送信息: url '.$url);

        $res = curlGet($url);
        m('log')->addlog('电费付款','接口返回信息:' .$res);

    }
    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;
    }

    //二级 或一级审批同意之后进行预扣款
    protected function flowcheckbefore($zt, $sm){
        $id=$this->rs['id'];
        $sql = " mid ='$id' and `table`='c_emfk' ";
        $flow_bill = m('flow_bill')->getone($sql,'allcheckid');
        $allcheckid=explode(',',$flow_bill['allcheckid']);
        $optionid = m('option')->getone("num = 'em_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'];
                    break;
                }
            }
        }

        //zt 1代表同意
        if($zt==1){
            $flowid=$this->getflow();

            if($flowid['nowcheckid']==$checkid){
                $data = m('c_emfk_details')->getall('mid='.$this->rs['id'], 'id,cbzxid,amount');
                foreach ($data as $key => $vo) {
                    $project=self::project($vo['cbzxid']);

                    $cbzx_code= self::dept($project['data'][0]['jz_cur_dept']);
                    $sql = " cost_id='$cbzx_code' and status = 1 and  is_default=1";
                    $cost = m('c_fund_account')->getone($sql, 'id,type,name,freeze_amount,account_balance');//查询账户表成本中心id

                    if($cost['type']=='1'){
                        if(($cost['account_balance']-$cost['freeze_amount'])<$vo['amount']){
                            return $cost['name']."余额不足";die;
                        }
                    }
                    $id=$cost['id'];

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

                    //修改冻结余额
                    $freeze = array(
                        'freeze_amount' => $cost['freeze_amount'] + $vo['amount'],
                    );

                    m('c_fund_account')->update($freeze, "`id`='$id'");
                }
            }

        }else{
            $docnum=$this->rs['docnum'];
            //将单据状态作废余额
            $withhold_cost = m('c_withhold_emfk')->getall("docnum='$docnum' and status =1", 'id,cost_id,amount');

            foreach ($withhold_cost as $key => $vo) {
                //减去冻结金额
                $project=self::project($vo['cost_id']);

                $cost_id= self::dept($project['data'][0]['jz_cur_dept']);

                $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' => 9,
            );
            m('c_withhold_emfk')->update($status, "docnum='$docnum'");
        }
    }


 
    public function emfk_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;

    }


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


}