<?php

namespace web\admin\ap;

class api {
    static function setwhere($db, $post) {
        $query = $post->get('query');
        $csql = new \ciy\sql('ap_api');
        $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_api');
            foreach ($field as $fr => $v) {
                if (get('_' . $fr))
                    $field[$fr]['c'] = ',' . $field[$fr]['c'];
            }
            $fshow = fieldadd($fshow, $field, 0, '_btn', '操作');
            $fshow = fieldadd($fshow, $field, -1, 'msg', '接入检测');
            $ret['field'] = $field;
            $ret['fshow'] = $fshow;
        }
        if ($post->getbool('once')) {
            $ret['once'] = true;
            $input = array();
            $ret['searchinput'] = $input;
        }
        return succjson($ret);
    }
    public static function json_addnew() {
        global $db;
        $rsuser = verifyfast();
        //if (nopower($db, $rsuser['id'], 'p u'))
        //    return errjson('您未被授权操作');
        $post = new \ciy\post();
        $csql = new \ciy\sql('ap_api');
        $csql->where('addtimes>', time() - 86400 * 7);
        $csql->column('id');
        $chkid = toint($db->get1($csql));
        if ($chkid > 0)
            return errjson('一周内只能建立一条API通道');
        $secret = randstr(10) . randstr(10);
        try {
            $db->begin();
            $updata = array();
            $updata['apisecret'] = $secret;
            $updata['ips'] = '';
            $updata['addtimes'] = tostamp();
            $updata['pubkey'] = '';
            $csql = new \ciy\sql('ap_api');
            if ($db->insert($csql, $updata) === false)
                throw new \Exception('新增失败:' . $db->error);
            $updata['id'] = $db->insert_id();
            $db->commit();
        } catch (\Exception $ex) {
            $db->rollback();
            savelogfile('err_db', $ex->getMessage());
            return errjson($ex->getMessage());
        }
        $ret['data'] = $updata;
        return succjson($ret);
    }
    public static function json_rekey() {
        global $db;
        $rsuser = verifyfast();
        //if (nopower($db, $rsuser['id'], 'p u'))
        //    return errjson('您未被授权操作');
        $post = new \ciy\post();
        $id = $post->getint('id');
        $secret = randstr(10) . randstr(10);
        try {
            $db->begin();
            $updata = array();
            $updata['apisecret'] = $secret;
            $csql = new \ciy\sql('ap_api');
            $csql->where('id', $id);
            if ($db->update($csql, $updata) === false)
                throw new \Exception('新增失败:' . $db->error);
            $db->commit();
        } catch (\Exception $ex) {
            $db->rollback();
            savelogfile('err_db', $ex->getMessage());
            return errjson($ex->getMessage());
        }
        $ret['secret'] = $secret;
        return succjson($ret);
    }
    public static function json_edit() {
        global $db;
        $rsuser = verifyfast();
        //if (nopower($db, $rsuser['id'], 'p u'))
        //    return errjson('您未被授权操作');
        $post = new \ciy\post();
        $id = $post->getint('id');
        $ips = explode("\n", $post->get('ips'));
        $iparr = array();
        foreach ($ips as $ip) {
            $ip = trim($ip);
            if (empty($ip))
                continue;
            if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE))
                return errjson('公网IP格式错误:' . $ip);
            $iparr[] = $ip;
        }
        try {
            $db->begin();
            $updata = array();
            $updata['ips'] = implode("\n", $iparr);
            $csql = new \ciy\sql('ap_api');
            $csql->where('id', $id);
            if ($db->update($csql, $updata) === false)
                throw new \Exception('更新失败:' . $db->error);
            $updata['id'] = $id;
            //savelogdb($db, $rsuser['id'], 'ap_api', $datarow, $updata);
            $db->commit();
        } catch (\Exception $ex) {
            $db->rollback();
            savelogfile('err_db', $ex->getMessage());
            return errjson($ex->getMessage());
        }
        $ret['data'] = $updata;
        return succjson($ret);
    }
    public static function json_pubkey() {
        global $db;
        $rsuser = verifyfast();
        //if (nopower($db, $rsuser['id'], 'p u'))
        //    return errjson('您未被授权操作');
        $post = new \ciy\post();
        $pubkey = $post->get('pubkey');
        $id = $post->getint('id');
        $oridata = $post->get('oridata');
        $hash = $post->get('hash');
        $pubkey = $post->get('pubkey');
        $csql = new \ciy\sql('ap_api');
        $csql->where('id', $id);
        $apirow = $db->getone($csql);
        if (!is_array($apirow))
            return errjson('API通道不存在');
        if (!empty($apirow['pubkey']))
            return errjson('该API通道已设置公钥');
        $publickey = $pubkey;
        if (strpos($publickey, '-----BEGIN PUBLIC KEY-----') === false)
            $publickey = "-----BEGIN PUBLIC KEY-----\n" . wordwrap($publickey, 64, "\n") . "\n-----END PUBLIC KEY-----";

        $pubkey = str_replace('-----BEGIN PUBLIC KEY-----', '', $pubkey);
        $pubkey = str_replace('-----END PUBLIC KEY-----', '', $pubkey);
        $pubkey = str_replace(["\r", "\n"], '', $pubkey);
        $pubkey = trim($pubkey);
        $csql = new \ciy\sql('ap_api');
        $csql->where('pubkey', $pubkey);
        $chkrow = $db->getone($csql);
        if (is_array($chkrow))
            return errjson('该公钥已存在');
        $sign = $post->get('sign');
        $timestamp = toint(substr($oridata, 3));
        if (abs(time() - $timestamp) > 300)
            return errjson('请在5分钟内完成操作');

        if (sha256($oridata) != $hash)
            return errjson('hash数据校验失败');
        $signbin = hex2bin($sign);
        if ($signbin === false)
            return errjson('签名格式错误');
        $hashbin = hex2bin($hash);
        if ($hashbin === false)
            return errjson('hash格式错误');

        $result = openssl_verify($hashbin, $signbin, $publickey, OPENSSL_ALGO_SHA256);
        if ($result === 0)
            return errjson('验签失败');

        else if ($result !== 1)
            return errjson('验签错误:' . openssl_error_string());
        $hash = strtoupper($hash);
        try {
            $db->begin();
            $updata = array();
            $updata['pubkey'] = $pubkey;
            $csql = new \ciy\sql('ap_api');
            $csql->where('id', $id);
            if ($db->update($csql, $updata) === false)
                throw new \Exception('更新失败:' . $db->error);
            $updata['id'] = $id;
            //savelogdb($db, $rsuser['id'], 'ap_api', $datarow, $updata);
            $db->commit();
        } catch (\Exception $ex) {
            $db->rollback();
            savelogfile('err_db', $ex->getMessage());
            return errjson($ex->getMessage());
        }
        $ret['data'] = $updata;
        return succjson($ret);
    }

    public static function json_del() {
        global $db;
        $rsuser = verifyfast();
        //if (nopower($db, $rsuser['id'], 'p d'))
        //    return errjson('您未被授权操作');
        $post = new \ciy\post();
        $ids = $post->get('ids');
        if (empty($ids))
            return errjson('请选择至少一条');
        $csql = new \ciy\sql('ap_api');
        $csql->where('id in', $ids);
        $rows = $db->get($csql);
        $vids = array();
        try {
            $db->begin();
            foreach ($rows as $row) {
                $delid = $row['id'];
                delcheck($db, $delid, 'ap_transfer', 'apiid', '转账订单');
                //delall($db, $delid, 'tablexx', 'xxid', '运动员');  //deltimeall
                delme($db, $delid, 'ap_api');
                $vids[] = $delid;
            }
            $db->commit();
        } catch (\Exception $ex) {
            $db->rollback();
            savelogfile('err_db', $ex->getMessage());
            return errjson($ex->getMessage());
        }
        $ret['ids'] = $vids;
        return succjson($ret);
    }
}
