<?php namespace Phpcmf\Controllers\Admin;

/**
 * 内容权限设置（模块 / 栏目）
 * 用户侧权限仍在 Member 插件 member/auth
 */
class Auth extends \Phpcmf\Common
{

    public function __construct() {
        parent::__construct();
        if (!IS_USE_MEMBER) {
            $this->_admin_msg(0, dr_lang('未安装用户系统，无法设置内容权限'));
        }
    }

    // 当前可配置的内容模块
    protected function _content_modules() {
        $module = \Phpcmf\Service::L('cache')->get('module-'.SITE_ID.'-content');
        if (!$module) {
            return [];
        }
        foreach ($module as $dir => $t) {
            if ($t['hlist'] == 1) {
                unset($module[$dir]);
            }
        }
        return $module;
    }

    // 构建用户组 / 等级列
    protected function _auth_columns($auth_type) {

        $group = [
            0 => [
                'id' => 0,
                'name' => dr_lang('游客'),
                'use' => 1,
            ]
        ];
        foreach ($this->member_cache['group'] as $t) {
            $group[$t['id']] = [
                'id' => $t['id'],
                'name' => dr_lang($t['name']),
                'use' => 1,
            ];
        }

        $level = [
            0 => [
                'id' => 0,
                'name' => dr_lang('游客'),
                'group_name' => '',
                'level_name' => dr_lang('游客'),
                'use' => 1,
            ]
        ];
        foreach ($this->member_cache['group'] as $t) {
            $gname = dr_lang($t['name']);
            $level[$t['id']] = [
                'id' => $t['id'],
                'name' => $gname,
                'group_name' => '',
                'level_name' => $gname,
                'use' => 1,
            ];
            if ($t['level']) {
                foreach ($t['level'] as $lv) {
                    $lname = dr_lang($lv['name']);
                    $level[$t['id'].'-'.$lv['id']] = [
                        'id' => $t['id'].'-'.$lv['id'],
                        'name' => $gname.' / '.$lname,
                        'group_name' => $gname,
                        'level_name' => $lname,
                        'use' => 1,
                    ];
                    $level[$t['id']]['use'] = 0;
                }
            }
        }

        if ($auth_type == 1) {
            return $group;
        }
        if ($auth_type == 2) {
            $columns = [];
            foreach ($level as $i => $t) {
                if ($t['use']) {
                    $columns[$i] = $t;
                }
            }
            return $columns;
        }
        return [
            'public' => [
                'id' => 'public',
                'name' => dr_lang('全局'),
                'use' => 1,
            ]
        ];
    }

    protected function _get_auth_row($auth_data, $aid) {
        $key = (string)$aid;
        if (isset($auth_data[$aid]) && is_array($auth_data[$aid])) {
            return $auth_data[$aid];
        }
        if (isset($auth_data[$key]) && is_array($auth_data[$key])) {
            return $auth_data[$key];
        }
        return [];
    }

    protected function _get_post_row($post, $aid) {
        $key = (string)$aid;
        if (isset($post[$aid]) && is_array($post[$aid])) {
            return $post[$aid];
        }
        if (isset($post[$key]) && is_array($post[$key])) {
            return $post[$key];
        }
        return [];
    }

    // 未勾选的 checkbox 不会出现在 POST 中，显式写成 0，避免关闭验证码等无效
    protected function _normalize_category_auth_flags($auth) {
        if (!is_array($auth)) {
            $auth = [];
        }
        foreach (['show', 'add', 'edit', 'del', 'code'] as $f) {
            $auth[$f] = empty($auth[$f]) ? 0 : 1;
        }
        return $auth;
    }

    // 表头：用户组 / 等级列
    protected function _auth_thead_html($columns) {
        $html = '<th class="fc-auth-name">'.dr_lang('权限项').'</th>';
        foreach ($columns as $aid => $col) {
            $key = (string)$aid;
            if ($key === '0') {
                $title = '<span class="font-red">'.htmlspecialchars((string)$col['name']).'</span>';
            } elseif (!empty($col['group_name'])) {
                $title = '<span class="fc-auth-gname">'.htmlspecialchars((string)$col['group_name']).'</span>'
                    .'<span class="fc-auth-lname">'.htmlspecialchars((string)$col['level_name']).'</span>';
            } else {
                $title = htmlspecialchars((string)$col['name']);
            }
            $html .= '<th class="fc-auth-col">'.$title.'</th>';
        }
        return $html;
    }

