• 欢迎来到THBWiki!如果您是第一次来到这里,请点击右上角注册一个帐户
  • 有任何意见、建议、求助、反馈都可以在 讨论板 提出
  • THBWiki以专业性和准确性为目标,如果你发现了任何确定的错误或疏漏,可在登录后直接进行改正

用户:玲子/GroupEditor.js

来自THBWiki
跳到导航 跳到搜索

注意:在发布之后,您可能需要清除浏览器缓存才能看到所作出的变更的影响。

  • Firefox或Safari:按住Shift的同时单击刷新,或按Ctrl-F5Ctrl-R(Mac为⌘-R
  • Google Chrome:Ctrl-Shift-R(Mac为⌘-Shift-R
  • Internet Explorer或Edge:按住Ctrl的同时单击刷新,或按Ctrl-F5
  • Opera:Ctrl-F5
mw.loader.using(['oojs-ui-core', 'oojs-ui-widgets', 'oojs-ui-windows']).then(function () {
    var pageTitle = mw.config.get('wgTitle');
    if (pageTitle !== '东方相关QQ群组列表' && pageTitle !== '玲子/GroupEditor.js') {
        return;
    }
    var userName = mw.config.get('wgUserName');
    var isLogin = true;
    if (userName === null) {
    	// 未登录
    	userName = '未登录';
    	isLogin = false;
    	//return;
    }
    mw.loader.load( 'https://touhou.review/index.php?title=用户:玲子/GroupEditor.css&action=raw&ctype=text/css', 'text/css' );
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.get('action')) {
    	return;
    }
    var api = new mw.Api();

    var btn_submit = new OO.ui.ButtonWidget({
        label: '提交更改',
        icon: 'check',
        flags: [
            'primary',
            'progressive'
        ]
    });

    var all_options = {
        '地区性东方群': [
            { data: '北京市', label: '北京市' },
            { data: '天津市', label: '天津市' },
            { data: '河北省', label: '河北省' },
            { data: '山西省', label: '山西省' },
            { data: '内蒙古自治区', label: '内蒙古自治区' },
            { data: '辽宁省', label: '辽宁省' },
            { data: '吉林省', label: '吉林省' },
            { data: '黑龙江省', label: '黑龙江省' },
            { data: '上海市', label: '上海市' },
            { data: '江苏省', label: '江苏省' },
            { data: '浙江省', label: '浙江省' },
            { data: '安徽省', label: '安徽省' },
            { data: '福建省', label: '福建省' },
            { data: '江西省', label: '江西省' },
            { data: '山东省', label: '山东省' },
            { data: '河南省', label: '河南省' },
            { data: '湖北省', label: '湖北省' },
            { data: '湖南省', label: '湖南省' },
            { data: '广东省', label: '广东省' },
            { data: '广西壮族自治区', label: '广西壮族自治区' },
            { data: '海南省', label: '海南省' },
            { data: '重庆市', label: '重庆市' },
            { data: '宁夏回族自治区', label: '宁夏回族自治区' },
            { data: '四川省', label: '四川省' },
            { data: '贵州省', label: '贵州省' },
            { data: '云南省', label: '云南省' },
            { data: '陕西省', label: '陕西省' },
            { data: '甘肃省', label: '甘肃省' },
            { data: '青海省', label: '青海省' },
            { data: '新疆维吾尔自治区', label: '新疆维吾尔自治区' },
            { data: '西藏自治区', label: '西藏自治区' },
            { data: '台湾省', label: '台湾省' },
            { data: '香港特别行政区', label: '香港特别行政区' },
            { data: '澳门特别行政区', label: '澳门特别行政区' },
            { data: '东亚', label: '海外→东亚' },
            { data: '欧洲', label: '海外→欧洲' },
            { data: '大洋洲', label: '海外→大洋洲' },
            { data: '东南亚', label: '海外→东南亚' },
        ],
        '组织实体官方群': [
            { data: '社团→音乐', label: '社团→音乐' },
            { data: '社团→同人志', label: '社团→同人志' },
            { data: '社团→游戏', label: '社团→游戏' },
            { data: '社团→周边', label: '社团→周边' },
            { data: '社团→综合', label: '社团→综合' },
            { data: '社团→技术', label: '社团→技术' },
            { data: '社团→其他', label: '社团→其他' },
            { data: '组织→MC服务器', label: '组织→MC服务器' },
            { data: '组织→同人游戏', label: '组织→同人游戏' },
            { data: '组织→技术交流', label: '组织→技术交流' },
            { data: '组织→视频创作推广', label: '组织→视频创作推广' },
            { data: '组织→其他', label: '组织→其他' },
        ],
        '网络区域社群': [
            { data: '贴吧附属', label: '贴吧附属' },
            { data: '论坛附属', label: '论坛附属' },
            { data: '网站用户', label: '网站用户' },
            { data: '非官方粉丝群', label: '非官方粉丝群' },
        ],
        '功能性公开群': [
            { data: '综合性答疑群', label: '专题讨论→综合性答疑群' },
            { data: '东方设定交流', label: '专题讨论→东方设定交流' },
            { data: '东方音乐交流', label: '专题讨论→东方音乐交流' },
            { data: '东方角色交流', label: '专题讨论→东方角色交流' },
            { data: '东方CP交流', label: '专题讨论→东方CP交流' },
            { data: '东方绘画交流', label: '专题讨论→东方绘画交流' },
            { data: '东方文学交流', label: '专题讨论→东方文学交流' },
            { data: '东方stg交流', label: '专题讨论→东方stg交流' },
            { data: '东方格斗作交流', label: '专题讨论→东方格斗作交流' },
            { data: '东方TRPG交流', label: '专题讨论→东方TRPG交流' },
            { data: '东方MMD交流', label: '专题讨论→东方MMD交流' },
            { data: '东方CP交流', label: '专题讨论→东方CP交流' },
            { data: '东方绘画交流', label: '专题讨论→东方绘画交流' },
            { data: '东方文学交流', label: '专题讨论→东方文学交流' },
            { data: 'Cosplay', label: '线下活动→Cosplay' },
            { data: '游戏模组', label: '综合→游戏模组' },
            { data: '新闻整合宣发', label: '综合→新闻整合宣发' },
            { data: '其他', label: '综合→其他' },
        ],
    };

    var input_type = new OO.ui.DropdownInputWidget({
        options: [
            { data: '活动官方群', label: '活动官方群' },             // 扩展
            { data: '地区性东方群', label: '地区性东方群' },
            { data: '学校东方群', label: '学校东方群' },             // 扩展
            { data: '组织实体官方群', label: '组织实体官方群' },      // 扩展
            { data: '网络区域社群', label: '网络区域社群' },
            { data: '功能性公开群', label: '功能性公开群' },
        ]
    }),
        input_area = new OO.ui.DropdownInputWidget({
            options: all_options['地区性东方群']
        }),
        input_area_field = new OO.ui.FieldLayout(input_area, {
            label: '地区:',
            align: 'top'
        }),
        input_city = new OO.ui.TextInputWidget({
            required: true,
            validate: 'non-empty',
            placeholder: '请输入城市(仅活动群和学校群)',
        }),
        input_city_field = new OO.ui.FieldLayout(input_city, {
            label: '城市:',
            align: 'top'
        }),
        input_custom = new OO.ui.TextInputWidget({
            required: true,
            validate: 'non-empty',
            placeholder: '请根据提示输入'
        }),
        input_custom_field = new OO.ui.FieldLayout(input_custom, {
            label: '地点:',
            align: 'top'
        }),
        input_group_id = new OO.ui.TextInputWidget({
            required: true,
            validate: /^\d+$/,
            placeholder: '请输入群号'
        }),
        input_group_name = new OO.ui.TextInputWidget({
            required: true,
            validate: 'non-empty',
            placeholder: '请输入群名'
        }),
        input_desc = new OO.ui.TextInputWidget({
            placeholder: '请输入群简介(可选)',
        }),
        input_group_link = new OO.ui.TextInputWidget({
            placeholder: '请输入加群链接(可选)需先设置群头像',
            disabled: true,
        }),
        progress = new OO.ui.ProgressBarWidget({
            progress: 0,
        }),
        progress_field = new OO.ui.FieldLayout(progress, {
            align: 'top',
        }),
        select_use_pic = new OO.ui.RadioSelectInputWidget({
            options: [
                {
                    data: 'none',
                    label: '不启用群头像'
                },
                {
                    data: 'new',
                    label: '上传新的群头像'
                },
                {
                    data: 'old',
                    label: '使用已有的群头像'
                }
            ]
        });

    var fieldset = new OO.ui.FieldsetLayout({
        label: '群组页面快速编辑器 [账号:' + userName + ']',
        classes: ['container']
    });

    fieldset.addItems([
        new OO.ui.Widget({
            content: [new OO.ui.HorizontalLayout({
                items: [
                    new OO.ui.FieldLayout(input_type, {
                        label: '群组类型:',
                        align: 'top',
                    }),
                    input_area_field,
                ]
            })]
        }),

        input_city_field,
        
        input_custom_field,

        new OO.ui.FieldLayout(input_group_id, {
            label: '群号:',
            align: 'top'
        }),

        new OO.ui.FieldLayout(input_group_name, {
            label: '群名:',
            align: 'top'
        }),

        new OO.ui.FieldLayout(input_desc, {
            label: '群简介:',
            align: 'top',
            help: '用一句话介绍群组,不支持换行,不宜过长',
            helpInline: true,
        }),

        new OO.ui.FieldLayout(input_group_link, {
            label: '加群链接:',
            align: 'top',
            help: '(可选)设置后点击图片可以跳转加群,需先设置群头像',
            helpInline: true,
        }),

        new OO.ui.FieldLayout(select_use_pic, {
            label: '群头像设置(会出现在简介里)',
            align: 'inline'
        }),

        new OO.ui.Widget({
            content: [new OO.ui.HorizontalLayout({
                items: [
                    new OO.ui.FieldLayout(btn_submit),
                    progress_field
                ]
            })]
        }),
    ]);
    
	if (!isLogin) {
		btn_submit.setDisabled(true);
        input_area.setDisabled(true);
        input_city.setDisabled(true);
        input_custom.setDisabled(true);
        input_group_id.setDisabled(true);
        input_group_name.setDisabled(true);
        input_desc.setDisabled(true);
        input_group_link.setDisabled(true);
        input_type.setDisabled(true);
        select_use_pic.setDisabled(true);
	}

    const checkPicFile = (file_name) => {
        // 检查文件是否存在 (不含命名空间)
        console.log('检查文件是否存在:' + file_name);
        var p = new Promise(function (resolve, reject) {
            api.parse('{{filepath:' + file_name + '|100}}', {
                pst: true,
                prop: 'text',
                disableeditsection: true,
                disablelimitreport: true,
            }).done(function (parse_data) {
                console.log(parse_data);
                if (/<img.*?>/.test(parse_data)) {
                    console.log('文件存在');
                    resolve(parse_data.match(/<img.*?>/)[0]);
                    return;
                }
                reject(parse_data);
                return;
            }).fail(function (parse_data) {
                console.log(parse_data);
                reject(parse_data);
                return;
            });
        });
        return p;
    };

    const getUploadWidget = () => {
        var input_upload_pic = new OO.ui.SelectFileWidget({
            accept: [
                'image/png',
                'image/jpeg',
                'image/webp'
            ],
            $tabIndexed: $('<a class="oo-ui-buttonElement-button" role="button" tabindex="0" rel="nofollow"><span class="oo-ui-iconElement-icon oo-ui-icon-upload"></span><span class="oo-ui-labelElement-label">选择文件</span><span class="oo-ui-indicatorElement-indicator oo-ui-indicatorElement-noIndicator"></span><input title="" class="oo-ui-inputWidget-input" type="file" tabindex="-1" accept="image/png, image/jpeg, image/webp"></a>'),
            showDropTarget: true,
            thumbnailSizeLimit: 2,
        }),
            notice_upload_pic = new OO.ui.MessageWidget({
                type: 'notice',
                label: new OO.ui.HtmlSnippet('还未添加任何图片')
            });

        var upload_field = new OO.ui.FieldsetLayout({
            classes: ['container']
        });
        upload_field.addItems([
            new OO.ui.FieldLayout(input_upload_pic, {
                label: '上传文件:',
                align: 'top'
            }),
            new OO.ui.FieldLayout(notice_upload_pic)
        ]);

        return {
            input_upload_pic: input_upload_pic,
            notice_upload_pic: notice_upload_pic,
            upload_field: upload_field
        };
    };

    const getOldPicWidget = () => {
        var group_id = input_group_id.getValue();
        var pic_upload_name = '文件:QQ群-' + group_id + '图片.jpg';
        var pic_file_link = '<a href="/' + pic_upload_name + '" class="new" title="' + pic_upload_name + '">' + pic_upload_name + '</a>';

        var input_pic_type = new OO.ui.DropdownInputWidget({
            options: [
                { data: 'jpg', label: 'jpg' },
                { data: 'png', label: 'png' },
                { data: 'webp', label: 'webp' }
            ]
        }),
            notice_old_pic = new OO.ui.MessageWidget({
                type: 'warning',
                label: new OO.ui.HtmlSnippet('将会使用现存的图片,请确保文件存在且文件后缀选择正确!<br>备查:' + pic_file_link)
            });
        var old_pic_field = new OO.ui.FieldsetLayout({
            classes: ['container']
        });
        old_pic_field.addItems([
            new OO.ui.FieldLayout(input_pic_type, {
                label: '文件后缀:',
                align: 'top'
            }),
            new OO.ui.FieldLayout(notice_old_pic)
        ]);

        return {
            input_pic_type: input_pic_type,
            notice_old_pic: notice_old_pic,
            old_pic_field: old_pic_field
        };
    };

    var upload_widget = getUploadWidget();
    var old_pic_widget = getOldPicWidget();
    var timeoutId = null;


    const checkExistPic = () => {
        var use_pic = select_use_pic.getValue();
        if (use_pic !== 'old') {
            return;
        }
        var pic_file_type = old_pic_widget.input_pic_type.getValue();
        var group_id = input_group_id.getValue();
        var pic_base_name = 'QQ群-' + group_id + '图片.' + pic_file_type;
        var pic_upload_name = '文件:' + pic_base_name;
        var pic_file_link = '<a href="/' + pic_upload_name + '" class="new" title="' + pic_upload_name + '">' + pic_upload_name + '</a>';
        old_pic_widget.notice_old_pic.setLabel(new OO.ui.HtmlSnippet('正在查找文件,请确保文件存在且文件后缀选择正确!<br>备查:' + pic_file_link));
        old_pic_widget.notice_old_pic.setType('notice');
        // 防抖
        clearTimeout(timeoutId);

        // 设置新的定时器,延迟 1s 执行
        timeoutId = setTimeout(() => {
            checkPicFile(pic_base_name).then(function (pic_data) {
                console.log(pic_data);
                pic_file_link = '<a href="/' + pic_upload_name + '" title="' + pic_upload_name + '">' + pic_upload_name + '</a>';
                old_pic_widget.notice_old_pic.setLabel(new OO.ui.HtmlSnippet('看起来wiki上已存在 ' + pic_file_link + '<br>图片预览:' + pic_data));
                old_pic_widget.notice_old_pic.setType('success');
            }).catch(function (pic_data) {
                console.log('文件不存在');
                old_pic_widget.notice_old_pic.setLabel(new OO.ui.HtmlSnippet('wiki上似乎没有这个文件,请确保文件存在且文件后缀选择正确!<br>备查:' + pic_file_link));
                old_pic_widget.notice_old_pic.setType('warning');
            });
        }, 1000);
    };

    input_type.on('change', function () {
        var group_type = input_type.getValue();
        input_city.setValue('');
        input_custom.setValue('');

        if (group_type === '活动官方群') {
            // 扩展
            input_city.setDisabled(false);
            input_area_field.setLabel('地区:');
            input_area.setOptions(all_options['地区性东方群']);
            input_custom_field.setLabel('活动名:');
        } else if (group_type === '地区性东方群') {
            input_city.setDisabled(true);
            input_area_field.setLabel('地区:');
            input_area.setOptions(all_options['地区性东方群']);
            input_custom_field.setLabel('地点:');
        } else if (group_type === '学校东方群') {
            // 扩展
            input_city.setDisabled(false);
            input_area_field.setLabel('地区:');
            input_area.setOptions(all_options['地区性东方群']);
            input_custom_field.setLabel('学校:');
        } else if (group_type === '组织实体官方群') {
            input_city.setDisabled(true);
            input_area_field.setLabel('类型:');
            input_custom_field.setLabel('名称:');
            input_area.setOptions(all_options[group_type]);
        } else if (group_type === '网络区域社群') {
            input_city.setDisabled(true);
            input_area_field.setLabel('类型:');
            input_custom_field.setLabel('名称:');
            input_area.setOptions(all_options[group_type]);
        } else if (group_type === '功能性公开群') {
            input_city.setDisabled(true);
            input_area_field.setLabel('类型:');
            input_custom_field.setLabel('名称:');
            input_area.setOptions(all_options[group_type]);
        }
    });

    input_area.on('change', function () {
        var group_type = input_type.getValue();
        var group_area = input_area.getValue();

        var net_labels = {
            '贴吧附属': { label: '贴吧', value: 'XX吧' },
            '论坛附属': { label: '论坛', value: 'XX论坛' },
            '网站用户': { label: '网站', value: 'XX网站' },
            '非官方粉丝群': { label: '主题', value: '输入一个主题' },
        };

        var func_labels = {
            '综合性答疑群': { label: '方向', value: '问答讨论' },
            '东方设定交流': { label: '方向', value: '科普' },
            '东方音乐交流': { label: '方向', value: '综合' },
            '东方角色交流': { label: '角色', value: '输入一个角色名' },
            '东方CP交流': { label: 'CP', value: '[[角色1]] x [[角色2]]' },
            '东方绘画交流': { label: '方向', value: '绘画' },
            '东方文学交流': { label: '方向', value: '诗词' },
            '东方stg交流': { label: '类别', value: '综合' },
            '东方格斗作交流': { label: '类别', value: '游戏' },
            '东方TRPG交流': { label: '方向', value: 'TRPG' },
            '东方MMD交流': { label: '方向', value: 'MMD' },
            'Cosplay': { label: '地区', value: '输入一个地区名' },
            '游戏模组': { label: '游戏名', value: '输入一个游戏名' },
            '新闻整合宣发': { label: '方向', value: '宣发' },
            '其他': { label: '类别', value: '综合' },
        };

        if (group_type === '活动官方群') {
            if (group_area === '北京市' || group_area === '上海市' || group_area === '重庆市' || group_area === '天津市') {
                input_city.setValue(group_area);
            }
            input_custom_field.setLabel('活动名:');
            input_custom.setValue('');
        } else if (group_type === '学校东方群') {
            if (group_area === '北京市' || group_area === '上海市' || group_area === '重庆市' || group_area === '天津市') {
                input_city.setValue(group_area);
            }
            input_custom_field.setLabel('学校:');
            input_custom.setValue('');
        } else if (group_type === '组织实体官方群') {
            if (group_area.startsWith('社团→')) {
                input_custom_field.setLabel('社团名:');
            } else if (group_area.startsWith('组织→')) {
                input_custom_field.setLabel('组织名:');
            }
            input_custom.setValue('');
            
        } else if (group_type === '网络区域社群') {
            if (net_labels[group_area]) {
                input_custom_field.setLabel(net_labels[group_area].label + ':');
                input_custom.setValue(net_labels[group_area].value);
            } else {
                input_custom_field.setLabel('类别:');
                input_custom.setValue('综合');
            }
        } else if (group_type === '功能性公开群') {
            if (func_labels[group_area]) {
                input_custom_field.setLabel(func_labels[group_area].label + ':');
                input_custom.setValue(func_labels[group_area].value);
            } else {
                input_custom_field.setLabel('类别:');
                input_custom.setValue('综合');
            }
        }
    });

    input_group_id.on('change', checkExistPic);

    upload_widget.input_upload_pic.on('change', function () {
        var pic_file = upload_widget.input_upload_pic.currentFiles[0];
        console.log(pic_file);
        if (!pic_file) {
            upload_widget.notice_upload_pic.setLabel(new OO.ui.HtmlSnippet('还未添加任何图片'));
            upload_widget.notice_upload_pic.setType('notice');
            btn_submit.setDisabled(true);
            input_group_link.setDisabled(true);
            input_group_link.setValue('');
            return;
        }
        if (pic_file.size > 2 * 1024 * 1024) {
            upload_widget.notice_upload_pic.setLabel(new OO.ui.HtmlSnippet('文件过大,请选择小于2MB的文件!'));
            upload_widget.notice_upload_pic.setType('error');
            btn_submit.setDisabled(true);
            input_group_link.setDisabled(true);
            input_group_link.setValue('');
            return;
        }
        if (pic_file.type !== 'image/png' && pic_file.type != 'image/jpeg' && pic_file.type != 'image/webp') {
            console.log('不支持的文件类型');
            return;
        }
        var pic_file_name = pic_file.name;
        upload_widget.notice_upload_pic.setLabel(new OO.ui.HtmlSnippet('已选择:' + pic_file_name));
        upload_widget.notice_upload_pic.setType('success');
        btn_submit.setDisabled(false);
        input_group_link.setDisabled(false);
        console.log('已选择:' + pic_file_name);
    });

    old_pic_widget.input_pic_type.on('change', checkExistPic);

    select_use_pic.on('change', function () {
        var use_pic = select_use_pic.getValue();
        if (use_pic === 'new') {
            // 上传新的群头像
            fieldset.removeItems([old_pic_widget.old_pic_field]);
            fieldset.addItems([upload_widget.upload_field]);
            var pic_file = upload_widget.input_upload_pic.currentFiles[0];
            if (!pic_file) {
                btn_submit.setDisabled(true);
                input_group_link.setDisabled(true);
                input_group_link.setValue('');
            }
        } else if (use_pic === 'old') {
            // 使用已有的群头像
            fieldset.removeItems([upload_widget.upload_field]);
            fieldset.addItems([old_pic_widget.old_pic_field]);
            checkExistPic();
            btn_submit.setDisabled(false);
            input_group_link.setDisabled(false);
        } else {
            // 不启用群头像
            fieldset.removeItems([upload_widget.upload_field]);
            fieldset.removeItems([old_pic_widget.old_pic_field]);
            btn_submit.setDisabled(false);
            input_group_link.setDisabled(true);
            input_group_link.setValue('');
        }
    });

    const getSectionId = (group_type, section_name) => {
        // 获取页面内全部标题的section
        console.log('开始获取section_id');
        console.log('group_type:' + group_type + 'section_name: ' + section_name);
        var p = new Promise(function (resolve, reject) {
            api.get({
                action: 'parse',
                page: '东方相关QQ群组列表',
                prop: 'sections'
            }).then(function (sections_data) {
                console.log(sections_data);
                var sections = sections_data.parse.sections;
                const main_section = {
                    活动官方群: '1',
                    地区性东方群: '2',
                    学校东方群: '3',
                    组织实体官方群: '4',
                    网络区域社群: '5',
                    功能性公开群: '6'
                };
                for (var i = 0; i < sections.length; i++) {
                    if (sections[i].line === section_name) {
                        var number_str = sections[i].number;
                        var section_type = main_section[group_type];
                        if (number_str.startsWith(section_type)) {
                            console.log(number_str);
                            console.log(section_type);
                            resolve(Number(sections[i].index));
                            return;
                        }
                    }
                }
                reject(-1);
                return;
            });
        });
        return p;
    };

    const getParaWikitext = (group_id, section_id, template_code) => {
        // 获取指定段落的wikitext
        console.log('开始获取指定段落的wikitext');
        console.log('group_id:' + group_id + 'section_id: ' + section_id);
        var p = new Promise(function (resolve, reject) {
            // 获取指定段落的源代码
            api.get({
                action: 'parse',
                page: '东方相关QQ群组列表',
                prop: 'wikitext',
                section: section_id,
            }).then(function (wikitext_data) {
                var lines = wikitext_data.parse.wikitext["*"].split('\n');
                const lastLine = lines.pop();
                exist_index = -1;

                // 检查是否已经存在该群组
                for (var i = 0; i < lines.length; i++) {
                    var c_group_id = '';
                    var sp = lines[i].split('|');
                    if (sp[0] === '{{QQ群扩展') {
                        c_group_id = sp[3];
                    } else if (sp[0] === '{{QQ群') {
                        c_group_id = sp[2];
                    }
                    if (c_group_id === group_id) {
                        console.log('已经存在的群组:' + c_group_id);
                        exist_index = i;
                        break;
                    }
                }
                if (exist_index !== -1) {
                    // 如果存在,则替换掉原来的代码
                    lines[exist_index] = template_code;
                } else {
                    // 如果不存在,则添加到最后一行
                    lines.push(template_code);
                }
                lines.push(lastLine);
                var new_wikitext = lines.join('\n');
                console.log(new_wikitext);
                resolve(new_wikitext);
                return;
            }).fail(function (wikitext_data) {
                console.log('获取段落wikitext失败');
                console.log(wikitext_data);
                reject(wikitext_data);
                return;
            });
        });
        return p;
    };

    const editParaWikitext = (section_id, new_wikitext, section_name) => {
        // 对指定段落进行编辑
        console.log('开始对指定段落进行编辑');
        console.log('section_id: ' + section_id + 'new_wikitext:' + new_wikitext);
        var p = new Promise(function (resolve, reject) {
            // 提交编辑
            api.postWithToken('csrf', {
                action: 'edit',
                title: '东方相关QQ群组列表',
                section: section_id,
                text: new_wikitext,
                summary: '/* ' + section_name + ' */ 群组页面快速编辑器 by 玲子',
                format: 'json',
            }).done(function (edit_data) {
                console.log(edit_data);
                resolve(edit_data);
                return;
            }).fail(function (edit_data) {
                console.log(edit_data);
                reject(edit_data);
                return;
            });
        });
        return p;
    };

    const uploadPicFile = (pic_file, pic_upload_name, use_pic) => {
        console.log('开始上传群头像');
        console.log('pic_upload_name: ' + pic_upload_name);
        var p = new Promise(function (resolve, reject) {
            // 无需上传
            if (use_pic !== 'new') {
                resolve(null);
                return;
            }
            // 检查文件大小
            if (pic_file.size > 2 * 1024 * 1024) {
                reject('文件过大,请选择小于2MB的文件!');
                return;
            }
            // 上传文件
            api.upload(pic_file, {
                filename: pic_upload_name,
                text: '[[分类:东方相关QQ群组]]',
                comment: '群组页面快速编辑器 by 玲子',
                ignorewarnings: true,
                format: 'json',
            }).done(function (upload_data) {
                console.log(upload_data);
                resolve(upload_data);
                return;
            }).fail(function (info, upload_data) {
                console.log(upload_data);
                if (upload_data.upload) {
                    resolve(upload_data);
                    return;
                } else {
                    reject(upload_data);
                    return;
                }
            });
        });
        return p;
    };

    btn_submit.on('click', function () {
        var windowManager = new OO.ui.WindowManager();
        var messageDialog = new OO.ui.MessageDialog();

        var group_type = input_type.getValue();
        var group_area = input_area.getValue();
        var group_city = input_city.getValue();
        var group_custom = input_custom.getValue();
        var group_id = input_group_id.getValue();
        var group_name = input_group_name.getValue();
        var group_desc = input_desc.getValue();
        var group_link = input_group_link.getValue();
        // 检查必填项是否为空
        if (group_type === '' || group_area === '' || group_custom === '' || group_id === '' || group_name === '') {
            $('body').append(windowManager.$element);
            windowManager.addWindows([messageDialog]);
            windowManager.openWindow(messageDialog, {
                title: '数据格式错误',
                message: '请填写所有必填项!'
            });
            return;
        }
        // 检查活动群和学校群是否填写城市
        if (group_type === '活动官方群' || group_type === '学校东方群') {
            if (group_city === '') {
                $('body').append(windowManager.$element);
                windowManager.addWindows([messageDialog]);
                windowManager.openWindow(messageDialog, {
                    title: '数据格式错误',
                    message: '请填写城市!'
                });
                return;
            }
        }

        // 检查群号是否纯数字
        if (!/^\d+$/.test(group_id) && group_id[0] === '0') {
            $('body').append(windowManager.$element);
            windowManager.addWindows([messageDialog]);
            windowManager.openWindow(messageDialog, {
                title: '数据格式错误',
                message: '群号格式错误!'
            });
            return;
        }

        // 检查群简介是否过长
        if (group_desc.length > 40) {
            $('body').append(windowManager.$element);
            windowManager.addWindows([messageDialog]);
            windowManager.openWindow(messageDialog, {
                title: '数据格式错误',
                message: '群简介过长!'
            });
            return;
        }

        // 检查群头像选项
        var use_pic = select_use_pic.getValue();
        var pic_file_type = 'jpg';
        var pic_file = null;
        var pic_upload_name = null;
        if (use_pic === 'new') {
            // 选择了上传新的群头像
            pic_file = upload_widget.input_upload_pic.currentFiles[0];
            console.log(upload_widget.input_upload_pic);
            // 这里如果原本已经传过文件的话就不用再上传了,只影响模板代码
            if (pic_file) {
                if (pic_file.size > 2 * 1024 * 1024) {
                    $('body').append(windowManager.$element);
                    windowManager.addWindows([messageDialog]);
                    windowManager.openWindow(messageDialog, {
                        title: '文件上传',
                        message: '文件过大,请选择小于2MB的文件!'
                    });
                    return;
                }
                // 确定上传文件名
                if (pic_file.type === 'image/png') {
                    pic_file_type = 'png';
                } else if (pic_file.type === 'image/jpeg') {
                    pic_file_type = 'jpg';
                } else if (pic_file.type === 'image/webp') {
                    pic_file_type = 'webp';
                } else {
                    $('body').append(windowManager.$element);
                    windowManager.addWindows([messageDialog]);
                    windowManager.openWindow(messageDialog, {
                        title: '文件上传',
                        message: '不支持的文件类型!'
                    });
                    return;
                }
                pic_upload_name = '文件:QQ群-' + group_id + '图片.' + pic_file_type;
            } else {
                $('body').append(windowManager.$element);
                windowManager.addWindows([messageDialog]);
                windowManager.openWindow(messageDialog, {
                    title: '文件上传',
                    message: '未选择文件!'
                });
                return;
            }
        } else if (use_pic === 'old') {
            // 选择了使用已有的群头像
            pic_file_type = old_pic_widget.input_pic_type.getValue();
        }
        // 检查加群链接是否正确
        if (use_pic !== 'none') {
            if (group_link !== '') {
                if (!/^https?:\/\/.*\.qq\.com\/.*$/.test(group_link)) {
                    $('body').append(windowManager.$element);
                    windowManager.addWindows([messageDialog]);
                    windowManager.openWindow(messageDialog, {
                        title: '数据格式错误',
                        message: '加群链接格式错误!'
                    });
                    return;
                }
            }
        }
        // 生成模板代码
        var template_code = '';
        if (group_type === '活动官方群' || group_type === '学校东方群' || group_type === '组织实体官方群') {
            // QQ群扩展模板
            template_code = '{{QQ群扩展|';
            if (group_type === '活动官方群' || group_type === '学校东方群') {
                template_code += group_city;
            } else if (group_type === '组织实体官方群') {
                if (group_area.startsWith('社团→') || group_area.startsWith('组织→')) {
                    template_code += group_area.substring(3);
                }
            }
            template_code += '|' + group_custom + '|' + group_id + '|' + group_name;
            if (group_desc !== '') {
                template_code += '|' + group_desc;
            }
            if (use_pic !== 'none') {
                template_code += '|图片=' + pic_file_type;
                if (group_link !== '') {
                    template_code += '|链接=' + group_link;
                }
            }
        } else {
            // 普通QQ群模板
            template_code = '{{QQ群|' + group_custom + '|' + group_id + '|' + group_name;
            if (group_desc !== '') {
                template_code += '|' + group_desc;
            }
            if (use_pic !== 'none') {
                template_code += '|图片=' + pic_file_type;
                if (group_link !== '') {
                    template_code += '|链接=' + group_link;
                }
            }
        }

        template_code += '}}';
        console.log(template_code);

        // 上传群头像
        progress_field.setLabel('正在上传文件...');
        progress.setProgress(10);
        uploadPicFile(pic_file, pic_upload_name, use_pic).then(function (upload_data) {
            progress_field.setLabel('正在获取段落:' + group_area);
            progress.setProgress(50);
            // 获取section_id
            var section_name = '';
            if (group_area.startsWith('社团→') || group_area.startsWith('组织→')) {
                section_name = group_area.substring(3) + '官方群';
            } else {
                section_name = group_area;
            }
            getSectionId(group_type, section_name).then(function (section_id) {
                // 获取段落wikitext
                progress_field.setLabel('正在获取源代码:' + section_name);
                progress.setProgress(70);
                getParaWikitext(group_id, section_id, template_code).then(function (new_wikitext) {
                    // 对指定段落进行编辑
                    progress_field.setLabel('正在编辑段落:' + section_name);
                    progress.setProgress(90);
                    editParaWikitext(section_id, new_wikitext, section_name).then(function (edit_data) {
                        progress_field.setLabel('编辑完成!');
                        progress.setProgress(100);
                        console.log(edit_data);
                        $('body').append(windowManager.$element);
                        windowManager.addWindows([messageDialog]);
                        windowManager.openWindow(messageDialog, {
                            title: '编辑成功',
                            message: '编辑成功!'
                        });
                    }).catch(function (edit_data) {
                        progress_field.setLabel('编辑时发生错误!');
                        progress.setProgress(0);
                        console.log(edit_data);
                        $('body').append(windowManager.$element);
                        windowManager.addWindows([messageDialog]);
                        windowManager.openWindow(messageDialog, {
                            title: '编辑失败',
                            message: '编辑失败:' + JSON.stringify(edit_data)
                        });
                    });
                }).catch(function (new_wikitext) {
                    progress_field.setLabel('获取段落(' + group_area + ')时发生错误!');
                    progress.setProgress(0);
                    console.log(new_wikitext);
                    $('body').append(windowManager.$element);
                    windowManager.addWindows([messageDialog]);
                    windowManager.openWindow(messageDialog, {
                        title: '数据格式错误',
                        message: '获取段落wikitext失败!' + JSON.stringify(new_wikitext)
                    });
                    return;
                });
            }).catch(function (section_id) {
                progress_field.setLabel('查找地区时发生错误!');
                progress.setProgress(0);
                $('body').append(windowManager.$element);
                windowManager.addWindows([messageDialog]);
                windowManager.openWindow(messageDialog, {
                    title: '数据格式错误',
                    message: '地区不存在!'
                });
                return;
            });
            progress.setProgress(0);
        }).catch(function (upload_data) {
            progress_field.setLabel('上传文件时发生错误!');
            progress.setProgress(0);
            console.log(upload_data);
            $('body').append(windowManager.$element);
            windowManager.addWindows([messageDialog]);
            windowManager.openWindow(messageDialog, {
                title: '文件上传',
                message: '文件上传失败:' + JSON.stringify(upload_data)
            });
            return;
        });
    });

    // 添加到页面顶部
    $('#mw-content-text').prepend(
        fieldset.$element
    );
});