<?php

namespace web\admin\ap;

class art_post {
    static function setwhere($db, $post) {
        $query = $post->get('query');
        $csql = new \ciy\sql('ap_art_post');
        $liid = objint($query, 'liid');
        if ($liid > 0)
            $csql->where('artstatus', $liid);
        $csql->where('sectionid', get('_sectionid'));
        $csql->where('name like', objstr($query, 'name'));
        $csql->where('source like', objstr($query, 'source'));
        $csql->where('author like', objstr($query, 'author'));
        $csql->where('readcnt like', objstr($query, 'readcnt'));
        $csql->where('inputuser', objstr($query, 'inputuser'));
        $csql->where('audituser', objstr($query, 'audituser'));
        $csql->wheredaterange('pubtimes', objstr($query, 'pubtimes'));
        $csql->order('artsort desc, id desc');
        return [$query, $csql];
    }

    public static function json_list() {
        global $db;
        $rsuser = verifyfast();
        $post = new \ciy\post();
        list($where, $csql) = self::setwhere($db, $post);
        $csql->column('!descs,content', $db->getraw('show full fields from ap_art_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_art_post');
            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' => 'name', 'name' => '文章标题', 'prop' => ' style="width:8em;"');
            $input[] = array('type' => 'input', 'form' => 'source', 'name' => '来源', 'prop' => ' style="width:8em;"');
            $input[] = array('type' => 'input', 'form' => 'author', 'name' => '作者', 'prop' => ' style="width:8em;"');
            $input[] = array('type' => 'input', 'form' => 'readcnt', 'name' => '阅读数', 'prop' => ' style="width:8em;"');
            $input[] = array('type' => 'select', 'form' => 'inputuser', 'name' => '撰写人', 'all' => '全部', 'select' => 'adminuser');
            $input[] = array('type' => 'select', 'form' => 'audituser', 'name' => '审核人', 'all' => '全部', 'select' => 'adminuser');
            $input[] = array('type' => 'daterange', 'form' => 'pubtimes', 'name' => '发布时间');
            $ret['searchinput'] = $input;
        }
        return succjson($ret);
    }

