<?php

namespace web\admin\ap;

class transfer {
    static function setwhere($db, $post) {
        $query = $post->get('query');
        $csql = new \ciy\sql('ap_transfer');
        $liid = objint($query, 'liid');
        if ($liid > 0)
            $csql->where('orderstatus', $liid);
        $val = objstr($query, 'id');
        if (!empty($val) && $val[0] == 'P')
            $csql->where('id', substr($val, 1));
        $csql->wherenumrange('amount', objstr($query, 'amount_1'), objstr($query, 'amount_2'), 100);
        $csql->wheredaterange('addtimes', objstr($query, 'addtimes'));
        $csql->where('thirdno like', objstr($query, 'thirdno'));
        $order = objstr($query, 'order', 'id desc');
        $csql->order($order);
        $query['order'] = $order;
        return [$query, $csql];
    }

    public static function json_list() {
        global $db;
        $rsuser = verifyfast();
        $post = new \ciy\post();
        list($where, $csql) = self::setwhere($db, $post);
        $pageno = $post->getint('pageno', 1);
        $pagecount = $post->getint('pagecount', 10);
        $csql->limit($pageno, $pagecount);
        $mainrowcount = $post->getint('count');
        $rows = $db->get($csql, $mainrowcount);
        if ($rows === false)
            return errjson($db->error);
        $ret = array('searchwhere' => $where, 'pageno' => $pageno, 'pagecount' => $pagecount, 'count' => $mainrowcount, 'list' => $rows);
        if ($post->getbool('field')) {
            $field = array();
            $fshow = $db->getfield($field, 'ap_transfer');
            foreach ($field as $fr => $v) {
                if (get('_' . $fr))
                    $field[$fr]['c'] = ',' . $field[$fr]['c'];
            }
            $fshow = fieldadd($fshow, $field, 0, '_btn', '操作');
            $ret['field'] = $field;
            $ret['fshow'] = $fshow;
        }
        if ($post->getbool('once')) {
            $ret['once'] = true;
            $input = array();
            $input[] = array('type' => 'input', 'form' => 'id', 'name' => '流水号', 'prop' => ' style="width:8em;"');
            $input[] = array('type' => 'num', 'form' => 'amount', 'name' => '金额', 'prop' => ' style="width:4em;"');
            $input[] = array('type' => 'daterange', 'form' => 'addtimes', 'name' => '创建时间');
            $input[] = array('type' => 'input', 'form' => 'thirdno', 'name' => '三方单号', 'prop' => ' style="width:8em;"');
            $ret['searchinput'] = $input;
        }
        return succjson($ret);
    }

    public static function json_checksign() {
        global $db;
        $post = new \ciy\post();
        $id = $post->getint('id');
        $csql = new \ciy\sql('ap_transfer');
        $csql->where('id', $id);
        $orderrow = $db->getone($csql);
        if (!is_array($orderrow))
            return errjson('数据不存在');
        $csql = new \ciy\sql('ap_api');
        $csql->where('id', $orderrow['apiid']);
        $apirow = $db->getone($csql);
        if (!is_array($apirow))
            return errjson('API不存在');
        $signs = array();
        $waitsignstr = 'amount=' . $orderrow['amount'] . ',addtimes=' . $orderrow['addtimes'];
        $signs[] = array('hash' => hash('sha256', $waitsignstr), 'sign' => $orderrow['signature']);
        $retsign = self::verifysign_api($apirow['pubkey'], $signs);
        if (is_string($retsign))
            return errjson($retsign);
        return succjson();
    }
    static function verifysign_api($signKey, $signs) {
        if (strpos($signKey, '-----BEGIN RSA PUBLIC KEY-----') === false && strpos($signKey, '-----BEGIN PUBLIC KEY-----') === false)
            $signKey = "-----BEGIN PUBLIC KEY-----\n" . wordwrap($signKey, 64, "\n") . "\n-----END PUBLIC KEY-----";

        foreach ($signs as $sign) {
            $signbin = hex2bin($sign['sign']);
            if ($signbin === false)
                return errjson('签名格式错误');
            $hashbin = hex2bin($sign['hash']);
            $result = openssl_verify($hashbin, $signbin, $signKey, OPENSSL_ALGO_SHA256);
            if ($result === 0)
                return '数字证书验签失败';
            else if ($result !== 1)
                return '数字证书验签错误:' . openssl_error_string();
            return true;
        }
    }
    public static function json_exportxls() {
        global $db;
        $rsuser = verifyfast();
        //if (nopower($db, $rsuser['id'], 'p e'))
        //    return errjson('您未被授权操作');
        $post = new \ciy\post();
        list($where, $csql) = self::setwhere($db, $post);
        $rows = $db->get($csql);
        if (count($rows) > 10000)
            return errjson('将导出' . count($rows) . '条，不建议超过1万条，请筛选缩小范围');
        $fields = array();
        $fields[] = array('style' => 'l', 'width' => 60,  'field' => 'id', 'name' => '行码');
        $fields[] = array('style' => 'l', 'width' => 100,  'field' => 'orderstatus', 'name' => '状态');
        $fields[] = array('style' => 'r', 'width' => 100,  'field' => 'amount', 'name' => '金额');
        $fields[] = array('style' => 'l', 'width' => 100,  'field' => 'addtimes', 'name' => '创建时间');
        $fields[] = array('style' => 'l', 'width' => 100,  'field' => 'uptimes', 'name' => '完成时间');
        $fields[] = array('style' => 'l', 'width' => 150,  'field' => 'thirdno', 'name' => '订单号');
        $fields[] = array('style' => 'l', 'width' => 150,  'field' => 'apiuser', 'name' => 'APIID');
        $fields[] = array('style' => 'l', 'width' => 150,  'field' => 'signature', 'name' => '签名');
        $code_orderstatus = getcatas($db, 'orderstatus');
        $datas = array();
        foreach ($rows as $row) {
            $dat = array();
            foreach ($fields as $field) {
                $field = $field['field'];
                $val = isset($row[$field]) ? $row[$field] : '';
                if ($field == 'id')
                    $val = enid($val);
                if ($field == 'orderstatus')
                    $val = ccode($code_orderstatus, $val);
                if ($field == 'amount')
                    $val = number_format($val / 100, 2);
                if ($field == 'addtimes')
                    $val = ($val == 0 ? '--' : date('Y-m-d H:i', $val));
                if ($field == 'uptimes')
                    $val = ($val == 0 ? '--' : date('Y-m-d H:i', $val));
                $dat[] = $val;
            }
            $datas[] = $dat;
        }
        $param = array();
        $param['field'] = $fields;
        $param['data'] = $datas;
        $param['sheetname'] = '数据报表';
        $param['titleheight'] = '25'; //列头高度
        $param['landscape'] = true; //横向打印
        $param['fixtopage'] = true; //打印整个工作表
        $param['toptitle'] = '转账单数据报表';
        $str = \ciy\excel::general_excel_xml($param);
        $filename = '';
        if (empty($filename))
            $filename = date('Y-m-d_H-i-s') . rand(1000, 9999);
        $filename .= '.xls';
        file_put_contents(PATH_WEB . 'ud/tmp/' . $filename, $str);
        return succjson(array('url' => '/ud/tmp/' . $filename));
    }
}