    protected function _auth_form_switch($label, $input_name, $checked, $help = '') {
        $html = '<div class="form-group">'
            .'<label class="col-md-2 control-label">'.$label.'</label>'
            .'<div class="col-md-9">'
            .'<input type="checkbox" name="'.$input_name.'" value="1"'
            .($checked ? ' checked' : '')
            .' data-on-text="'.dr_lang('禁止').'" data-off-text="'.dr_lang('开放').'"'
            .' data-on-color="danger" data-off-color="success" class="make-switch" data-size="small">';
        if ($help) {
            $html .= '<span class="help-block">'.$help.'</span>';
        }
        $html .= '</div></div>';
        return $html;
    }

    protected function _auth_matrix_wrap($thead, $tbody) {
        return '<div class="table-scrollable fc-auth-wrap">'
            .'<table class="table table-striped table-bordered table-hover fc-auth-table">'
            .'<thead><tr class="heading">'.$thead.'</tr></thead>'
            .'<tbody>'.$tbody.'</tbody>'
            .'</table></div>';
    }

    // 栏目权限弹窗按钮
    protected function _auth_category_btn($aid, $page, $title, $btn_class = 'btn blue btn-xs', $btn_text = '') {
        $url = dr_url('cms/auth/add', ['aid' => $aid, 'page' => $page]);
        $js_title = str_replace(["\\", "'"], ["\\\\", "\\'"], (string)$title);
        if ($btn_text === '') {
            $btn_text = dr_lang('设置');
        }
        return '<button type="button" class="'.$btn_class.'" onclick="dr_iframe_show(\''.$js_title.'\', \''.$url.'\', \'85%\', \'90%\')">'
            .'<i class="fa fa-cog"></i> '.$btn_text
            .'</button>';
    }

    // 栏目权限入口（全局表单）
    protected function _auth_category_form($columns, $page = 'cms') {
        $aid = 'public';
        $name = dr_lang('全局');
        foreach ($columns as $k => $col) {
            $aid = (string)$k;
            $name = (string)$col['name'];
            break;
        }
        return '<div class="form-group">'
            .'<label class="col-md-2 control-label">'.dr_lang('栏目权限').'</label>'
            .'<div class="col-md-9">'
            .$this->_auth_category_btn($aid, $page, dr_lang('[%s]栏目权限', $name), 'btn blue btn-sm', dr_lang('设置栏目发布/审核等权限'))
            .'<span class="help-block">'.dr_lang('访问、发布、修改、删除及投稿限制等').'</span>'
            .'</div></div>';
    }

    // 栏目权限矩阵行
    protected function _auth_category_row($columns, $page = 'cms') {
        $html = '<tr><td class="fc-auth-name">'.dr_lang('栏目权限').'</td>';
        foreach ($columns as $aid => $col) {
            $key = (string)$aid;
            $html .= '<td class="fc-auth-col">'
                .$this->_auth_category_btn($key, $page, dr_lang('[%s]栏目权限', $col['name']))
                .'</td>';
        }
        $html .= '</tr>';
        return $html;
    }