    public static function json_getdata() {
        global $db;
        $rsuser = verifyfast();
        $post = new \ciy\post();
        $id = $post->getint('id');
        $act = $post->get('act');
        if ($id > 0) {
            $csql = new \ciy\sql('ap_art_post');
            $csql->where('id', $id);
            $row = $db->getone($csql);
            if (!is_array($row))
                return errjson('数据不存在');
            if ($act == 'view' || $act == 'review') {
            }
        } else {
            $row = array();
            $row['artsort'] = 20;
        }
        $ret['data'] = $row;
        if ($act == 'edit') {
        }
        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();
        $sectionid = getint('_sectionid');
        $id = $post->getint('id');
        $artsort = $post->getint('artsort');
        $name = $post->get('name');
        $source = $post->get('source');
        $author = $post->get('author');
        $readcnt = $post->getint('readcnt');
        $avmp = $post->get('avmp');
        $img = $post->get('img');
        $descs = $post->get('descs');
        $content = $post->get('content');
        if ($artsort == 0)
            return errjson('请填写排序位');
        if (empty($name))
            return errjson('请填写文章标题');
        if ($content == '[MD]')
            return errjson('请填写内容');
        $datarow = null;
        if ($id > 0) {
            $csql = new \ciy\sql('ap_art_post');
            $csql->where('id', $id);
            $datarow = $db->getone($csql);
            if (!is_array($datarow))
                return errjson('数据不存在');
        }
        $csql = new \ciy\sql('ap_art_section');
        $csql->where('id', $sectionid);
        $sectionrow = $db->getone($csql);
        if (!is_array($sectionrow))
            return errjson('板块不存在');
        try {
            $db->begin();
            $updata = array();
            $updata['sectionid'] = $sectionid;
            $updata['audituser'] = 0;
            $updata['pubtimes'] = 0;
            if ($post->get('btn') == '审核发布') {
                if ($sectionrow['adminuser'] == $rsuser['id']) {
                    $updata['audituser'] = $rsuser['id'];
                    $updata['pubtimes'] = tostamp();
                    $updata['artstatus'] = 100;
                } else
                    $updata['artstatus'] = 20;
            } else
                $updata['artstatus'] = 10;
            $updata['artsort'] = $artsort;
            $updata['name'] = $name;
            $updata['source'] = $source;
            $updata['author'] = $author;
            $updata['readcnt'] = $readcnt;
            $updata['avmp'] = $avmp;
            $updata['img'] = $img;
            $updata['descs'] = $descs;
            $updata['inputuser'] = $rsuser['id'];
            $updata['content'] = $content;
            $csql = new \ciy\sql('ap_art_post');
            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_art_post', $datarow, $updata);
            $db->commit();
        } catch (\Exception $ex) {
            $db->rollback();
            savelogfile('err_db', $ex->getMessage());
            return errjson($ex->getMessage());
        }
        $ret['data'] = $updata;
        self::total($db);
        return succjson($ret);
    }
    public static function total($db) {
        global $db;
        $sectionid = getint('_sectionid');
        if($sectionid == 0)
            return;
        $csql = new \ciy\sql('ap_art_post');
        $csql->where('sectionid', $sectionid);
        $csql->where('artstatus', 20);
        $auditcnt = $db->get1($csql);
        $csql = new \ciy\sql('ap_art_post');
        $csql->where('sectionid', $sectionid);
        $csql->where('artstatus', 100);
        $artcnt = $db->get1($csql);
        $updata = array();
        $updata['auditcnt'] = $auditcnt;
        $updata['artcnt'] = $artcnt;
        $csql = new \ciy\sql('ap_art_section');
        $csql->where('id', $sectionid);
        $db->update($csql, $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_art_post');
        $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_art_post');
                savelogdb($db, $rsuser['id'], 'ap_art_post', $row, null);
                $vids[] = $delid;
            }
            $db->commit();
        } catch (\Exception $ex) {
            $db->rollback();
            savelogfile('err_db', $ex->getMessage());
            return errjson($ex->getMessage());
        }
        $ret['ids'] = $vids;
        self::total($db);
        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' => 'c', 'width' => 100,  'field' => 'sectionid', 'name' => '版块');
        $fields[] = array('style' => 'c', 'width' => 100,  'field' => 'artstatus', 'name' => '文章状态');
        $fields[] = array('style' => 'l', 'width' => 100,  'field' => 'artsort', 'name' => '排序位');
        $fields[] = array('style' => 'l', 'width' => 150,  'field' => 'name', 'name' => '文章标题');
        $fields[] = array('style' => 'l', 'width' => 150,  'field' => 'source', 'name' => '来源');
        $fields[] = array('style' => 'l', 'width' => 150,  'field' => 'author', 'name' => '作者');
        $fields[] = array('style' => 'r', 'width' => 100,  'field' => 'studycnt', 'name' => '精读数');
        $fields[] = array('style' => 'r', 'width' => 100,  'field' => 'readcnt', 'name' => '阅读数');
        $fields[] = array('style' => 'l', 'width' => 150,  'field' => 'avmp', 'name' => '音视频');
        $fields[] = array('style' => 'l', 'width' => 300,  'field' => 'img', 'name' => '缩略图');
        $fields[] = array('style' => 'l', 'width' => 150,  'field' => 'descs', 'name' => '摘要');
        $fields[] = array('style' => 'l', 'width' => 100,  'field' => 'inputuser', 'name' => '撰写人');
        $fields[] = array('style' => 'l', 'width' => 100,  'field' => 'audituser', 'name' => '审核人');
        $fields[] = array('style' => 'l', 'width' => 100,  'field' => 'pubtimes', 'name' => '发布时间');
        $code_artstatus = getcatas($db, 'artstatus');
        $code_artsort = getcatas($db, 'artsort');
        $code_inputuser = getcatas($db, 'adminuser');
        $code_audituser = getcatas($db, 'adminuser');
        $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 == 'artstatus')
                    $val = ccode($code_artstatus, $val);
                if ($field == 'artsort')
                    $val = ccode($code_artsort, $val);
                if ($field == 'inputuser')
                    $val = ccode($code_inputuser, $val);
                if ($field == 'audituser')
                    $val = ccode($code_audituser, $val);
                if ($field == 'pubtimes')
                    $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'] = '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[] = '版块.sectionid';
        $headsn[] = '文章状态.artstatus';
        $headsn[] = '排序位.artsort';
        $headsn[] = '文章标题.name';
        $headsn[] = '来源.source';
        $headsn[] = '作者.author';
        $headsn[] = '精读数.studycnt';
        $headsn[] = '阅读数.readcnt';
        $headsn[] = '摘要.descs';
        $headsn[] = '撰写人.inputuser';
        $headsn[] = '发布时间.pubtimes';
        $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_artstatus = getcatas($db, 'artstatus');
        $code_artsort = getcatas($db, 'artsort');
        $code_inputuser = getcatas($db, 'adminuser');
        $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_art_post');
            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_art_post');
                            $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)) {
                        $value = 0;
                    } else {
                        $value = dcode($code_artstatus, $showdat);
                        if ($value == -1)
                            $errmsg = $name . '文字与系统数据不匹配';
                    }
                } else if ($name == '排序位') {
                    if (empty($showdat)) {
                        $errmsg = $name . '为必填项';
                    } else {
                        $value = dcode($code_artsort, $showdat);
                        if ($value == -1)
                            $errmsg = $name . '文字与系统数据不匹配';
                    }
                } else if ($name == '文章标题') {
                    if (empty($showdat)) {
                        $errmsg = $name . '为必填项';
                    } else {
                    }
                } else if ($name == '来源') {
                    if (empty($showdat)) {
                        $value = '';
                    } else {
                    }
                } else if ($name == '作者') {
                    if (empty($showdat)) {
                        $value = '';
                    } else {
                    }
                } else if ($name == '精读数') {
                    if (empty($showdat)) {
                        $value = 0;
                    } else {
                        $showdat = str_replace(',', '', $showdat);
                        if (!is_numeric($showdat))
                            $errmsg = $name . '不是数字';
                        else
                            $value = toint($showdat);
                    }
                } else if ($name == '阅读数') {
                    if (empty($showdat)) {
                        $value = 0;
                    } else {
                        $showdat = str_replace(',', '', $showdat);
                        if (!is_numeric($showdat))
                            $errmsg = $name . '不是数字';
                        else
                            $value = toint($showdat);
                    }
                } else if ($name == '摘要') {
                    if (empty($showdat)) {
                        $value = '';
                    } else {
                    }
                } else if ($name == '撰写人') {
                    if (empty($showdat)) {
                        $value = 0;
                    } else {
                        $value = dcode($code_inputuser, $showdat);
                        if ($value == -1)
                            $errmsg = $name . '文字与系统数据不匹配';
                    }
                } else if ($name == '发布时间') {
                    if (empty($showdat)) {
                        $value = 0;
                    } else {
                        $value = tostamp($showdat);
                        if ($value === 0) {
                            $errmsg = $name . '时间格式错误';
                        } else {
                            $showdat = date('Y-m-d H:i', $value);
                        }
                    }
                }
                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['sectionid'] = $post->get('sectionid_' . $i);
                $updata['artstatus'] = $post->get('artstatus_' . $i);
                $updata['artsort'] = $post->get('artsort_' . $i);
                $updata['name'] = $post->get('name_' . $i);
                $updata['source'] = $post->get('source_' . $i);
                $updata['author'] = $post->get('author_' . $i);
                $updata['studycnt'] = $post->get('studycnt_' . $i);
                $updata['readcnt'] = $post->get('readcnt_' . $i);
                $updata['descs'] = $post->get('descs_' . $i);
                $updata['inputuser'] = $post->get('inputuser_' . $i);
                $updata['pubtimes'] = $post->get('pubtimes_' . $i);
                $csql = new \ciy\sql('ap_art_post');
                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();
    }
}
