<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head th:replace="components/vue/vue-list :: head('权限列表', 'list')"></head>
<body>
<div id="app">
    <el-row :gutter="10" style="margin:0 10px 0 10px;">
        <el-col :xs="24" :sm="16" :md="16" :lg="16" :xl="16">
            <template>
                <el-table border stripe size="medium" height="356" :data="tableData" highlight-current-row
                          style="font-size: 12px"
                          v-loading="tableLoading" cell-style="padding:1px">
                    <el-table-column align="center" type="index" :index="indexSerial" width="50"></el-table-column>
                    <el-table-column align="center" prop="id" label="id" width="180"></el-table-column>
                    <el-table-column align="center" prop="typeName" th:label="#{roleAuthority.typeCode}" width="160"></el-table-column>
                    <el-table-column align="center" prop="typeCode" th:label="#{roleAuthority.typeName}" width="160"></el-table-column>
                    <el-table-column align="center" th:label="#{operation}">
                        <template slot-scope="scope">
                            <el-button size="mini" type="primary" icon="el-icon-edit"
                                       @click="handleEdit(scope.$index, scope.row)">
                            </el-button>
                            <!--<el-button size="mini" type="danger" icon="el-icon-delete"
                                       @click="handleDelete(scope.$index, scope.row)">删除
                            </el-button>-->
                        </template>
                    </el-table-column>
                </el-table>
                <el-col class="toolbar" style="padding:10px;">
                    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageNo"
                                   :page-sizes="[10, 20, 30, 40]" :page-size="pageSize"
                                   layout="total, sizes, prev, pager, next, jumper" :total="total"
                                   style="float:right"></el-pagination>
                </el-col>
            </template>
        </el-col>
        <el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8">
            <el-card shadow="never">
                <div slot="header">
                    <span th:text="#{authority}"></span>: <span>{{ruleForm.authority}}</span>
                    <el-button style="float: right; padding: 3px 0" type="text" @click="submitForm('ruleForm')"><i class="fas fa-save" style="color: #409EFF"></i>&nbsp;<span th:text="#{save}"></span></el-button>
                </div>
                <div style="height:400px;overflow-y:auto;overflow-x:hidden;">
                    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="0px" class="demo-ruleForm" height="300px">
                        <el-form-item label="" prop="name">
                            <el-tree
                                    :data="treeData"
                                    show-checkbox
                                    default-expand-all
                                    node-key="id"
                                    ref="tree"
                                    highlight-current
                                    :props="defaultProps">
                            </el-tree>
                        </el-form-item>
                    </el-form>
                </div>
            </el-card>
        </el-col>
    </el-row>

