<template>
    <div class="admin-YouQingLianJie">
        <!--    搜索    -->
        <div class="yqlj-search">
            <div>
                <el-input
                        class="search-name"
                        placeholder="请输入新闻分类名称"
                        v-model="searchData"
                        clearable>
                </el-input>
                <el-button size="mini" type="primary" @click="handleSearch">查询</el-button>
            </div>
            <div>
                <el-button size="mini" plain @click="handleDelete">删除</el-button>
                <el-button size="mini" type="primary" @click="handleOpenAdd">新增</el-button>
            </div>
        </div>
        <!--    table    -->
        <myTable
                class="yqlj-table"
                @editor="handleOpenEditor"
                @delete="handleDelete"
                @select-change="handleSelectChange" />

        <!--    分页    -->
        <myPagination
                class="yqlj-pagination"
                :pageSizes="defaultPageSizes"
                @size-change="handleSizeChange"
                @current-page="handleCurrentPage" />

        <!--    弹窗 新增   -->
        <el-dialog
                title="新增新闻分类"
                :visible.sync="addDialogVisit"
                width="30%"
                @close="handleResetLinks('addForm')"
                center>
            <div class="add-dialog-content">
                <el-form :model="addForm" :rules="addRules" ref="addForm" label-width="80px" class="demo-ruleForm">
                    <el-form-item label="名称:" prop="name">
                        <el-input v-model="addForm.name"></el-input>
                    </el-form-item>
                    <el-form-item label="序号:" prop="number">
                        <el-input v-model="addForm.number"></el-input>
                    </el-form-item>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button size="mini" @click="addDialogVisit = false">取 消</el-button>
                <el-button size="mini" type="primary" @click="handleAddLinks('addForm')">确 定</el-button>
            </span>
        </el-dialog>
        <!--    弹窗 编辑   -->
        <el-dialog
                title="编辑新闻分类"
                :visible.sync="editorDialogVisit"
                width="30%"
                @close="handleEditorReset('editorForm')"
                @open="handleGetLinksInfo"
                center>
            <div class="add-dialog-content">
                <el-form :model="editorForm" :rules="editorRules" ref="editorForm" label-width="80px"
                         class="demo-ruleForm">
                    <el-form-item label="名称:" prop="name">
                        <el-input v-model="editorForm.name"></el-input>
                    </el-form-item>
                    <el-form-item label="序号:" prop="number">
                        <el-input v-model="editorForm.number"></el-input>
                    </el-form-item>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button size="mini" @click="editorDialogVisit = false">取 消</el-button>
                <el-button size="mini" type="primary" @click="handleEditorLinks('editorForm')">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import myPagination             from './components/Pagination';
    import myTable                  from './components/Table';
    import * as NewsClassifyService from '@/api/newsClassify';
    import * as comminUtil          from '@/utils/admin/tools';
    import Vue                      from 'vue';

    const tableData = {
        myData: [],
    };
    const pagination = {
        page:  1,
        size:  10,
        total: 0,
    };
    const defaultPageSizes = [10, 20, 30, 40];

    const paginationServiceData = Vue.observable(pagination);
    const tableServiceData = Vue.observable(tableData);
    export default {
        name:       'YouQingLianJie',
        provide:    {
            tableServiceData,
            paginationServiceData,
        },
        components: {
            myPagination,
            myTable,
        },
        data() {
            return {
                defaultPageSizes:  defaultPageSizes,
                addDialogVisit:    false,
                editorDialogVisit: false,
                searchData:        '',
                tableSelectData:   [],
                addForm:           {
                    name:   '',
                    number: 0,
                },
                addRules:          {
                    name:   [
                        { required: true, message: '友情链接名称不能为空', trigger: 'blur' },
                    ],
                    number: [
                        { required: true, message: '序号不能为空', trigger: 'blur' },
                    ],
                },
                editorForm:        {
                    name:   '',
                    number: 0,
                },
                editorRules:       {
                    name:   [
                        { required: true, message: '友情链接名称不能为空', trigger: 'blur' },
                    ],
                    number: [
                        { required: true, message: '序号不能为空', trigger: 'blur' },
                    ],
                },
                userId:            null,
                selectRow:         null,
            };
        },
        computed:   {
            myPage() {
                return paginationServiceData.page;
            },
            mySize() {
                return paginationServiceData.size;
            },
            myTotal() {
                return paginationServiceData.total;
            },
        },
        methods:    {
            handleResetLinks(formName) {
                this.$refs[formName].resetFields();
                this.addDialogVisit = false;
            },
            handleAddLinks(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.addLinksFun();
                    } else {
                        return false;
                    }
                });
            },
            async addLinksFun() {
                const loading = this.$loading({ background: 'rgba(0, 0, 0, 0.7)' });
                try {
                    const opt = Object.assign({}, this.addForm, { userId: this.userId });
                    const res = await NewsClassifyService.getNewsClassifyAdd(opt);
                    if (res.code === 0) {
                        this.addDialogVisit = false;
                        const opt = this.getOption();
                        const myData = await NewsClassifyService.getNewsClassifyList(opt);
                        this.initPageData(myData.data);
                        loading.close();
                    }
                } catch (e) {
                    loading.close();
                }
                this.addDialogVisit = false;
            },
            handleGetLinksInfo() {
                const opt = { newsClassifyId: this.selectRow.newsClassifyId };
                const loading = this.$loading({ background: 'rgba(0, 0, 0, 0.7)' });
                NewsClassifyService.getNewsClassifyInfo(opt)
                                   .then(res => {
                                       const { name, number } = res.data;
                                       this.editorForm.name = name;
                                       this.editorForm.number = number;
                                       loading.close();
                                   })
                                   .catch(err => {
                                       loading.close();
                                   });
            },
            handleEditorReset(formName) {
                this.$refs[formName].resetFields();
                this.addDialogVisit = false;
            },
            handleEditorLinks(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.editorLinksFun();
                    } else {
                        return false;
                    }
                });
            },
            async editorLinksFun() {
                const loading = this.$loading({ background: 'rgba(0, 0, 0, 0.7)' });
                try {
                    const opt = Object.assign({}, this.editorForm, {
                        userId:         this.userId,
                        newsClassifyId: this.selectRow.newsClassifyId,
                    });
                    const res = await NewsClassifyService.getNewsClassifyUpdate(opt);
                    if (res.code === 0) {
                        this.editorDialogVisit = false;
                        const opt = this.getOption();
                        const myData = await NewsClassifyService.getNewsClassifyList(opt);
                        this.initPageData(myData.data);
                        loading.close();
                    }

                    loading.close();
                } catch (e) {
                    loading.close();
                }
                this.addDialogVisit = false;
            },
            getOption() {
                const opt = {
                    page: this.myPage,
                    size: this.mySize,
                    name: this.searchData,
                };
                return opt;
            },
            handleSearch() {
                paginationServiceData.page = 1;
                this.searchYouQingData();
            },
            handleOpenAdd() {
                this.addDialogVisit = true;
            },
            handleOpenEditor(data) {
                this.selectRow = data;
                this.editorDialogVisit = true;
            },
            async handleDelete() {
                if (!this.tableSelectData.length) {
                    this.$message.warning('请选择至少一条需要删除的数据');
                    return;
                }
                const opt = {
                    newsClassifyIds: [...this.tableSelectData],
                };
                const loading = this.$loading({ background: 'rgba(0, 0, 0, 0.7)' });
                try {
                    const res = await NewsClassifyService.getNewsClassifyDelete(opt);
                    loading.close();
                    if (res.code === 0 && res.data) {
                        // 删除成功重置选择状态
                        this.tableSelectData = [];
                        // 刷新页面
                        const newOpt = this.getOption();
                        const res = await NewsClassifyService.getNewsClassifyList(newOpt);
                        if (res.code === 0) {
                            this.initPageData(res.data);
                        }
                        loading.close();
                    }
                } catch (err) {
                    loading.close();
                }
            },
            searchYouQingData() {
                const opt = this.getOption();
                const loading = this.$loading({ background: 'rgba(0, 0, 0, 0.7)' });
                NewsClassifyService.getNewsClassifyList(opt)
                                   .then(res => {
                                       this.initPageData(res.data);
                                       loading.close();
                                   })
                                   .catch(err => {
                                       loading.close();
                                   });
            },
            handleSizeChange(size) {
                paginationServiceData.size = size;
                this.searchYouQingData();
            },
            handleCurrentPage(page) {
                paginationServiceData.page = page;
                this.searchYouQingData();
            },
            handleSelectChange(data) {
                this.tableSelectData = data;
            },
            initPageData(listData) {
                tableServiceData.myData = listData.data;
                paginationServiceData.total = listData.total;
            },
        },
        created() {
            const userAuth = comminUtil.getUserAuth();
            this.userId = userAuth && userAuth.userId ? userAuth.userId : null;
        },
        mounted() {
            this.searchYouQingData();
        },
        beforeDestroy() {
            Object.assign(tableServiceData, tableData);
            Object.assign(paginationServiceData, pagination);
        },
    };
</script>

<style lang="scss" scoped>
    .admin-YouQingLianJie {
        padding: 20px;

        .yqlj-search {
            display: flex;
            justify-content: space-between;
            margin-bottom: 20px;

            .search-name {
                width: 220px;
                margin-right: 10px;
            }
        }

        .yqlj-pagination {
            margin-top: 20px;
        }
    }
</style>