<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="url">
                        <el-input v-model="addForm.url"></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="url">
                        <el-input v-model="editorForm.url"></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 YQLJService from '@/api/youqinglianjie';
    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:    {
            defaultPageSizes,
            tableServiceData,
            paginationServiceData,
        },
        components: {
            myPagination,
            myTable,
        },
        data() {
            return {
                defaultPageSizes:  defaultPageSizes,
                addDialogVisit:    false,
                editorDialogVisit: false,
                searchData:        '',
                tableSelectData:   [],
                addForm:           {
                    name: '',
                    url:  '',
                },
                addRules:          {
                    name: [
                        { required: true, message: '友情链接名称不能为空', trigger: 'blur' },
                    ],
                    url:  [
                        { required: true, message: '友情链接不能为空', trigger: 'blur' },
                    ],
                },
                editorForm:        {
                    name: '',
                    url:  '',
                },
                editorRules:       {
                    name: [
                        { required: true, message: '友情链接名称不能为空', trigger: 'blur' },
                    ],
                    url:  [
                        { 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 YQLJService.getLinksAdd(opt);
                    if (res.code === 0) {
                        this.addDialogVisit = false;
                        const opt = this.getOption();
                        const myData = await YQLJService.getLinksList(opt);
                        this.initPageData(myData.data);
                        loading.close();
                    }
                } catch (e) {
                    loading.close();
                }
                this.addDialogVisit = false;
            },
            handleGetLinksInfo() {
                const opt = { hlId: this.selectRow.hlId };
                const loading = this.$loading({ background: 'rgba(0, 0, 0, 0.7)' });
                YQLJService.getLinksInfo(opt)
                           .then(res => {
                               const { name, url } = res.data;
                               this.editorForm.name = name;
                               this.editorForm.url = url;
                               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, hlId: this.selectRow.hlId });
                    const res = await YQLJService.getLinksUpdate(opt);
                    if (res.code === 0) {
                        this.editorDialogVisit = false;
                        const opt = this.getOption();
                        const myData = await YQLJService.getLinksList(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 = {
                    hlIds: [...this.tableSelectData],
                };
                const loading = this.$loading({ background: 'rgba(0, 0, 0, 0.7)' });
                try {
                    const res = await YQLJService.getLinksDelete(opt);
                    loading.close();
                    if (res.code === 0 && res.data) {
                        // 删除成功重置选择状态
                        this.tableSelectData = [];
                        // 刷新页面
                        const newOpt = this.getOption();
                        const res = await YQLJService.getLinksList(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)' });
                YQLJService.getLinksList(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();
        },
    };
</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>