    public function index() {

        $v = \Phpcmf\Service::M()->db->table('member_setting')->where('name', 'auth_type')->get()->getRowArray();
        $auth_type = intval($v['value']);
        $columns = $this->_auth_columns($auth_type);
        $modules = $this->_content_modules();

        $row = \Phpcmf\Service::M()->db->table('member_setting')->where('name', 'auth2')->get()->getRowArray();
        $value = $row ? dr_string2array($row['value']) : [];
        if (!is_array($value)) {
            $value = [];
        }
        $auth_data = isset($value[SITE_ID]) && is_array($value[SITE_ID]) ? $value[SITE_ID] : [];

        if (IS_AJAX_POST) {

            $post = \Phpcmf\Service::L('input')->post('data');
            if (!is_array($post)) {
                $post = [];
            }

            foreach ($columns as $aid => $col) {
                $old = $this->_get_auth_row($auth_data, $aid);
                $post_row = $this->_get_post_row($post, $aid);

                $home = isset($old['home']) && is_array($old['home']) ? $old['home'] : [];
                $home['show'] = empty($post_row['home']['show']) ? 0 : 1;
                $old['home'] = $home;

                $mod = isset($old['module']) && is_array($old['module']) ? $old['module'] : [];
                foreach ($modules as $mid => $m) {
                    if (!isset($mod[$mid]) || !is_array($mod[$mid])) {
                        $mod[$mid] = [];
                    }
                    $mod[$mid]['show'] = empty($post_row['module'][$mid]['show']) ? 0 : 1;
                    $mod[$mid]['search'] = empty($post_row['module'][$mid]['search']) ? 0 : 1;
                }
                $old['module'] = $mod;

                $auth_data[$aid] = $old;
            }

            $value[SITE_ID] = $auth_data;
            \Phpcmf\Service::M()->db->table('member_setting')->replace([
                'name' => 'auth2',
                'value' => dr_array2string($value)
            ]);
            \Phpcmf\Service::M('cache')->sync_cache('member');
            $this->_json(1, dr_lang('操作成功'));
        }

        $is_single = dr_count($columns) <= 1;
        $page = \Phpcmf\Service::L('input')->get('page');
        if (!$page) {
            $page = 'site';
        }
        if ($page !== 'site' && !isset($modules[$page])) {
            $page = 'site';
        }

        $tabs = [];

        // —— 整站 ——
        $site_html = '';
        if ($is_single) {
            $aid = 'public';
            foreach ($columns as $k => $col) {
                $aid = (string)$k;
                break;
            }
            $data = $this->_get_auth_row($auth_data, $aid);
            $aid_attr = htmlspecialchars($aid);
            $site_html .= $this->_auth_form_switch(
                dr_lang('禁止整站访问'),
                'data['.$aid_attr.'][home][show]',
                !empty($data['home']['show']),
                dr_lang('针对整个网站的前端界面访问权限')
            );
            $site_html .= $this->_auth_category_form($columns, 'cms');
        } else {
            $tbody = '<tr><td class="fc-auth-name">'.dr_lang('禁止整站访问').'</td>';
            foreach ($columns as $aid => $col) {
                $key = (string)$aid;
                $data = $this->_get_auth_row($auth_data, $aid);
                $checked = !empty($data['home']['show']) ? ' checked' : '';
                $tbody .= '<td class="fc-auth-col">'
                    .'<input type="checkbox" class="fc-auth-check" name="data['.htmlspecialchars($key).'][home][show]" value="1"'.$checked.' />'
                    .'</td>';
            }
            $tbody .= '</tr>';
            $tbody .= $this->_auth_category_row($columns, 'cms');
            $site_html .= $this->_auth_matrix_wrap($this->_auth_thead_html($columns), $tbody);
        }
        $tabs['site'] = [
            'id' => 'site',
            'name' => dr_lang('整站'),
            'dirname' => '',
            'icon' => 'fa fa-globe',
            'html' => $site_html,
        ];

        // —— 各内容模块 ——
        foreach ($modules as $mid => $m) {
            $mname = dr_lang($m['name']);
            $icon = !empty($m['icon']) ? $m['icon'] : 'fa fa-folder';
            $mod_html = '';
            if ($is_single) {
                $aid = 'public';
                foreach ($columns as $k => $col) {
                    $aid = (string)$k;
                    break;
                }
                $data = $this->_get_auth_row($auth_data, $aid);
                $aid_attr = htmlspecialchars($aid);
                $mid_attr = htmlspecialchars($mid);
                $mod_html .= $this->_auth_form_switch(
                    dr_lang('禁止访问'),
                    'data['.$aid_attr.'][module]['.$mid_attr.'][show]',
                    !empty($data['module'][$mid]['show']),
                    dr_lang('禁止后无法访问本模块前台')
                );
                $mod_html .= $this->_auth_form_switch(
                    dr_lang('禁止搜索'),
                    'data['.$aid_attr.'][module]['.$mid_attr.'][search]',
                    !empty($data['module'][$mid]['search']),
                    dr_lang('禁止后无法使用本模块搜索')
                );
                if (empty($m['share'])) {
                    $mod_html .= $this->_auth_category_form($columns, $mid);
                } else {
                    $mod_html .= '<div class="form-group"><label class="col-md-2 control-label">'.dr_lang('栏目权限').'</label>'
                        .'<div class="col-md-9"><span class="help-block" style="margin-top:8px;">'
                        .dr_lang('本模块使用共享栏目，请到「整站」中设置栏目权限')
                        .'</span></div></div>';
                }
            } else {
                $tbody = '';
                $tbody .= '<tr><td class="fc-auth-name">'.dr_lang('禁止访问').'</td>';
                foreach ($columns as $aid => $col) {
                    $key = (string)$aid;
                    $data = $this->_get_auth_row($auth_data, $aid);
                    $checked = !empty($data['module'][$mid]['show']) ? ' checked' : '';
                    $tbody .= '<td class="fc-auth-col">'
                        .'<input type="checkbox" class="fc-auth-check" name="data['.htmlspecialchars($key).'][module]['.htmlspecialchars($mid).'][show]" value="1"'.$checked.' />'
                        .'</td>';
                }
                $tbody .= '</tr>';
                $tbody .= '<tr><td class="fc-auth-name">'.dr_lang('禁止搜索').'</td>';
                foreach ($columns as $aid => $col) {
                    $key = (string)$aid;
                    $data = $this->_get_auth_row($auth_data, $aid);
                    $checked = !empty($data['module'][$mid]['search']) ? ' checked' : '';
                    $tbody .= '<td class="fc-auth-col">'
                        .'<input type="checkbox" class="fc-auth-check" name="data['.htmlspecialchars($key).'][module]['.htmlspecialchars($mid).'][search]" value="1"'.$checked.' />'
                        .'</td>';
                }
                $tbody .= '</tr>';
                if (empty($m['share'])) {
                    $tbody .= $this->_auth_category_row($columns, $mid);
                }
                $mod_html .= $this->_auth_matrix_wrap($this->_auth_thead_html($columns), $tbody);
                if (!empty($m['share'])) {
                    $mod_html .= '<p class="help-block" style="margin-top:12px;">'
                        .dr_lang('本模块使用共享栏目，请到「整站」中设置栏目权限')
                        .'</p>';
                }
            }
            $tabs[$mid] = [
                'id' => $mid,
                'name' => $mname,
                'dirname' => $mid,
                'icon' => $icon,
                'html' => $mod_html,
            ];
        }

        \Phpcmf\Service::V()->assign([
            'menu' => \Phpcmf\Service::M('auth')->_admin_menu(
                [
                    '内容权限' => ['cms/auth/index', 'fa fa-table'],
                    'help' => [801],
                ]
            ),
            'auth_type' => $auth_type,
            'page' => $page,
            'tabs' => $tabs,
        ]);
        \Phpcmf\Service::V()->display('auth_index.html');
    }

