<?php

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

class openemfkClassAction extends openapiAction
{
    public $data = [];
    public $subdata = [];
    public $model = '';

    const MODEL_NAME = 'emfk';
    const FK_NUMB_PREFIX = 'EM-FK-';
    const TABLE_NAME = 'c_emfk';
    const DETAILS_TABLE_NAME = 'c_emfk_details';
    const DB_PREFIX = 'oa';

    public function initAction()
    {
        //post方式接收接口数据
        //m('log')->addlog('电费付款','接收数据:'.$_POST['data']);
       if(!isset($_POST['data'])){
           $this->listAction();
       }

        $data = json_decode($_POST['data'], true);

        if (empty($data)) $this->showreturn([], $_POST['data'], '201');

        if (!empty($data['docnum'])) $this->data['docnum'] = $data['docnum']; //如果是编辑则携带编码
        $user = $this->getUser($data['uname']); //获取用户信息
        $data['applicant'] = $data['optname'] =  $user['name'];

        //m('log')->addlog('电费付款','用户:'.$user['name']);

        $this->subdata = $this->getSubData($data['details']);
        unset($data['details']);
        unset($data['uname']);

        $this->data = $data;

        //构建主表其他信息
        $this->data['applydt'] = $this->data['optdt'] = $data['date'] ?: date('Y-m-d');
        $this->data['uid'] = $this->data['optid'] = $user['id'];
        $this->data['docnum'] = $this->data['docnum'] ?: $this->getDocNum();
        $this->data['status'] = 0;
        $this->data['amount'] = $this->AmountSum();

    }

    //返回不存在的接口方法
    public function __call($name, $arguments)
    {
        $msg = $name . ' action not found';
        $this->showreturn([], $msg, '201');
    }

    //创建预付款单
    public function createAction()
    {
        $model = m(self::TABLE_NAME);
        $id =$model->insert($this->data);

        if ($id) {
            //插入子表数据
            $details = m(self::DETAILS_TABLE_NAME);

            foreach ($this->subdata as $sub) {
                $sub['mid'] = $id;
                $sub['comid'] = 1;
                $details->insert($sub);
            }

            //启动流程
            $this->goflow($id);
            $this->showreturn(['numb' => $this->data['docnum'], 'id' => $id], '插入数据成功', '200');
        } else $this->showreturn([], $model->getLastSql(), '201');
    }

    public function updateAction()
    {
        $mid = $this->getIdByDocNum($this->data['docnum']);
        if (!$mid) $this->showreturn([], '修改数据失败,不匹配的数据记录', '201');

        $where = 'id=' . $mid;
        unset($this->data['docnum']);
        $res = m(self::MODEL_NAME)->update($this->data, $where);
        if (!$res) $this->showreturn([], '修改数据失败,数据字段异常或字段不匹配', '201');

        $details = m(self::DETAILS_TABLE_NAME);
        //1.获取子表数据,子表数据必须要携带子表id
        //2.查询所有子表ID 如果子表ID存在于 记录中则是修改 否则是新增
        $scount = 0;
        foreach ($this->subdata as $k => $sub) {
            if (empty($sub['id'])) {   //插入操作
                $sub['mid'] = $mid;
                $sub['comid'] = 1;
                $details->insert($sub);
            } else {                //新增
                //如果已经存在的子表数据则修改
                if ($details->getone('id=' . $sub['id'])) {
                    $details->update($sub, 'id=' . $sub['id']);
                } else {
                    $sub['mid'] = $mid;
                    $sub['comid'] = 1;
                    $details->insert($sub);
                }
            }
            $scount++;
        }
        $this->showreturn([], '修改数据成功,子表数据成功修改' . $scount . '条记录', '200');
    }

    private function getUser($username)
    {
        $where = "email='" . $username . "@gonn.com.cn'";
        return $this->db->getone('oa_userinfo', $where);
    }

