<template>
    <div class='container'>
        <div class='handle-box'>
            <el-form :inline='true'>
                <el-form-item>
                    <el-button type='primary' @click='dialogVisible = true' v-if="hasAuth('sys:user:save')">新增
                    </el-button>
                </el-form-item>
            </el-form>
        </div>
        <el-table
            ref='crowdTable'
            :data='tableData'
            tooltip-effect='dark'
            style='width: 100%'
            border
            stripe>

            <el-table-column
                type='index'
                label='序号'
                width='50'>
            </el-table-column>

            <el-table-column
                prop='name'
                label='群组名称'
                :show-overflow-tooltip='true'>
            </el-table-column>

            <el-table-column
                prop='description'
                label='群组描述'
                :show-overflow-tooltip='true'>
            </el-table-column>

            <el-table-column
                prop='maxusers'
                width='100'
                align='center'
                label='最大人数'>
            </el-table-column>

            <el-table-column
                prop='affiliations_count'
                width='100'
                align='center'
                label='目前人数'>
                <template slot-scope='scope'>
                    {{ scope.row.affiliations_count - 1 }}
                </template>
            </el-table-column>

            <el-table-column
                prop='created'
                label='创建时间'>
                <template slot-scope='scope'>
                    {{ $moment(new Date(scope.row.created)).format('yyyy-MM-DD HH:mm:ss') }}
                </template>
            </el-table-column>

            <el-table-column
                prop='icon'
                fixed='right'
                width='220px'
                label='操作'>
                <template slot-scope='scope'>
                    <span>
                        <el-button type='text' @click='editHandle(scope.row)'>编辑</el-button>
                        <el-divider direction='vertical'></el-divider>
                    </span>
                    <template>
                        <el-popconfirm title='确定删除这条数据吗？' @confirm='delHandle(scope.row.id)'>
                            <el-button type='text' slot='reference'>删除</el-button>
                        </el-popconfirm>
                    </template>
                    <span>
                        <el-divider direction='vertical'></el-divider>
                        <el-button type='text' @click='showManageMember(scope.row)'>管理成员</el-button>
                    </span>
                    <span>
                        <el-divider direction='vertical'></el-divider>
                        <el-button type='text' @click='showQRCode(scope.row)'>二维码</el-button>
                    </span>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            @size-change='handleSizeChange'
            @current-change='handleCurrentChange'
            layout='total, sizes, prev, pager, next, jumper'
            :page-sizes='[5, 10, 15, 20]'
            :current-page='paging.current'
            :page-size='paging.size'
            :total='paging.total'>
        </el-pagination>

        <!--新增对话框-->
        <el-dialog
            title='提示'
            :visible.sync='dialogVisible'
            width='60%'
            :before-close='handleClose'>
            <el-form :model='gourpForm' :rules='gourpFormRules' ref='gourpForm'>
                <el-row>
                    <el-col :span='12'>
                        <el-form-item label='群组名称:' prop='groupname' label-width='100px'>
                            <el-input v-model='gourpForm.groupname' autocomplete='off' placeholder='请输入群组名称'></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span='12'>
                        <el-form-item label='是否公开:' prop='ispublic' label-width='100px'>
                            <el-select :disabled='gourpForm.id' v-model='gourpForm.ispublic' placeholder='请选择是否公开'>
                                <el-option
                                    v-for='item in ispublicList'
                                    :key='item.value'
                                    :label='item.label'
                                    :value='item.value'>
                                </el-option>
                            </el-select>
                            <p class='form-tips'>提示：无特殊需求选择不公开</p>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span='24'>
                        <el-form-item label='群组描述:' prop='desc' label-width='100px'>
                            <el-input type='textarea' rows='3' v-model='gourpForm.desc' autocomplete='off'
                                      placeholder='请输入群组描述'></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span='12'>
                        <el-form-item label='最大数量:' prop='maxusers' label-width='100px'>
                            <el-input type='number' v-model='gourpForm.maxusers' autocomplete='off'
                                      placeholder='请输入群组人员最大数量'></el-input>
                            <p class='form-tips'>提示：无特殊需求填200</p>
                        </el-form-item>
                    </el-col>
                    <el-col :span='12'>
                        <el-form-item label='是否批准:' prop='approval' label-width='100px'>
                            <el-select :disabled='gourpForm.id' v-model='gourpForm.approval' placeholder='请选择是否需要批准进群'>
                                <el-option
                                    v-for='item in approvalList'
                                    :key='item.value'
                                    :label='item.label'
                                    :value='item.value'>
                                </el-option>
                            </el-select>
                            <p class='form-tips'>提示：若无特殊需求请使用默认的需要批准配置</p>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot='footer' class='dialog-footer'>
                <el-button @click="resetForm('gourpForm')">取 消</el-button>
                <el-button type='primary' @click="submitForm('gourpForm')">确 定</el-button>
            </div>
        </el-dialog>
        <ManageMember ref='manageMember'></ManageMember>
        <QrCode ref='qrCode'></QrCode>
    </div>
</template>

<script>
import axios from 'axios';//加载表格数据的时候用原生axios防止loading组件显示两次
import { Loading } from 'element-ui';
import ManageMember from './components/manageMember';
import QrCode from './components/qrCode';