</div>
</body>
<script th:src="@{/js/vue/common.js}"></script>
<script th:inline="javascript">
    /*<![CDATA[*/
    //Vue.http.options.emulateJSON = true;
    //Vue.http.options.emulateHTTP = true;
    var headerName = [[${_csrf.headerName}]];
    axios.defaults.headers.common[headerName] = [[${_csrf.token}]];

    //国际化
    international([[${session.locale}]]);

    var requestUrls = {
        list: "/api/roleAuthorities/data",
        add: "/api/roleAuthorities/add",
        edit: "",
        delete: "/api/roleAuthorities/ids/",
        authData: "/api/roleAuthorities/authData",
        updateAuth: "/api/roleAuthorities/updateAuth"
    };

    var app = new Vue({
        el: '#app',
        data: {
            tableData: [],
            pageNo: 1,
            pageSize: 10,
            total: 1000,
            tableLoading: true,
            searchForm: {
                typeName: '',
                typeCode: ''
            },
            treeData: [],
            checkedKeys: [],
            ruleForm: {
                ids: [],
                authority: ''
            },
            rules: {

            },
            defaultProps: {
                children: 'children',
                label: 'text'
            }
        },
        mounted: function () {
            this.loadData(this.pageNo, this.pageSize);
            //this.loadTreeData();
        },
        methods: {
            indexSerial(index) {
                return index + 1 + (this.pageNo - 1) * this.pageSize;
            },
            loadTreeData(){
                let params_ = {
                    typeCode: this.ruleForm.authority
                };
                this.$http.get(requestUrls.authData, {
                    params: params_
                }).then((response) => {
                    this.treeData = response.data.data;
                    this.setCheckedKeys();
                    this.$refs.tree.setCheckedKeys(this.checkedKeys);
                }).catch((error) => {
                    let errorMessage = [[#{requestError}]];
                    if (error.response) {
                        errorMessage = error.response.data.message;
                    }
                    parent.showError(errorMessage);
                });
            },
            setCheckedKeys() {
                //通过 key 设置
                loadChecked(this.treeData);
            },
            submitForm(formName) {
                parent.openLoading();
                this.ruleForm.ids = this.$refs.tree.getCheckedKeys();
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.$http.post(requestUrls.updateAuth, this.ruleForm).then((response) => {
                            parent.closeLoading();
                            parent.showSuccess([[#{updateSuccess}]]);
                            parent.updateListData();
                            closeLayer();
                        }).catch((error) => {
                            parent.closeLoading();
                            let errorMessage = [[#{requestError}]];
                            if (error.response) {
                                errorMessage = error.response.data.message;
                            }
                            parent.showError(errorMessage);
                        });
                    } else {
                        parent.closeLoading();
                        setTimeout(()=>{
                            let isError= document.getElementsByClassName("is-error");
                            isError[0].querySelector('input').focus();
                        },100);
                        return false;
                    }
                });
            },
            loadData(pageNo, pageSize) {
                if (!isNaN(pageNo)) {
                    this.pageNo = pageNo;
                }
                if (!isNaN(pageSize)) {
                    this.pageSize = pageSize;
                }
                var params_ = {
                    pageNo: this.pageNo,
                    pageSize: this.pageSize
                };
                Object.assign(params_, this.searchForm);
                for (let key in params_) {
                    if (isArray(params_[key])) {
                        params_[key] = params_[key].join(',');
                    }
                }

                this.tableLoading = true;
                this.$http.get(requestUrls.list, {
                    params: params_
                }).then((response) => {
                    this.tableLoading = false;
                    this.total = parseInt(response.data.total);
                    this.tableData = [];
                    for (let key in response.data.rows) {
                        this.$set(this.tableData, key, response.data.rows[key]);
                    }
                }).catch((error) => {
                    this.tableLoading = false;
                    let errorMessage = [[#{requestError}]];
                    if (error.response) {
                        errorMessage = error.response.data.message;
                    }
                    parent.showError(errorMessage);
                });
            },
            //每页显示数据量变更
            handleSizeChange(val) {
                this.pageSize = val;
                this.loadData(this.pageNo, this.pageSize);
            },
            //页码变更
            handleCurrentChange(val) {
                this.pageNo = val;
                this.loadData(this.pageNo, this.pageSize);
            },
            doSearch(event) {
                this.pageNo = 1;
                this.loadData(this.pageNo, this.pageSize);
            },
            doReset(event) {
                for (let i in this.searchForm) {
                    this.searchForm[i] = null;
                }
                this.doSearch(event);
            },
            formatSex(row, column) {
                let list = [[${sexTypeList}]];
                for (let i = 0; i < list.length; i++) {
                    if (String(row.sex) === String(list[i]["typeCode"])) {
                        return list[i]["typeName"];
                    }
                }
                return row.sex;
            },
            formatEnabled(row, column) {
                let list = [[${enabledStatusList}]];
                for (let i = 0; i < list.length; i++) {
                    if (String(row.enabled) === String(list[i]["typeCode"])) {
                        return list[i]["typeName"];
                    }
                }
            },
            formatHeadPhoto(row, column) {
                let value = row.headPhoto;
                if (!value) {
                    return '';
                }
                return '<img class="image-thumb" src="' + [[${filePathPrefix}]] + value + '" alt="头像" width="30px">';
            },
            handleEdit(index, row) {
                /*parent.showWindow({
                    title: '新增',
                    content: requestUrls.edit + row.typeCode
                });*/
                this.ruleForm.authority = row.typeCode;
                this.treeData = [];
                this.checkedKeys = [];
                this.loadTreeData();
            },
            handleDelete(index, row) {
                parent.showDelete(index, row);
            },
            doAdd(event) {
                parent.showWindow({
                    title: [[#{add}]],
                    content: requestUrls.add
                });
            },
            doEdit(event) {

            },
            doDelete(index, row) {
                this.$http.delete(requestUrls.delete + row.userId)
                    .then((response) => {
                        parent.showSuccess("删除成功");
                        this.loadData(this.pageNo, this.pageSize);
                    }).catch((response) => {
                    console.error(response);
                });
            },
            doImport(event) {
                this.$http.get("/api/authorities/import", {}).then(function (response) {
                    this.$notify({
                        title: '提示',
                        message: response.data.message,
                        position: 'bottom-right',
                        duration: 2000
                    });
                }).catch(function (response) {
                    console.error(response);
                });
            },
            doExport(event) {
                window.open("/api/authorities/export");
            }
        }
    });

    function iframeMethond(index, row) {
        console.log('iframeMethond');
        app.doDelete(index, row);
    }

    function iframeUpdateList() {
        app.loadData(app.pageNo, app.pageSize);
    }

    /**
     * 递归初始化选中
     */
    function loadChecked(treeData) {
        if (treeData && treeData.length) {
            for(let i = 0; i < treeData.length; i++){
                if (treeData[i].checked){
                    app.checkedKeys.push(treeData[i].id);
                }
                if (treeData[i].children && treeData[i].children.length) {
                    loadChecked(treeData[i].children);
                }
            }
        }
    }
    /*]]>*/
</script>
</html>