<?php

namespace web\admin\ap;

class pnt_bundle {
    static function setwhere($db, $post) {
        $query = $post->get('query');
        $csql = new \ciy\sql('ap_pnt_bundle');
        $csql->wherenumrange('buypnt', objstr($query, 'buypnt_1'), objstr($query, 'buypnt_2'), 1);
        $csql->wherenumrange('buymoney', objstr($query, 'buymoney_1'), objstr($query, 'buymoney_2'), 100);
        $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_pnt_bundle');
            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' => 'num', 'form' => 'buypnt', 'name' => '金币', 'prop' => ' style="width:4em;"');
            $input[] = array('type' => 'num', 'form' => 'buymoney', 'name' => '金额', 'prop' => ' style="width:4em;"');
            $ret['searchinput'] = $input;
        }
        return succjson($ret);
    }
    public static function json_update() {
        global $db;
        $rsuser = verifyfast();
        //if (nopower($db, $rsuser['id'], 'p u'))
        //    return errjson('您未被授权操作');
        $post = new \ciy\post();
        $id = $post->getint('id');
        $buypnt = $post->getint('buypnt');
        $buymoney = $post->getint('buymoney');
        if ($buypnt == 0)
            return errjson('请填写金币');
        if ($buymoney == 0)
            return errjson('请填写金额');
        $datarow = null;
        if ($id > 0) {
            $csql = new \ciy\sql('ap_pnt_bundle');
            $csql->where('id', $id);
            $datarow = $db->getone($csql);
            if (!is_array($datarow))
                return errjson('数据不存在');
        }
        try {
            $db->begin();
            $updata = array();
            $updata['buypnt'] = $buypnt;
            $updata['buymoney'] = $buymoney;
            $csql = new \ciy\sql('ap_pnt_bundle');
            if ($id > 0) {
                $csql->where('id', $id);
                if ($db->update($csql, $updata) === false)
                    throw new \Exception('更新失败:' . $db->error);
            } else {
                if ($db->insert($csql, $updata) === false)
                    throw new \Exception('新增失败:' . $db->error);
                $id = $db->insert_id();
            }
            $updata['id'] = $id;
            savelogdb($db, $rsuser['id'], 'ap_pnt_bundle', $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_pnt_bundle');
        $csql->where('id in', $ids);
        $rows = $db->get($csql);
        $vids = array();
        try {
            $db->begin();
            foreach ($rows as $row) {
                $delid = $row['id'];
                //delcheck($db, $delid, 'tablexx', 'xxid', '管理员');
                //delall($db, $delid, 'tablexx', 'xxid', '运动员');  //deltimeall
                delme($db, $delid, 'ap_pnt_bundle');
                savelogdb($db, $rsuser['id'], 'ap_pnt_bundle', $row, null);
                $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_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' => 'r', 'width' => 100,  'field' => 'buypnt', 'name' => '金币');
        $fields[] = array('style' => 'r', 'width' => 100,  'field' => 'buymoney', 'name' => '金额');
        $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 == 'buymoney')
                    $val = number_format($val / 100, 2);
                $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'] = 'Demo数据报表';
        $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));
    }

    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[] = '金币.buypnt';
        $headsn[] = '金额.buymoney';
        $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]
            );
        }
        $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++) {
            $lineidx = $rowidx - $xlsidx + 1;
            $hrhtml = '';
            $firsthtml = '<td><div>' . $lineidx . '</div></td>';
            $bempty = true;
            $unqs = array();
            $csql = new \ciy\sql('ap_pnt_bundle');
            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_pnt_bundle');
                            $csqlchk->where('id', $id)->column('id');
                            $chkid = toint($db->get1($csqlchk));
                            if ($chkid != $id)
                                $errmsg = $name . '在数据库中不存在';
                            $value = $id;
                        }
                    }
                } else if ($name == '金币') {
                    if (empty($showdat)) {
                        $errmsg = $name . '为必填项';
                    } else {
                        $showdat = str_replace(',', '', $showdat);
                        if (!is_numeric($showdat))
                            $errmsg = $name . '不是数字';
                        else
                            $value = toint($showdat);
                    }
                } else if ($name == '金额') {
                    if (empty($showdat)) {
                        $errmsg = $name . '为必填项';
                    } else {
                        $showdat = str_replace(',', '', $showdat);
                        if (!is_numeric($showdat))
                            $errmsg = $name . '不是数字';
                        else
                            $value = toint((float)$showdat * 100);
                    }
                }
                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;
            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('您未被授权操作');
        $post = new \ciy\post();
        $total = $post->getint('total');
        try {
            $db->begin();
            for ($i = 1; $i <= $total; $i++) {
                $id = $post->getint('id_' . $i);
                $updata = array();
                $updata['buypnt'] = $post->get('buypnt_' . $i);
                $updata['buymoney'] = $post->get('buymoney_' . $i);
                $csql = new \ciy\sql('ap_pnt_bundle');
                if ($id == 0) {
                    if ($db->insert($csql, $updata) === false)
                        throw new \Exception('新增导入失败:' . $db->error);
                } else {
                    $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());
        }
        return succjson();
    }
}