let loading;
let options = {};
export default {
    name: 'groupManage',
    components: { ManageMember, QrCode },
    data() {
        return {
            dialogVisible: false,
            gourpForm: {
                groupname: '',
                desc: '',
                ispublic: false,
                maxusers: 200,
                approval: true,
                owner: 'admin',
                members: []
            },
            ispublicList: [{
                label: '公开',
                value: true
            }, {
                label: '不公开',
                value: false
            }],
            approvalList: [{
                label: '不需要',
                value: false
            }, {
                label: '需要',
                value: true
            }],
            gourpFormRules: {
                groupname: [
                    { required: true, message: '请输入群组名称', trigger: 'blur' }
                ],
                desc: [
                    { required: true, message: '请输入群组描述', trigger: 'blur' }
                ],
                ispublic: [
                    { required: true, message: '请选择是否公开', trigger: 'blur' }
                ],
                maxusers: [
                    { required: true, message: '请输入最大人数', trigger: 'blur' }
                ],
                approval: [
                    { required: true, message: '请选择是否需要审核', trigger: 'blur' }
                ]
            },
            tableData: [],
            tableDataAll: [],
            page: {
                cursor: '',//上次查询返回的游标，下次查询会查询本次查询后续的数据
                limit: 100//请求数据的大小
            },
            paging: {
                size: 10,
                total: 0,
                current: 1
            }

        };
    },
    mounted() {
        this.loadData();
    },
    methods: {
        //加载群组列表
        loadData() {
            //不使用全局的加载loading组件,等到群组详情查询完成了再关闭
            loading = Loading.service(options);
            let _this = this;
            axios.get('/api/easemob/queryGroupPage', { params: _this.page }).then(res => {
                //拿到群组数据
                let groupList = res.data.data.data;
                if (groupList.length <= 0) {
                    //关闭转loading
                    loading.close();
                    return;
                }
                //再拿到所有群的groupid集合 并转成字符串
                let groupIds = groupList.map(t => {
                    return t.groupid;
                }).join(',');
                //再查询群组详情
                _this.loadDataDetails(groupIds);
            });
        },
        //加载群组详情
        loadDataDetails(groupIds) {
            let _this = this;
            axios.get('/api/easemob/queryGroupDetails/' + groupIds, {}).then(res => {
                //把数据加入到表格数据中
                _this.tableDataAll = [];
                _this.tableDataAll.push(...res.data.data.data);
                //设置真正的表格数据
                _this.tableData = _this.tableDataAll.slice((_this.paging.current - 1) * _this.paging.size, _this.paging.current * _this.paging.size);
                //回写数据条数
                _this.paging.total = _this.tableDataAll.length;
                //关闭转loading
                loading.close();
            });
        },
        handleClose() {
            this.resetForm('gourpForm');
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
            this.dialogVisible = false;
            this.gourpForm = {
                groupname: '',
                desc: '',
                ispublic: false,
                maxusers: 200,
                approval: true,
                owner: 'admin',
                members: []
            };
        },
        submitForm(formName) {
            let _this = this;
            //如果id不为空，封装修改参数
            if (_this.gourpForm.id) {
                _this.gourpForm.editParams = {
                    id: _this.gourpForm.id,
                    groupname: _this.gourpForm.groupname,
                    description: _this.gourpForm.desc,
                    maxusers: _this.gourpForm.maxusers
                };
            }
            _this.$refs[formName].validate((valid) => {
                if (valid) {
                    _this.$axios.post('/api/easemob/' + (_this.gourpForm.id ? 'updateGroup' : 'createGroup'), _this.gourpForm.id ? _this.gourpForm.editParams : _this.gourpForm).then(res => {
                        if (res.data.data.data) {
                            _this.$notify({
                                showClose: true,
                                message: '恭喜你，操作成功',
                                type: 'success'
                            });
                            _this.loadData();
                        } else {
                            _this.$notify({
                                showClose: true,
                                message: res.data.data.error_description ? res.data.data.error_description : '操作失败',
                                type: 'error'
                            });
                        }
                        _this.resetForm(formName);
                    });
                } else {
                    return false;
                }
            });
        },
        editHandle(row) {
            this.gourpForm = {
                id: row.id,
                groupname: row.name,
                desc: row.description,
                ispublic: row.public,
                maxusers: row.maxusers,
                approval: row.membersonly,
                owner: 'admin',
                members: []
            };
            this.dialogVisible = true;
        },
        delHandle(id) {
            let _this = this;
            _this.$axios.delete('/api/easemob/deleteGroup/' + id).then(res => {
                if (res.data.data.data) {
                    _this.$notify({
                        showClose: true,
                        message: '恭喜你，操作成功',
                        type: 'success'
                    });
                    _this.loadData();
                } else {
                    _this.$notify({
                        showClose: true,
                        message: res.data.data.error_description ? res.data.data.error_description : '操作失败',
                        type: 'error'
                    });
                }
            });
        },
        handleSizeChange(val) {
            this.paging.size = val;
            this.loadData();
        },
        handleCurrentChange(val) {
            this.paging.current = val;
            this.loadData();
        },
        showManageMember(row) {
            this.$refs['manageMember'].show(row);
        },
        showQRCode(row) {
            this.$refs['qrCode'].show(row, 'GROUP');
        }
    }
};
</script>

<style scoped>
.form-tips {
    color: #999999;
    font-size: 12px;
}
</style>