    // 存储模式值
    public function save_edit() {

        $value = intval(\Phpcmf\Service::L('input')->get('value'));
        if (!$value) {
            $msg = dr_lang('已切换至按全局配置模式');
        } elseif ($value == 1) {
            $msg = dr_lang('已切换至按用户组配置模式');
        } elseif ($value == 2) {
            $msg = dr_lang('已切换至按用户组等级配置模式');
        } else {
            $this->_json(0, dr_lang('未知模式'));
        }

        \Phpcmf\Service::M()->db->table('member_setting')->replace([
            'name' => 'auth_type',
            'value' => $value
        ]);
        \Phpcmf\Service::M('cache')->sync_cache('member');

        $this->_json(1, $msg);
    }

    // 初始化组权限（仅清空内容相关配置，保留用户权限）
    public function init_edit() {

        $v = \Phpcmf\Service::M()->db->table('member_setting')->where('name', 'auth2')->get()->getRowArray();
        $aid = \Phpcmf\Service::L('input')->get('aid');
        if ($aid === null || $aid === false || $aid === '') {
            $this->_json(0, dr_lang('参数错误'));
        }
        if ($aid !== 'public' && $aid !== '0' && $aid !== 0
            && !preg_match('/^\d+(-\d+)?$/', (string)$aid)) {
            $this->_json(0, dr_lang('参数错误'));
        }
        $value = $v ? dr_string2array($v['value']) : [];
        if (!is_array($value)) {
            $value = [];
        }
        $old = isset($value[SITE_ID][$aid]) && is_array($value[SITE_ID][$aid]) ? $value[SITE_ID][$aid] : [];
        if (!$old && is_numeric($aid) && isset($value[SITE_ID][intval($aid)]) && is_array($value[SITE_ID][intval($aid)])) {
            $old = $value[SITE_ID][intval($aid)];
        }
        $keep = [];
        if (isset($old['member'])) {
            $keep['member'] = $old['member'];
        }
        if (isset($old['app'])) {
            $keep['app'] = $old['app'];
        }
        $value[SITE_ID][$aid] = $keep;

        \Phpcmf\Service::M()->db->table('member_setting')->replace([
            'name' => 'auth2',
            'value' => dr_array2string($value)
        ]);
        \Phpcmf\Service::M('cache')->sync_cache('member');

        $this->_json(1, dr_lang('本组内容权限初始化完成'));
    }

