<?php

namespace web\admin\rigger;

class admin {
    static function setwhere($db, $post) {
        $query = $post->get('query');
        $csql = new \ciy\sql('zc_admin');
        $csql->where('departid', $post->get('departid'));
        $liid = objint($query, 'liid');
        if ($liid > 0)
            $csql->where('stpstatus', $liid);
        $csql->where('name like', objstr($query, 'name'));
        $csql->where('mobile like', objstr($query, 'mobile'));
        $csql->where('sex', objstr($query, 'sex'));
        $csql->wheredaterange('logintimes', objstr($query, 'logintimes'));
        $csql->wheredaterange('addtimes', objstr($query, 'addtimes'));
        $order = objstr($query, 'order', 'id desc');
        $csql->order($order);
        $query['order'] = $order;
        return [$query, $csql];
    }
    public static function json_init() {
        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);
        $ret = array('searchwhere' => $where, 'pageno' => $pageno, 'pagecount' => $pagecount, 'count' => $mainrowcount, 'list' => $rows);
        if ($post->getbool('field')) {
            $field = array();
            $fshow = $db->getfield($field, 'zc_admin');
            foreach ($field as $fr => $v) {
                if ($post->is('_' . $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' => 'mobile',
                'name' => '手机号',
                'prop' => ' style="width:8em;"'
            );
            $input[] = array(
                'type' => 'select',
                'form' => 'sex',
                'name' => '性别',
                'select' => 'sex',
                'all' => '全部'
            );
            $input[] = array(
                'type' => 'daterange',
                'form' => 'logintimes',
                'name' => '登录时间'
            );
            $input[] = array(
                'type' => 'daterange',
                'form' => 'addtimes',
                'name' => '注册时间'
            );
            $ret['searchinput'] = $input;
            $csql = (new \ciy\sql('zc_depart'))->column('id,upid,name,isuse');
            $ret['zc_depart'] = $db->get($csql);
            $csql = new \ciy\sql('zc_role');
            $csql->column('id,name');
            $ret['zc_role'] = $db->get($csql);
        }
        return succjson($ret);
    }
    public static function json_update() {
        global $db;
        $rsuser = verifyfast();
        $post = new \ciy\post();
        $id = $post->getint('id');
        $name = $post->get('name');
        if (empty($name))
            return errjson('请填写姓名');
        $stpstatus = $post->getint('stpstatus');
        if ($stpstatus <= 0)
            return errjson('请填写状态');
        $mobile = $post->get('mobile');
        if (empty($mobile))
            return errjson('请填写手机号');
        $sex = $post->getint('sex');
        if ($sex <= 0)
            return errjson('请填写性别');
        $departid = $post->getint('departid');
        if ($departid == 0)
            return errjson('请选择组织/部门');
        $roleid = $post->getint('roleid');
        $icon = $post->get('icon');
        $datarow = null;
        if ($id > 0) {
            if (nopower($db, $rsuser['id'], 'p500u'))
                return errjson('您未被授权操作修改');
            $csql = new \ciy\sql('zc_admin');
            $csql->where('id', $id);
            $datarow = $db->getone($csql);
            if (!is_array($datarow))
                return errjson('数据不存在');
            if ($datarow['roleid'] != $roleid) {
                if (nopower($db, $rsuser['id'], 'p500r'))
                    return errjson('您没有赋予角色的权限');
            } else
                $roleid = 0;
        } else {
            if (nopower($db, $rsuser['id'], 'p500a'))
                return errjson('您未被授权操作新增');
            if (nopower($db, $rsuser['id'], 'p500r'))
                $roleid = 0;
        }
        if ($roleid > 0) {
            $csql = new \ciy\sql('zc_role');
            $csql->where('id', $roleid);
            $rolerow = $db->getone($csql);
            if (!is_array($rolerow))
                return errjson('角色不存在');
        }
        try {
            $db->begin();
            $csql = new \ciy\sql('zc_admin');
            $csql->where('mobile', $mobile);
            $csql->column('id');
            $chkid = toint($db->get1($csql));
            if ($chkid > 0 && (($id > 0 && $chkid != $id) || $id == 0))
                throw new \Exception('CIYIGN数据已存在');

            $updata = array();
            $updata['icon'] = $icon;
            $updata['name'] = $name;
            $updata['stpstatus'] = $stpstatus;
            $updata['mobile'] = $mobile;
            $updata['sex'] = $sex;
            $updata['departid'] = $departid;
            $updata['roleid'] = $roleid;
            if ($roleid > 0) {
                $updata['power'] = $rolerow['power'];
            }
            $csql = new \ciy\sql('zc_admin');
            if ($id > 0) {
                $csql->where('id', $id);
                if ($db->update($csql, $updata) === false)
                    throw new \Exception('更新失败:' . $db->error);
                if ($stpstatus == 10) {
                    if ($roleid > 0 || $datarow['name'] != $name || $datarow['icon'] != $icon)
                        if ($db->execute('update zc_online set usrchg=2 where user=?', array($id)) === false)
                            throw new \Exception('更新online失败:' . $db->error);
                } else {
                    if ($db->execute('delete from zc_online where user=?', array($id)) === false)
                        throw new \Exception('删除online失败:' . $db->error);
                }
                if ($datarow['name'] != $name)
                    $db->execute('update zc_online set usrchg=2');
            } else {
                $updata['addtimes'] = tostamp();
                if ($db->insert($csql, $updata) === false)
                    throw new \Exception('新增失败:' . $db->error);
                $id = $db->insert_id();
                if ($db->execute('update zc_online set usrchg=2') === false)
                    throw new \Exception('更新online失败:' . $db->error);
            }
            $updata['id'] = $id;
            savelogdb($db, $rsuser['id'], 'zc_admin', $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'], 'p500d'))
            return errjson('您未被授权操作');

        $post = new \ciy\post();
        $ids = $post->get('ids');
        if (empty($ids))
            return errjson('请选择至少一条');
        $csql = new \ciy\sql('zc_admin');
        $csql->where('id in', $ids);
        $rows = $db->get($csql);
        $vids = array();
        try {
            $db->begin();
            foreach ($rows as $row) {
                $delid = $row['id'];
                if ($rsuser['id'] == $delid)
                    throw new \Exception('CIYIGN不能删除本人');
                if ($row['id'] == 10)
                    throw new \Exception('CIYIGN不能删除超级管理员');
                delme($db, $delid, 'zc_admin');
                $db->execute('delte from zc_online where user=?', array($delid));
                savelogdb($db, $rsuser['id'], 'zc_admin', $row, null);
                $vids[] = $delid;
            }
            $db->commit();
        } catch (\Exception $ex) {
            $db->rollback();
            savelogfile('err_db', $ex->getMessage());
            return errjson($ex->getMessage());
        }
        $db->execute('update zc_online set usrchg=2');
        $ret['ids'] = $vids;
        return succjson($ret);
    }
    public static function json_repass() {
        global $db;
        $rsuser = verifyfast();
        global $_token;
        if (nopower($db, $rsuser['id'], 'p500p'))
            return errjson('您未被授权操作');
        $post = new \ciy\post();
        $id = $post->getint('id');
        $newpass = rand(100000, 999999);
        try {
            $db->begin();
            $updata = array();
            $updata['trytime'] = 0;
            $updata['password'] = sha256($newpass . $_token['salt']);
            $csql = new \ciy\sql('zc_admin');
            $csql->where('id', $id);
            if ($db->update($csql, $updata) === false)
                throw new \Exception('更新失败:' . $db->error);
            if ($db->execute('delete from zc_online where user=?', array($id)) === false)
                throw new \Exception('删除online失败:' . $db->error);
            $db->commit();
        } catch (\Exception $ex) {
            $db->rollback();
            savelogfile('err_db', $ex->getMessage());
            return errjson($ex->getMessage());
        }
        $ret['msg'] = '重置后密码: ' . $newpass;
        return succjson($ret);
    }
    public static function json_exportxls() {
        global $db;
        $rsuser = verifyfast();
        if (nopower($db, $rsuser['id'], 'p500e'))
            return errjson('您未被授权操作');
        $post = new \ciy\post();
        $csql = new \ciy\sql('zc_admin');

        list($where, $csql) = self::setwhere($db, $post);
        $rows = $db->get($csql);
        if (count($rows) > 10000)
            return errjson('将导出' . count($rows) . '条，不建议超过1万条，请筛选缩小范围');
        $fields = array();
        $fields[] = array('width' => 60, 'style' => 'c', 'field' => 'id', 'name' => '行码');
        $fields[] = array('width' => 100, 'style' => 'l', 'field' => 'name', 'name' => '姓名');
        $fields[] = array('width' => 60, 'style' => 'c', 'field' => 'stpstatus', 'name' => '状态');
        $fields[] = array('width' => 100, 'style' => 'l', 'field' => 'mobile', 'name' => '手机号');
        $fields[] = array('width' => 60, 'style' => 'c', 'field' => 'sex', 'name' => '性别');
        $fields[] = array('width' => 100, 'style' => 'l', 'field' => 'departid', 'name' => '所属组织');
        $fields[] = array('width' => 100, 'style' => 'l', 'field' => 'logintimes', 'name' => '活跃时间');
        $fields[] = array('width' => 100, 'style' => 'l', 'field' => 'addtimes', 'name' => '注册时间');
        $code_stpstatus = getcatas($db, 'stpstatus', 'zc_cata');
        $code_sex = getcatas($db, 'sex', 'zc_cata');
        $csql = (new \ciy\sql('zc_depart'))->column('id,upid,name');
        $code_departid = $db->get($csql);
        $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 == 'stpstatus')
                    $val = ccode($code_stpstatus, $val);
                if ($field == 'sex')
                    $val = ccode($code_sex, $val);
                if ($field == 'departid')
                    $val = implode('-', mcode($code_departid, $val));
                if ($field == 'logintimes')
                    $val = ($val == 0 ? '--' : date('Y-m-d H:i', $val));
                if ($field == 'addtimes')
                    $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'] = '管理员数据报表';
        // $param['total'] = array();
        // $param['total'][] = array('name'=>'合计','merge'=>8,'style'=>'l');
        // $param['total'][] = array('name'=>'=SUM(R[-'.count($datas).']C:R[-1]C)','style'=>'r');
        // $param['total'][] = array('name'=>'=MAX(R[-'.count($datas).']C:R[-1]C)','style'=>'r');
        // $param['total'][] = array('name'=>'','style'=>'l');
        // $param['total'][] = array('name'=>'','style'=>'l');

        //$param['rowstop'] = '<Row ss:Height="45"><Cell ss:MergeAcross="4" ss:StyleID="cap"><Data ss:Type="String">众产CIYPHP</Data></Cell></Row>';//顶部行
        //$param['rowsfooter'] = '<Row><Cell ss:MergeAcross="1"><Data ss:Type="String" ss:StyleID="r">合计</Data></Cell><Cell ss:Formula="=SUM(R[-2]C:R[-1]C)"><Data ss:Type="Number"></Data></Cell></Row>';//底部行

        $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'], 'p500a'))
            return errjson('您未被授权操作新增');

        $post = new \ciy\post();
        $file = $post->get('file');
        if (!file_exists(PATH_WEB . 'ud/' . $file))
            return errjson('文件不存在');
        require_once PATH_ROOT . '../libs/phpoffice/autoload.php';
        $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load(PATH_WEB . 'ud/' . $file);
        $sheet = $spreadsheet->getActiveSheet();
        $datas = $sheet->toArray('', true, true, false);
        $datacnt = count($datas);
        if ($datacnt < 2)
            return errjson('数据为空');
        $html = '';
        $headsn = array();
        $headsn[] = '姓名.name';
        $headsn[] = '手机号.mobile';
        $headsn[] = '性别.sex';
        $headsn[] = '所属组织.departid';
        $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_sex = getcatas($db, 'sex', 'zc_cata');
        $csql = (new \ciy\sql('zc_depart'))->column('id,upid,name');
        $code_departid = $db->get($csql);
        $html .= '<div class="table">';
        $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('zc_admin');
            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('zc_admin');
                            $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 if ($name == '手机号') {
                    $csql->where('mobile', $showdat);
                    $unqs[] = $showdat;
                    if (empty($showdat)) {
                        $errmsg = $name . '为必填项';
                    }
                } else if ($name == '性别') {
                    if (empty($showdat)) {
                        $errmsg = $name . '为必填项';
                    } else {
                        $value = dcode($code_sex, $showdat);
                        if ($value == -1)
                            $errmsg = $name . '文字与系统数据不匹配';
                    }
                } else if ($name == '所属组织') {
                    if (empty($showdat)) {
                        $value = 0;
                    } else {
                        $dats = explode('-', $showdat);
                        $value = dcode($code_departid, $dats[count($dats) - 1]);
                        if ($value == -1)
                            $errmsg = $name . '文字与系统数据不匹配';
                    }
                }
                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:#e09420;" 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'], 'p500a'))
            return errjson('您未被授权操作新增');
        $post = new \ciy\post();
        $total = $post->getint('total');
        try {
            $db->begin();
            for ($i = 1; $i <= $total; $i++) {
                $id = $post->getint('id_' . $i);
                $name = $post->get('name_' . $i);
                $mobile = $post->get('mobile_' . $i);
                $sex = $post->get('sex_' . $i);
                $departid = $post->get('departid_' . $i);
                $csql = new \ciy\sql('zc_admin');
                $csql->where('mobile', $mobile);
                $csql->column('id');
                $chkid = toint($db->get1($csql));
                if ($chkid > 0 && (($id > 0 && $chkid != $id) || $id == 0))
                    throw new \Exception('CIYIGN发现数据有重复');

                $updata = array();
                $updata['name'] = $name;
                $updata['mobile'] = $mobile;
                $updata['stpstatus'] = 10;
                $updata['sex'] = $sex;
                $updata['departid'] = $departid;
                $updata['addtimes'] = tostamp();
                $csql = new \ciy\sql('zc_admin');
                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());
        }
        $db->execute('update zc_online set usrchg=2');
        return succjson();
    }
}