    private function getSubData($details = [])
    {
        $arr = [];
        foreach ($details as $k => $d) {
            if (!empty($d['id'])) $arr[$k]['id'] = $d['id'];
            $arr[$k]['charge_type'] = $d['charge_type'];
            $arr[$k]['amount'] = $d['amount'];
            $arr[$k]['cbzxid'] = $d['cbzxid'];
        }
        return $arr;
    }

    //子表金额求和
    private function AmountSum()
    {
        $sum = 0;
        foreach ($this->subdata as $v) {
            $sum += $v['amount'];
        }
        return $sum;
    }

    private function getDocNum()
    {
        $ext = self::FK_NUMB_PREFIX . date("Ymd"); //编号前缀
        $where = "`docnum` like '%" . $ext . "%'";
        $mode = m(self::TABLE_NAME);

        $data = $mode->getone($where, 'id,docnum', 'id desc');

        $num = '001'; //编号后缀

        if ($data) {
            $num = (int)substr($data['docnum'], strlen($ext)) + 1;
            if (strlen($num) == 2) {
                $num = '0' . $num;
            } else if (strlen($num) == 1) {
                $num = '00' . $num;
            }
        }
        return $ext . $num;
    }

    private function getIdByDocNum($docnum)
    {
        $data = m(self::TABLE_NAME)->getone("`docnum`='" . $docnum . "'", 'id,docnum');
        return $data['id'] ?: 0;
    }

    //启动流程
    private function goflow($id)
    {
        $mode = m("flow:" . self::MODEL_NAME);
        $mode->initdata(self::MODEL_NAME,$id);
        $mode->submit();
    }



    public function listAction(){

        $sql  = 'select id,fbillno,status from [Q]c_emfk  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(
                '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);
            $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']="FSRCBILLNO ="."'".$value['fbillno']."'";

            $data_model=json_encode($model);
            return $data_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]finifom_oayfk_paymentflow',"`fbillno`='".$new_array[$ke]['FBillNo']."'",'id,fbillno');
                        $fbillno=$new_array['FSRCBILLNO'];
                        $datalist = $this->db->getone('[Q]c_fininfom_oayfk',"`fbillno`='".$value['fbillno']."'",'id,fbillno,amountOfThisPayment');
                        if(!$payflow ){
                            $paymentflow=array(
                                'fsrcbillno'        =>$new_array[$ke]['FSRCBILLNO'],
                                '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'))
                            );
                            m('finifom_oayfk_paymentflow')->insert($paymentflow);

                        }
                    }
                }

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

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

                    $addarr = array(
                        'table'     => 'c_fininfom_oayfk',
                        '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);
                    echo '成功';
                }



            }else{

                $key = ['FSRCBILLNO','FBillNo','FDOCUMENTSTATUS','FPAYTOTALAMOUNTFOR','FPOSTDATE' ];
                $new_array = array();
                foreach($array as $k=>$v) {
                    $new_array= array_combine($key,$v);
                }
                $fbillno=$new_array['FSRCBILLNO'];
                $datalist = $this->db->getone('[Q]c_fininfom_oayfk',"`fbillno`='".$fbillno."'",'id,fbillno,amountOfThisPayment');
                if($new_array['FDOCUMENTSTATUS']=='C'){
                    $payflow = $this->db->getone('[Q]finifom_oayfk_paymentflow',"`fbillno`='".$new_array['FBillNo']."'",'id,fbillno');
                    if(!$payflow ){
                        $paymentflow=array(
                            'fsrcbillno'        =>$new_array['FSRCBILLNO'],
                            'fbillno'        =>$new_array['FBillNo'],
                            'fpaytotalamountfor'        =>$new_array['FPAYTOTALAMOUNTFOR'],
                            'mid'        =>$datalist['id'],
                            'date'        =>substr($new_array['FPOSTDATE'],0,strpos($new_array['FPOSTDATE'], 'T'))
                        );
                        m('finifom_oayfk_paymentflow')->insert($paymentflow);

                    }



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

                        $addarr = array(
                            'table'     => 'c_fininfom_oayfk',
                            '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);

                        echo "成功1";
                    }
                }
            }
//
        }



    }

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


}