    // 栏目等详细权限设置
    public function add() {

        $aid = \Phpcmf\Service::L('input')->get('aid');
        if ($aid == 'public') {
            $name = dr_lang('全局');
        } elseif (!$aid && $aid !== '0' && $aid !== 0) {
            $aid = 0;
            $name = dr_lang('游客');
        } elseif (strpos((string)$aid, '-') !== false) {
            list($gid, $lid) = explode('-', $aid);
            if (!$this->member_cache['group'][$gid]) {
                $this->_admin_msg(0, dr_lang('此用户组不存在'));
            } elseif (!$this->member_cache['group'][$gid]['level'][$lid]) {
                $this->_admin_msg(0, dr_lang('此用户组等级不存在'));
            }
            $name = $this->member_cache['group'][$gid]['name'].'-'.$this->member_cache['group'][$gid]['level'][$lid]['name'];
        } else {
            if ($aid !== '0' && $aid !== 0 && !$this->member_cache['group'][$aid]) {
                $this->_admin_msg(0, dr_lang('此用户组不存在'));
            }
            $name = ($aid === '0' || $aid === 0) ? dr_lang('游客') : $this->member_cache['group'][$aid]['name'];
        }

        // 共享栏目
        $share_module = \Phpcmf\Service::L('cache')->get('module-'.SITE_ID.'-share');
        $share_categroy = [];
        if (is_file(dr_get_app_dir('module').'Libraries/Category.php')) {
            $share_module['category'] = \Phpcmf\Service::L('category', 'module')->get_category('share');
        }
        if ($share_module['category']) {
            foreach ($share_module['category'] as $t) {
                if ($t['tid'] != 2) {
                    $t['is_post'] = 0;
                    if (!$t['child'] && $t['tid'] == 1) {
                        $t['is_post'] = 1;
                    }
                    $share_categroy[$t['id']] = $t;
                }
            }
        }

        // 模块部分
        $module = $this->_content_modules();
        if ($module) {
            foreach ($module as $dir => $t) {
                if (is_file(dr_get_app_dir('module').'Libraries/Category.php')) {
                    $module[$dir]['category'] = \Phpcmf\Service::L('tree', 'module')
                        ->init(\Phpcmf\Service::L('category', 'module')->get_category($dir))
                        ->html_icon()->get_tree_array(0);
                } else {
                    $module[$dir]['category'] = \Phpcmf\Service::L('cache')->get('module-'.SITE_ID.'-'.$dir, 'category');
                }
            }
        }

        $v = \Phpcmf\Service::M()->db->table('member_setting')->where('name', 'auth2')->get()->getRowArray();
        $value = $v ? dr_string2array($v['value']) : [];
        if (!is_array($value)) {
            $value = [];
        }
        $data = isset($value[SITE_ID][$aid]) && is_array($value[SITE_ID][$aid]) ? $value[SITE_ID][$aid] : [];
        $auth = [
            'share_category' => is_array($data['share_category_public'] ?? null) ? $data['share_category_public'] : [],
            'category' => is_array($data['category_public'] ?? null) ? $data['category_public'] : [],
        ];

        if (IS_AJAX_POST) {

            $post = \Phpcmf\Service::L('input')->post('data');
            if (!is_array($post)) {
                $post = [];
            }
            $save = $data;

            // 栏目模式与统一栏目权限
            if (isset($post['home']['is_category'])) {
                if (!isset($save['home']) || !is_array($save['home'])) {
                    $save['home'] = [];
                }
                $save['home']['is_category'] = empty($post['home']['is_category']) ? 0 : 1;
            }
            $share_public = \Phpcmf\Service::L('input')->post('share_category');
            if (is_array($share_public)) {
                $save['share_category_public'] = $this->_normalize_category_auth_flags($share_public);
            }
            $cat_public = \Phpcmf\Service::L('input')->post('category');
            if (is_array($cat_public)) {
                if (!isset($save['category_public']) || !is_array($save['category_public'])) {
                    $save['category_public'] = [];
                }
                foreach ($cat_public as $cmid => $crow) {
                    // 模板里的 hidden test 字段不算权限配置
                    if (!is_array($crow) || (dr_count($crow) === 1 && isset($crow['test']))) {
                        continue;
                    }
                    $save['category_public'][$cmid] = $this->_normalize_category_auth_flags($crow);
                }
            }
            if (isset($post['module']) && is_array($post['module'])) {
                if (!isset($save['module']) || !is_array($save['module'])) {
                    $save['module'] = [];
                }
                foreach ($post['module'] as $mid => $row) {
                    if (!isset($save['module'][$mid]) || !is_array($save['module'][$mid])) {
                        $save['module'][$mid] = [];
                    }
                    if (isset($row['is_category'])) {
                        $save['module'][$mid]['is_category'] = empty($row['is_category']) ? 0 : 1;
                    }
                }
            }

            // 保留用户权限 / 应用权限 / 访问禁止项 / 按栏目独立设置
            if (isset($data['member'])) {
                $save['member'] = $data['member'];
            }
            if (isset($data['app'])) {
                $save['app'] = $data['app'];
            }
            if (isset($data['home']['show'])) {
                if (!isset($save['home']) || !is_array($save['home'])) {
                    $save['home'] = [];
                }
                $save['home']['show'] = $data['home']['show'];
            }
            if (isset($data['module']) && is_array($data['module'])) {
                foreach ($data['module'] as $mid => $row) {
                    if (!isset($save['module'][$mid]) || !is_array($save['module'][$mid])) {
                        $save['module'][$mid] = [];
                    }
                    if (isset($row['show'])) {
                        $save['module'][$mid]['show'] = $row['show'];
                    }
                    if (isset($row['search'])) {
                        $save['module'][$mid]['search'] = $row['search'];
                    }
                }
            }
            if (isset($data['share_category'])) {
                $save['share_category'] = $data['share_category'];
            }
            if (isset($data['category'])) {
                $save['category'] = $data['category'];
            }

            $value[SITE_ID][$aid] = $save;
            \Phpcmf\Service::M()->db->table('member_setting')->replace([
                'name' => 'auth2',
                'value' => dr_array2string($value)
            ]);
            \Phpcmf\Service::M('cache')->sync_cache('member');
            $this->_json(1, dr_lang('操作成功'));
        }

        $page = trim(\Phpcmf\Service::L('input')->get('page'));
        if (!$page) {
            $page = 'cms';
        }

        // 弹窗只展示当前入口对应的栏目（共享 / 单个模块）
        $is_share_page = ($page === 'cms' || $page === 'site');
        $mid = '';
        $m = [];
        if ($is_share_page) {
            $page = 'cms';
            $page_name = dr_lang('共享栏目');
        } elseif (isset($module[$page])) {
            $mid = $page;
            $m = $module[$page];
            $page_name = dr_lang($m['name']);
            // 共享型模块无独立栏目，回退到共享栏目
            if (!empty($m['share'])) {
                $is_share_page = true;
                $page = 'cms';
                $mid = '';
                $m = [];
                $page_name = dr_lang('共享栏目');
            }
        } else {
            $this->_admin_msg(0, dr_lang('模块不存在'));
        }

        $verify = [];
        if (\Phpcmf\Service::M()->is_table_exists('admin_verify')) {
            $verify = \Phpcmf\Service::M()->table('admin_verify')->getAll();
        }

        $diy = $this->_get_diy();
        if ($is_share_page) {
            $diy['module'] = [];
        }

        \Phpcmf\Service::V()->assign([
            'aid' => $aid,
            'diy' => $diy,
            'menu' => \Phpcmf\Service::M('auth')->_admin_menu(
                [
                    dr_lang('%s：%s栏目权限', $name, $page_name) => ['cms/auth/add{aid='.$aid.'&page='.$page.'}', 'fa fa-table'],
                    'help' => [801],
                ]
            ),
            'page' => $page,
            'page_name' => $page_name,
            'is_share_page' => $is_share_page,
            'mid' => $mid,
            'm' => $m,
            'data' => $data,
            'auth' => $auth,
            'verify' => $verify,
            'is_ajax_edit' => 0,
            'share_categroy' => \Phpcmf\Service::L('tree')->init($share_categroy)->html_icon()->get_tree_array(0),
        ]);
        \Phpcmf\Service::V()->display('auth_setting.html');
    }

