<?php

namespace web\admin\demo;

class safeop {
    static function setwhere($db, $post) {
        $query = $post->get('query');
        $csql = new \ciy\sql('ap_transfer');
        $liid = objint($query, 'liid');
        if ($liid > 0)
            $csql->where('accounttype', $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->where('tranaccount like', objstr($query, 'tranaccount'));
        $csql->where('tranname like', objstr($query, 'tranname'));
        $csql->where('tranidid like', objstr($query, 'tranidid'));
        $csql->where('memo like', objstr($query, 'memo'));
        $csql->wheredaterange('addtimes', objstr($query, 'addtimes'));
        $csql->where('apiuser', objstr($query, 'apiuser'));
        $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);
        $csql->where('orderstatus', 10);
        $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('where' => $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'];
                if ($fr == 'merchantid')
                    $field[$fr]['c'] = ',' . $field[$fr]['c'];
            }
            $field['orderstatus']['c'] = '';
            $field['fee']['c'] = '';
            $field['wano']['c'] = '';
            $field['uptimes']['c'] = '';
            $field['orderno']['c'] = '';
            $field['pubkeyid']['c'] = '';
            $field['signtimes']['c'] = '';
            $field['tranreceipt']['c'] = '';
            $field['errmsg']['c'] = '';
            $ret['field'] = $field;
            $ret['fshow'] = $fshow;
        }
        if ($post->getbool('once')) {
            $ret['once'] = array();
            $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' => 'input', 'form' => 'tranaccount', 'name' => '账号', 'prop' => ' style="width:8em;"');
            $input[] = array('type' => 'input', 'form' => 'tranname', 'name' => '姓名', 'prop' => ' style="width:8em;"');
            $input[] = array('type' => 'input', 'form' => 'tranidid', 'name' => '身份证号', 'prop' => ' style="width:8em;"');
            $input[] = array('type' => 'input', 'form' => 'memo', 'name' => '备注', 'prop' => ' style="width:8em;"');
            $input[] = array('type' => 'daterange', 'form' => 'addtimes', 'name' => '创建时间');
            $input[] = array('type' => 'select', 'form' => 'apiuser', 'name' => '操作人', 'all' => '全部', 'select' => 'meruser');
            $ret['once']['input'] = $input;
            $csql = new \ciy\sql('hf_merchantbase');
            $csql->where('id', $rsuser['s_b']);
            $ret['once']['merchant'] = $db->getone($csql);
            $csql = new \ciy\sql('hf_merchantpubkey');
            $csql->where('merchantid', $rsuser['s_b']);
            $ret['once']['hf_merchantpubkey'] = $db->get($csql);
            // if($ret['once']['merchant']['safecase'] > 10){
            //     $csql = new \ciy\sql('hf_merchantuser');
            //     $csql->where('id', $ret['once']['merchant']['s_b']);
            //     $ret['once']['merchant'] = $db->getone($csql);

            // }
        }
        return succjson($ret);
    }
    public static function json_update() {
        global $db;
        $rsuser = verifyfast();
        //if (nopower($db, $rsuser['id'], 'p u'))
        //    return errjson('您未被授权操作');
        $csql = new \ciy\sql('hf_merchantbase');
        $csql->where('id', $rsuser['s_b']);
        $merchantrow = $db->getone($csql);
        $post = new \ciy\post();
        $id = $post->getint('id');
        $data = array();
        $data['accounttype'] = $post->getint('accounttype');
        $data['amount'] = $post->getint('amount');
        $data['tranaccount'] = $post->get('tranaccount');
        $data['tranname'] = $post->get('tranname');
        $data['tranidid'] = $post->get('tranidid');
        $data['memo'] = $post->get('memo');
        $retchk = check_transtr($data['amount'], $data['accounttype'], $data['tranaccount'], $data['tranname'], $data['tranidid'], $data['memo'], $merchantrow['safecase']);
        if (is_string($retchk))
            return errjson($retchk);
        if ($id > 0) {
            $csql = new \ciy\sql('ap_transfer');
            $csql->where('merchantid', $rsuser['s_b']);
            $csql->where('id', $id);
            $datarow = $db->getone($csql);
            if (!is_array($datarow))
                return errjson('数据不存在');
        }
        try {
            $db->begin();
            $updata = self::updatedata($db, $rsuser, $id, $data, $merchantrow);
            $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_multiedit() {
        global $db;
        $rsuser = verifyfast();
        //if (nopower($db, $rsuser['id'], 'p u'))
        //    return errjson('您未被授权操作');
        $csql = new \ciy\sql('hf_merchantbase');
        $csql->where('id', $rsuser['s_b']);
        $merchantrow = $db->getone($csql);
        $post = new \ciy\post();
        $count = $post->getint('count');
        $datas = array();
        for ($i = 0; $i < $count; $i++) {
            if ($post->get('accounttype_' . $i) == '')
                continue;
            $data = array();
            $data['accounttype'] = $post->getint('accounttype_' . $i);
            $data['accounttype'] = ($data['accounttype'] == 1 ? 20 : 10);
            $data['amount'] = $post->getint('amount_' . $i);
            $data['tranaccount'] = $post->get('tranaccount_' . $i);
            $data['tranname'] = $post->get('tranname_' . $i);
            $data['tranidid'] = $post->get('tranidid_' . $i);
            $data['memo'] = $post->get('memo_' . $i);
            $retchk = check_transtr($data['amount'], $data['accounttype'], $data['tranaccount'], $data['tranname'], $data['tranidid'], $data['memo'], $merchantrow['safecase']);
            if (is_string($retchk))
                return errjson('第' . ($i + 1) . '行，' . $retchk);
            $datas[] = $data;
        }
        try {
            $db->begin();
            foreach ($datas as $data) {
                self::updatedata($db, $rsuser, 0, $data, $merchantrow);
            }
            $db->commit();
        } catch (\Exception $ex) {
            $db->rollback();
            savelogfile('err_db', $ex->getMessage());
            return errjson($ex->getMessage());
        }
        return succjson();
    }
    static function updatedata($db, $rsuser, $id, $data, $merchantrow) {
        $updata = array();
        $updata['amount'] = $data['amount'];
        $updata['accounttype'] = $data['accounttype'];
        $updata['tranaccount'] = $data['tranaccount'];
        $updata['tranname'] = $data['tranname'];
        $updata['tranidid'] = $data['tranidid'];
        $updata['memo'] = $data['memo'];
        $updata['apiuser'] = $rsuser['id'];
        $csql = new \ciy\sql('ap_transfer');
        if ($id > 0) {
            $csql->where('id', $id);
            if ($db->update($csql, $updata) === false)
                throw new \Exception('更新失败:' . $db->error);
        } else {
            $updata['providerid'] = $rsuser['s_a'];
            $updata['merchantid'] = $rsuser['s_b'];
            $updata['thirdno'] = '';
            $updata['orderstatus'] = 10;
            $updata['iswa'] = $merchantrow['bwa'];
            $updata['wano'] = '';
            $updata['addtimes'] = tostamp();
            $updata['signtimes'] = 0;
            $updata['uptimes'] = 0;
            $updata['orderno'] = '';
            $updata['payfundno'] = '';
            $updata['signature'] = '';
            $updata['pubkeyid'] = 0;
            $updata['fee'] = 0;
            $updata['tranreceipt'] = 10;
            $updata['errmsg'] = '';
            if ($db->insert($csql, $updata) === false)
                throw new \Exception('新增失败:' . $db->error);
            $id = $db->insert_id();
        }
        $updata['id'] = $id;
        return $updata;
    }

    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_transfer');
        $csql->where('merchantid', $rsuser['s_b']);
        $csql->where('id in', $ids);
        $rows = $db->get($csql);
        $vids = array();
        try {
            $db->begin();
            foreach ($rows as $row) {
                if ($row['orderstatus'] != 10)
                    continue;
                $delid = $row['id'];
                //delcheck($db, $delid, 'tablexx', 'xxid', '管理员');
                //delall($db, $delid, 'tablexx', 'xxid', '运动员');  //deltimeall
                delme($db, $delid, 'ap_transfer');
                $vids[] = $delid;
            }
            $db->commit();
        } catch (\Exception $ex) {
            $db->rollback();
            savelogfile('err_db', $ex->getMessage());
            return errjson($ex->getMessage());
        }
        $ret['ids'] = $vids;
        return succjson($ret);
    }

    public static function json_getdopay() {
        global $db;
        $rsuser = verifyfast();
        $csql = new \ciy\sql('hf_merchantbase');
        $csql->where('id', $rsuser['s_b']);
        $merchantrow = $db->getone($csql);
        $csql = new \ciy\sql('ap_transfer');
        $csql->where('merchantid', $rsuser['s_b']);
        $csql->where('orderstatus', 10);
        $orderrows = $db->get($csql);
        $ret['datas'] = array();
        $money = 0;
        foreach ($orderrows as $orderrow) {
            $money += $orderrow['amount'];
            $ret['datas'][] = array(
                'id' => $orderrow['id'],
                'hash' => hash('sha256', signorder($orderrow))
            );
        }
        $ret['total'] = count($orderrows);
        $ret['money'] = $money;
        $ret['safecase'] = $merchantrow['safecase'];
        if ($ret['safecase'] > 0) {
            $csql = new \ciy\sql('hf_merchantuser');
            $csql->where('id', $rsuser['id']);
            $userrow = $db->getone($csql);
            if ($userrow['pubkeyid'] > 0) {
                $csql = new \ciy\sql('hf_merchantpubkey');
                $csql->where('id', $userrow['pubkeyid']);
                $csql->where('safecase', $merchantrow['safecase']);
                $pubkeyrow = $db->getone($csql);
                $ret['pubkey'] = $pubkeyrow['pubkey'];
            }
        }
        return succjson($ret);
    }
    public static function json_dopay() {
        global $db;
        $rsuser = verifyfast();
        $post = new \ciy\post();
        //if (nopower($db, $rsuser['id'], 'p d'))
        //    return errjson('您未被授权操作');
        $csql = new \ciy\sql('hf_merchantuser');
        $csql->where('id', $rsuser['id']);
        $userrow = $db->getone($csql);
        if (empty($userrow['password']))
            return errjson('请先设置初始登录密码');
        $csql = new \ciy\sql('hf_merchantalipaycharge');
        $csql->where('merchantid', $userrow['merchantid']);
        $csql->where('addtimes<', time() - 60);
        $csql->where('orderstatus<100');
        if (toint($db->get1($csql)) > 0)//检查商户余额，结合本次下单金额与手续费欠费金额，是否低于，低于提示。
            return errjson('有未结算的手续费，请稍后下单，请稍后下单或检查账户余额');
        $csql = new \ciy\sql('hf_merchantbase');
        $csql->where('id', $userrow['merchantid']);
        $merchantrow = $db->getone($csql);
        if (!is_array($merchantrow))
            return errjson('商户不存在');
        $tp = date('H') * 3600 + date('i') * 60 + date('s') + 1;
        if ($merchantrow['stpt'] < $merchantrow['endpt']) {
            if ($tp < $merchantrow['stpt'] || $tp > $merchantrow['endpt'])
                return errjson('当前时间不在服务时间范围内');
        } else {
            if ($tp < $merchantrow['stpt'] && $tp > $merchantrow['endpt'])
                return errjson('当前时间不在服务时间范围内');
        }
        if ($merchantrow['saasstatus'] != 10)
            return errjson('商户已被暂停服务');
        $csql = new \ciy\sql('hf_providerbase');
        $csql->where('id', $merchantrow['providerid']);
        $providerrow = $db->getone($csql);
        if (!is_array($providerrow))
            return errjson('服务商不存在');
        if ($providerrow['providerstatus'] != 10)
            return errjson('转账服务暂停，请联系服务商!');
        if ($providerrow['depositmoney'] <= 0)
            return errjson('转账服务暂停，请联系服务商');
        $signs = $post->get('sign');
        if ($merchantrow['safecase'] == 10) {
            if (empty($userrow['password2']))
                return errjson('请先在右上角下拉菜单中，设置安全密码');
            $authtime = $post->getint('auth');
            if (abs($authtime / 1000 - tostamp()) > 300) {
                return errjson('您的本地时间与服务器时间相差超过5分钟，请调整本机时间。<br/>服务器时间: ' . date('Y-m-d H:i:s') . '<br/>您本机时间: ' . date('Y-m-d H:i:s', $authtime / 1000));
            }
            if ($post->get('pass') != sha512($userrow['password2'] . $authtime)) {
                sleep(2);
                return errjson('安全密码错误');
            }
            sleep(1);
        } else {
            $csql = new \ciy\sql('hf_merchantpubkey');
            $csql->where('id', $userrow['pubkeyid']);
            $pubkeyrow = $db->getone($csql);
            if (!is_array($pubkeyrow))
                return errjson('未找到数字证书');
            if ($merchantrow['safecase'] == 20) {
                $retsign = verifysign_web3($pubkeyrow['pubkey'], $signs);
                if (is_string($retsign))
                    return errjson($retsign);
            }
            if ($merchantrow['safecase'] == 30) {
                $retsign = verifysign_vn($pubkeyrow['pubkey'], $signs);
                if (is_string($retsign))
                    return errjson($retsign);
            }
        }
        try {
            $db->begin();
            foreach ($signs as $sign) {
                $updata = array();
                $updata['orderstatus'] = 20;
                $updata['apiuser'] = $rsuser['id'];
                if ($merchantrow['safecase'] > 10) {
                    $updata['signtimes'] = tostamp();
                    $updata['signature'] = $sign['sign'];
                    $updata['pubkeyid'] = $userrow['pubkeyid'];
                }
                $csql = new \ciy\sql('ap_transfer');
                $csql->where('id', $sign['id']);
                $csql->where('orderstatus', 10);
                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());
        }
        return succjson();
    }


    public static function json_importxls_in() {
        global $db;
        $rsuser = verifyfast();
        //if (nopower($db, $rsuser['id'], 'p i'))
        //    return errjson('您未被授权操作');
        $post = new \ciy\post();
        $file = PATH_WEB . '/ud' . $post->get('file');
        if (!file_exists($file))
            return errjson('文件不存在');
        require_once PATH_ROOT . '../libs/phpoffice/autoload.php';
        $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file);
        $sheet = $spreadsheet->getActiveSheet();
        $datas = $sheet->toArray('', true, true, false);
        $datacnt = count($datas);
        if ($datacnt < 2)
            return errjson('数据为空');
        $html = '';
        $headsn = array();
        $headsn[] = '行码.id';
        $headsn[] = '账号类型.accounttype';
        $headsn[] = '金额.amount';
        $headsn[] = '账号.tranaccount';
        $headsn[] = '姓名.tranname';
        $headsn[] = '身份证号.tranidid';
        $headsn[] = '备注.memo';
        $xlsidx = 1;
        if (empty($datas[0][count($headsn) - 1]))
            $xlsidx = 2;
        $heads = array();
        foreach ($headsn as $_head) {
            $hd = explode('.', $_head);
            if (count($hd) < 2)
                continue;
            $heads[] = array(
                'idx' => array_search($hd[0], $datas[$xlsidx - 1]),
                'fld' => $hd[1],
                'name' => $hd[0]
            );
        }
        $code_accounttype = getcatas($db, 'accounttype');
        $csql = new \ciy\sql('hf_merchantbase');
        $csql->where('id', $rsuser['s_b']);
        $merchantrow = $db->getone($csql);
        $html .= '<div class="table" style="width: 100%;height: calc(100% - 2.2em);overflow: auto;">';
        $html .= '<table><tbody><tr>';
        $html .= '<th>#</th>';
        foreach ($heads as $arr) {
            $html .= '<th>' . $arr['name'] . '</th>';
        }
        $html .= '</tr>';
        $cnt = 0;
        $uniques = array();
        $id = 0;
        for ($rowidx = $xlsidx; $rowidx < $datacnt; $rowidx++) {
            $bfull = false;
            foreach ($datas[$rowidx] as $dat) {
                if (empty($dat))
                    continue;
                $bfull = true;
                break;
            }
            if (!$bfull)
                continue;
            $lineidx = $rowidx - $xlsidx + 1;
            $hrhtml = '';
            $firsthtml = '<td><div>' . $lineidx . '</div></td>';
            $bempty = true;
            $unqs = array();
            $csql = new \ciy\sql('ap_transfer');
            $data = array();
            foreach ($heads as $arr) {
                $name = $arr['name'];
                $errmsg = ''; //数据有误，显示红色说明
                $showdat = ''; //显示在表格中的数据
                if ($arr['idx'] > -1)
                    $showdat = trim($datas[$rowidx][$arr['idx']]);
                if ($showdat == '--')
                    $showdat = '';
                $value = $showdat; //在表单中的数据(转换后)
                $ext = ''; //扩展表单
                if ($name == '行码') {
                    if (empty($showdat)) {
                        $value = 0;
                        $showdat = '<kbd>新增</kbd>';
                    } else {
                        $id = deid($showdat);
                        if ($id == 0)
                            $errmsg = $name . '解析错误';
                        else {
                            $csqlchk = new \ciy\sql('ap_transfer');
                            $csqlchk->where('id', $id);
                            $chkrow = $db->getone($csqlchk);
                            if (!is_array($chkrow))
                                $errmsg = $name . '在数据库中不存在';
                            if ($chkrow['orderstatus'] != 10)
                                $errmsg = $name . '状态错误';
                            $value = $id;
                        }
                    }
                } else if ($name == '账号类型') {
                    if (empty($showdat)) {
                        $errmsg = $name . '为必填项';
                    } else {
                        $value = dcode($code_accounttype, $showdat);
                        $data['accounttype'] = $data;
                        if ($value == -1)
                            $errmsg = $name . '文字与系统数据不匹配';
                    }
                } else if ($name == '金额') {
                    $showdat = str_replace(',', '', $showdat);
                    if (!is_numeric($showdat))
                        $errmsg = $name . '不是数字';
                    else
                        $value = toint((float)$showdat * 100);
                    $data['amount'] = $value;
                    if ($value < 0.1)
                        $errmsg = $name . '不能小于0.1元';
                } else if ($name == '账号') {
                    if (empty($showdat)) {
                        $errmsg = $name . '必填';
                    }
                    $data['tranaccount'] = $showdat;
                } else if ($name == '姓名') {
                    if (empty($showdat)) {
                        $errmsg = $name . '必填';
                    }
                    $data['tranname'] = $showdat;
                } else if ($name == '身份证号') {
                    if (empty($showdat)) {
                        $value = '';
                    }
                    $data['tranidid'] = $showdat;
                } else if ($name == '备注') {
                    if (empty($showdat)) {
                        $value = '';
                    }
                    $data['memo'] = $showdat;
                }
                if (!empty($showdat))
                    $bempty = false;

                if (empty($errmsg))
                    $hrhtml .= '<td><div>' . $showdat . '<input type="hidden" name="' . $arr['fld'] . '_' . $lineidx . '" value="' . $value . '"/>' . $ext . '</div></td>';
                else
                    $hrhtml .= '<td style="background:#ffe8c5;" title="#' . $lineidx . ':' . $errmsg . '"><div>' . $showdat . '</div></td>';
            }
            if ($bempty)
                continue;

            $retchk = check_transtr($data['amount'], $data['accounttype'], $data['tranaccount'], $data['tranname'], $data['tranidid'], $data['memo'], $merchantrow['safecase']);
            if (is_string($retchk))
                $firsthtml = '<td style="background:#ffe8c5;" title="#' . $lineidx . ':' . $retchk . '"><div class="lang">重复</div></td>';
            else if (count($unqs) > 0) {
                $unq = implode('|', $unqs);
                if (in_array($unq, $uniques))
                    $firsthtml = '<td style="background:#ffe8c5;" title="#' . $lineidx . ':该行与待导入数据有重复"><div class="lang">重复</div></td>';
                else {
                    $uniques[] = $unq;
                    $csql->column('id');
                    $chkid = toint($db->get1($csql));
                    if ($chkid > 0 && (($id > 0 && $chkid != $id) || $id == 0))
                        $firsthtml = '<td style="background:#ffe8c5;" title="#' . $lineidx . ':该行与数据库数据有重复"><div class="lang">重复</div></td>';
                }
            }
            $html .= '<tr>' . $firsthtml . $hrhtml . '</tr>';
            $cnt++;
        }
        $html .= '</tbody></table></div>';
        $html .= '<input type="hidden" name="total" value="' . $cnt . '"/>';
        $html .= '<code>共' . $cnt . '条数据</code>';
        return succjson(array('html' => $html, 'count' => $cnt));
    }

    public static function json_importxls_data() {
        global $db;
        $rsuser = verifyfast();
        //if (nopower($db, $rsuser['id'], 'p i'))
        //    return errjson('您未被授权操作');
        $csql = new \ciy\sql('hf_merchantbase');
        $csql->where('id', $rsuser['s_b']);
        $merchantrow = $db->getone($csql);
        $post = new \ciy\post();
        $total = $post->getint('total');
        try {
            $db->begin();
            for ($i = 1; $i <= $total; $i++) {
                $id = $post->getint('id_' . $i);
                $data = array();
                $data['accounttype'] = $post->get('accounttype_' . $i);
                $data['amount'] = $post->get('amount_' . $i);
                $data['tranaccount'] = $post->get('tranaccount_' . $i);
                $data['tranname'] = $post->get('tranname_' . $i);
                $data['tranidid'] = $post->get('tranidid_' . $i);
                $data['memo'] = $post->get('memo_' . $i);
                self::updatedata($db, $rsuser, $id, $data, $merchantrow);
            }
            $db->commit();
        } catch (\Exception $ex) {
            $db->rollback();
            savelogfile('err_db', $ex->getMessage());
            return errjson($ex->getMessage());
        }
        return succjson();
    }
}