    // 弹出设置单独权限
    public function edit() {

        $at = dr_safe_filename(\Phpcmf\Service::L('input')->get('at'));
        if (!$at || !in_array($at, ['share_category', 'category'])) {
            $this->_json(0, dr_lang('at参数错误'));
        }

        $v = \Phpcmf\Service::M()->db->table('member_setting')->where('name', 'auth2')->get()->getRowArray();
        $aid = \Phpcmf\Service::L('input')->get('aid');
        !$aid && $aid !== '0' && $aid = 0;
        $value = $v ? dr_string2array($v['value']) : [];
        if (!is_array($value)) {
            $value = [];
        }

        $id = intval(\Phpcmf\Service::L('input')->get('id'));
        if (!$id) {
            $this->_json(0, dr_lang('id参数错误'));
        }

        $mid = dr_safe_filename(\Phpcmf\Service::L('input')->get('mid'));

        if (IS_AJAX_POST) {

            if ($at == 'category') {
                $post = \Phpcmf\Service::L('input')->post($at);
                $row = is_array($post[$mid] ?? null) ? $post[$mid] : [];
                $value[SITE_ID][$aid][$at][$mid][$id] = $this->_normalize_category_auth_flags($row);
            } else {
                $row = \Phpcmf\Service::L('input')->post($at);
                $value[SITE_ID][$aid][$at][$id] = $this->_normalize_category_auth_flags($row);
            }

            \Phpcmf\Service::M()->db->table('member_setting')->replace([
                'name' => 'auth2',
                'value' => dr_array2string($value)
            ]);
            \Phpcmf\Service::M('cache')->sync_cache('member');
            $this->_json(1, dr_lang('操作成功'));
        }

        if ($at == 'category') {
            $auth = [$at => [$mid => $value[SITE_ID][$aid][$at][$mid][$id]]];
        } else {
            $auth = [$at => $value[SITE_ID][$aid][$at][$id]];
        }

        $verify = [];
        if (\Phpcmf\Service::M()->is_table_exists('admin_verify')) {
            $verify = \Phpcmf\Service::M()->table('admin_verify')->getAll();
        }

        \Phpcmf\Service::V()->assign([
            'mid' => $mid,
            'diy' => $this->_get_diy(),
            'auth' => $auth,
            'verify' => $verify,
            'is_ajax_edit' => 1,
        ]);
        \Phpcmf\Service::V()->display('auth_'.$at.'.html');
    }

    // 复制动作
    public function copy_edit() {

        $id = intval(\Phpcmf\Service::L('input')->get('id'));
        $at = dr_safe_filename(\Phpcmf\Service::L('input')->get('at'));
        if (!$at) {
            $this->_json(0, dr_lang('at参数错误'));
        }

        $v = \Phpcmf\Service::M()->db->table('member_setting')->where('name', 'auth2')->get()->getRowArray();
        $aid = \Phpcmf\Service::L('input')->get('aid');
        !$aid && $aid !== '0' && $aid = 0;
        $value = $v ? dr_string2array($v['value']) : [];
        if (!is_array($value)) {
            $value = [];
        }

        switch ($at) {

            case 'level':
            case 'group':
                $group = [
                    0 => [
                        'id' => 0,
                        'name' => dr_lang('游客'),
                    ],
                ];
                foreach ($this->member_cache['group'] as $t) {
                    if ($at == 'level') {
                        $group[$t['id']] = [
                            'id' => $t['id'],
                            'name' => dr_lang($t['name']),
                        ];
                        if ($t['level']) {
                            foreach ($t['level'] as $lv) {
                                $group[$t['id'].'-'.$lv['id']] = [
                                    'id' => $t['id'].'-'.$lv['id'],
                                    'name' => '  └  '.dr_lang($lv['name']),
                                ];
                            }
                        }
                    } else {
                        $group[$t['id']] = $t;
                    }
                }

                if (IS_AJAX_POST) {

                    $auth = $value[SITE_ID][$aid];
                    if (!$auth) {
                        $this->_json(0, dr_lang('当前用户组没有配置权限规则'));
                    }

                    $catids = \Phpcmf\Service::L('input')->post('catid');
                    if (!$catids) {
                        $this->_json(0, dr_lang('你还没有选择用户组呢'));
                    }

                    $c = 0;
                    if (isset($catids[0]) && $catids[0] == 0) {
                        foreach ($group as $gid => $t) {
                            $c++;
                            $value[SITE_ID][$gid] = $auth;
                        }
                    } else {
                        foreach ($catids as $gid) {
                            $c++;
                            $value[SITE_ID][$gid] = $auth;
                        }
                    }

                    \Phpcmf\Service::M()->db->table('member_setting')->replace([
                        'name' => 'auth2',
                        'value' => dr_array2string($value)
                    ]);
                    \Phpcmf\Service::M('cache')->sync_cache('member');
                    $this->_json(1, dr_lang('共复制%s个用户组', $c));
                }

                \Phpcmf\Service::V()->assign([
                    'form' => dr_form_hidden(),
                    'select' => \Phpcmf\Service::L('tree')->select_category(
                        $group,
                        0,
                        'id=\'dr_catid\' name=\'catid[]\' multiple="multiple" style="height:200px"',
                        '',
                        0,
                        0
                    ),
                ]);
                \Phpcmf\Service::V()->display('auth_copy_group.html');exit;

            case 'share_category':
                $share_module = \Phpcmf\Service::L('cache')->get('module-'.SITE_ID.'-share');
                if (is_file(dr_get_app_dir('module').'Libraries/Category.php')) {
                    $share_module['category'] = \Phpcmf\Service::L('category', 'module')->get_category('share');
                }
                if (IS_AJAX_POST) {

                    $auth = $value[SITE_ID][$aid]['share_category'][$id];
                    if (!$auth) {
                        $this->_json(0, dr_lang('当前栏目没有配置权限规则'));
                    }

                    $catids = \Phpcmf\Service::L('input')->post('catid');
                    if (!$catids) {
                        $this->_json(0, dr_lang('你还没有选择栏目呢'));
                    }

                    $c = 0;
                    if (isset($catids[0]) && $catids[0] == 0) {
                        foreach ($share_module['category'] as $cid => $t) {
                            $c++;
                            $value[SITE_ID][$aid]['share_category'][$cid] = $auth;
                        }
                    } else {
                        foreach ($catids as $cid) {
                            $c++;
                            $value[SITE_ID][$aid]['share_category'][$cid] = $auth;
                        }
                    }

                    \Phpcmf\Service::M()->db->table('member_setting')->replace([
                        'name' => 'auth2',
                        'value' => dr_array2string($value)
                    ]);
                    \Phpcmf\Service::M('cache')->sync_cache('member');
                    $this->_json(1, dr_lang('共复制%s个栏目', $c));
                }

                \Phpcmf\Service::V()->assign([
                    'form' => dr_form_hidden(),
                    'select' => \Phpcmf\Service::L('tree')->select_category(
                        $share_module['category'],
                        0,
                        'id=\'dr_catid\' name=\'catid[]\' multiple="multiple" style="height:200px"',
                        dr_lang('全部栏目'),
                        0,
                        0
                    ),
                ]);
                \Phpcmf\Service::V()->display('auth_copy_category.html');exit;

            case 'category':
                $mid = dr_safe_filename(\Phpcmf\Service::L('input')->get('mid'));
                $module = \Phpcmf\Service::L('cache')->get('module-'.SITE_ID.'-'.$mid);
                if (is_file(dr_get_app_dir('module').'Libraries/Category.php')) {
                    $module['category'] = \Phpcmf\Service::L('category', 'module')->get_category($mid);
                }
                if (IS_AJAX_POST) {

                    $auth = $value[SITE_ID][$aid]['category'][$mid][$id];
                    if (!$auth) {
                        $this->_json(0, dr_lang('当前栏目没有配置权限规则'));
                    }

                    $catids = \Phpcmf\Service::L('input')->post('catid');
                    if (!$catids) {
                        $this->_json(0, dr_lang('你还没有选择栏目呢'));
                    }

                    $c = 0;
                    if (isset($catids[0]) && $catids[0] == 0) {
                        foreach ($module['category'] as $cid => $t) {
                            $c++;
                            $value[SITE_ID][$aid]['category'][$mid][$cid] = $auth;
                        }
                    } else {
                        foreach ($catids as $cid) {
                            $c++;
                            $value[SITE_ID][$aid]['category'][$mid][$cid] = $auth;
                        }
                    }

                    \Phpcmf\Service::M()->db->table('member_setting')->replace([
                        'name' => 'auth2',
                        'value' => dr_array2string($value)
                    ]);
                    \Phpcmf\Service::M('cache')->sync_cache('member');
                    $this->_json(1, dr_lang('共复制%s个栏目', $c));
                }

                \Phpcmf\Service::V()->assign([
                    'form' => dr_form_hidden(),
                    'select' => \Phpcmf\Service::L('category', 'module')->select(
                        $module['mid'],
                        0,
                        'id=\'dr_catid\' name=\'catid[]\' multiple="multiple" style="height:200px"',
                        dr_lang('全部栏目'),
                        0,
                        0
                    ),
                ]);
                \Phpcmf\Service::V()->display('auth_copy_category.html');exit;
        }

        $this->_json(0, dr_lang('未知类型'));
    }

    private function _get_diy() {

        $diy = [
            'module' => [],
            'category' => [],
        ];

        $local = \Phpcmf\Service::Apps(1);
        foreach ($local as $dir => $path) {
            if (is_file($path.'Config/Auth.php')) {
                $_data = require $path.'Config/Auth.php';
                if ($_data) {
                    foreach ($_data as $key => $val) {
                        if ($val && isset($diy[$key])) {
                            foreach ($val as $file) {
                                if (is_file($path.'Views/auth/'.$file)) {
                                    $diy[$key][] = [
                                        'app' => $dir,
                                        'file' => $path.'Views/auth/'.$file,
                                    ];
                                } else {
                                    log_message('error', '应用插件['.$dir.']权限模板文件不存在：'.$path.'Views/auth/'.$file);
                                }
                            }
                        }
                    }
                }
            }
        }

        return $diy;
    }

}
