<template>
    <div class="page">
        <div class="searchArea">
            <el-form
                ref="form"
                v-model="search"
            >
                <el-form-item class="searchItem">
                    <el-select
                        size="small"
                        clearable
                        filterable
                        v-model="search.systemCode"
                        placeholder="系统名"
                    >
                        <el-option
                            v-for="(item, index) in dataSource"
                            :key="index"
                            :label="item.systemCode"
                            :value="item.systemCode"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item class="searchItem">
                    <el-input
                        v-model="search.tableName"
                        placeholder="表名(英)"
                        clearable
                        size="small"
                    ></el-input>
                </el-form-item>
                <el-form-item
                    clearable
                    class="searchItem"
                >
                    <el-input
                        v-model="search.tableCnName"
                        placeholder="表名(中)"
                        size="small"
                    ></el-input>
                </el-form-item>
                <!-- <el-form-item label="表描述"
                      clearable
                      class="searchItem">
          <el-input v-model="search.tableDesc"
                    size="small"></el-input>
        </el-form-item> -->
                <el-form-item class="searchItem">
                    <el-select
                        size="small"
                        clearable
                        filterable
                        v-model="search.tableType"
                        placeholder="表类型"
                    >
                        <el-option
                            v-for="item in typeList"
                            :key="item.index"
                            :label="item.typeName"
                            :value="item.value"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item
                    class="searchItem"
                    style="width:30%"
                >
                    <el-button
                        type="primary"
                        @click="searchData(1)"
                        size="small"
                        icon="el-icon-search"
                        v-privilege="activeMenu + 'QUERY'"
                    >查询</el-button>
                    <el-button
                        type="primary"
                        @click="cancel"
                        size="small"
                        icon="el-icon-refresh"
                        v-privilege="activeMenu + 'QUERY'"
                    >重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="controlBar">
            <el-button
                type="primary"
                size="small"
                icon="el-icon-circle-plus-outline"
                @click="addRow"
                v-privilege="activeMenu + 'ADD'"
            >新增</el-button>
            <el-button
                type="primary"
                size="small"
                icon="el-icon-tickets"
                @click="goPage('字段管理')"
                v-privilege="activeMenu + 'QUERY'"
            >字段</el-button>
            <el-button
                type="primary"
                size="small"
                icon="el-icon-share"
                @click="goPage('外键管理')"
                v-privilege="activeMenu + 'QUERY'"
            >关联</el-button>
            <el-button
                type="primary"
                size="small"
                icon="el-icon-refresh"
                @click="refreshAll"
                v-privilege="activeMenu + 'QUERY'"
            >全库刷新</el-button>
            <el-button
                type="primary"
                size="small"
                icon="el-icon-refresh"
                @click="refreshChoice"
                v-privilege="activeMenu + 'QUERY'"
            >选择刷新</el-button>
            <el-button
                type="primary"
                size="small"
                icon="el-icon-download"
                @click="singleTableExport"
                v-privilege="activeMenu + 'QUERY'"
            >导出表</el-button>
            <el-button
                type="primary"
                size="small"
                icon="el-icon-download"
                :loading="sysBtnLaoding"
                @click="dataSourceExport"
                v-privilege="activeMenu + 'QUERY'"
            >系统导出</el-button>
        </div>
        <!-- <div class="controlBar">
        <ul>
            <li @click="addRow">
                <i class="el-icon-circle-plus-outline"></i>
                <span>新增</span>
            </li>
            <li @click="editRow">
                <i class="el-icon-edit"></i>
                <span>编辑</span>
            </li>
            <li @click="deletRow">
                <i class="el-icon-delete"></i>
                <span>删除</span>
            </li>
            <li @click="showRow">
                <i class="el-icon-view"></i>
                <span>查看</span>
            </li>
            <li @click="goPage('字段管理')">
                <i class="el-icon-tickets"></i>
                <span>字段</span>
            </li>
            <li @click="goPage('外键管理')">
                <i class="el-icon-share"></i>
                <span>关联</span>
            </li>
            <li @click="refreshAll">
                <i class="el-icon-refresh"></i>
                <span>全库刷新</span>
            </li>
            <li @click="refreshChoice">
                <i class="el-icon-refresh"></i>
                <span>选择刷新</span>
            </li>
            <li @click="singleTableExport">
                <i class="el-icon-download"></i>
                <span>导出表</span>
            </li>
            <li @click="dataSourceExport">
                <i class="el-icon-download"></i>
                <span>系统导出</span>
            </li>
        </ul>
    </div> -->
        <div class="table">
            <el-table
                v-loading="tableLoading"
                :data="tableData"
                :height="tableHeight"
                :highlight-current-row='true'
                ref="singleTable"
                border
                @selection-change="selsChange"
            >
                <el-table-column
                    type="selection"
                    align="center"
                    width="50"
                ></el-table-column>
                <el-table-column
                    label="系统名"
                    :show-overflow-tooltip="true"
                    prop="systemCode"
                    width="150"
                    align="center"
                ></el-table-column>
                <el-table-column
                    prop="tableName"
                    :show-overflow-tooltip="true"
                    align="center"
                    label="表名(英)"
                ></el-table-column>
                <el-table-column
                    prop="tableCnName"
                    :show-overflow-tooltip="true"
                    align="center"
                    label="表名(中)"
                ></el-table-column>
                <el-table-column
                    prop="tableDesc"
                    :show-overflow-tooltip="true"
                    align="center"
                    width="300"
                    label="表描述"
                ></el-table-column>
                <el-table-column
                    prop="uiUrl"
                    :show-overflow-tooltip="true"
                    align="center"
                    label="UI界面"
                ></el-table-column>
                <el-table-column
                    prop="tableType"
                    :show-overflow-tooltip="true"
                    align="center"
                    :formatter="typeFormat"
                    label="表类型"
                    width="100"
                ></el-table-column>
                <el-table-column
                    prop="isVirtual"
                    :show-overflow-tooltip="true"
                    align="center"
                    :formatter="statusFormat"
                    width="70"
                    label="是否虚表"
                ></el-table-column>
                <el-table-column
                    prop="status"
                    :show-overflow-tooltip="true"
                    align="center"
                    width="70"
                    :formatter="statusFormat"
                    label="状态"
                ></el-table-column>
                <el-table-column
                    label="操作"
                    align="center"
                    width="250"
                    fixed="right"
                >
                    <template slot-scope="scope">
                        <el-button
                            type="danger"
                            size="small"
                            icon="el-icon-delete"
                            @click="deletRow(scope.row)"
                            v-privilege="activeMenu + 'DELETE'"
                        >删除</el-button>
                        <el-button
                            type="primary"
                            size="small"
                            icon="el-icon-edit"
                            @click="editRow(scope.row)"
                            v-privilege="activeMenu + 'PUT'"
                        >编辑</el-button>
                        <el-button
                            type="primary"
                            size="small"
                            icon="el-icon-view"
                            @click="showRow(scope.row)"
                            v-privilege="activeMenu + 'QUERY'"
                        >查看</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="yt-table-page">
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="pageIndex"
                :page-sizes="[10, 20, 30, 40, 100, 200]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
            >
            </el-pagination>
        </div>
        <!-- 弹窗 -->
        <el-dialog
            :title="oprtTitle"
            :visible.sync="dialogVisible"
            :before-close="handleClose"
            width="60%"
        >
            <detail
                v-if="dialogVisible"
                :code="status"
                :item="choiceItem"
                :dialogColose="dialogColose"
                @save="saveRow"
                @add="detailAddRow"
            ></detail>
        </el-dialog>
    </div>
</template>
<script>
import { getCookie } from '@/utils/util.js';
import qs from 'qs';
import detail from './detail'
export default {
    name: 'libraryTable',
    components: {
        detail
    },
    data () {
        return {
            activeMenu: '',
            tableLoading: false,
            search: {
                systemCode: '',
                tableName: '',
                tableCnName: '',
                // tableDesc: '',
                tableType: ''
            },
            typeList: [{
                typeName: '系统表',
                value: 1
            }, {
                typeName: '业务（应用）表',
                value: 2
            }, {
                typeName: '平台表',
                value: 3
            }, {
                typeName: '全部',
                value: ''
            }],
            sysCodes: [],
            tableData: [],
            dataSource: [],
            arrID: 0,
            pageIndex: 1,
            pageSize: 20,
            total: 0,
            searchStatus: false,
            tableHeight: null,
            dialogVisible: false,
            oprtTitle: '新增库表',
            status: 'add',
            choiceItem: {},
            dialogColose: false,
            sysBtnLaoding: false
        }
    },
    mounted: function () {
        let tableName = localStorage.getItem('tableName');
        if (tableName) {
            this.localTableName(tableName);
            localStorage.removeItem('tableName')
        } else {
            this.queryData();
        }
        this.getDataSource();
        this.$nextTick(() => {
            this.tableHeight = this.getRoleHeight(this.$refs['singleTable'].$el) - 70;
        });
    },
    created () {
        this.activeMenu = window.localStorage.getItem('activeMenu');
    },
    methods: {
        //  计算树区域高度
        getRoleHeight (dom) {
            return window.innerHeight - dom.offsetTop;
        },
        // 获取&查询数据
        queryData: function (status) {
            let that = this,
                defaultParms = {
                    pageSize: that.pageSize,
                    pageNum: that.pageIndex
                },
                params = status || defaultParms,
                getUrl = 'pass/v1/mdtables/';
            that.tableLoading = true;
            that.axios.get(getUrl, {
                params: params
            }
            ).then(function (response) {
                if (response) {
                    let data = response.data;
                    that.tableData = data.list;
                    that.total = data.total;
                    if (that.sysCodes.length === 0) {
                        that.sysCodes = that.tableData.reduce((arr, item) => {
                            if (that.sysCodes.indexOf(item.systemCode) === -1 && item.systemCode) {
                                arr.push(item.systemCode)
                            }
                            return arr
                        }, [])
                    }
                }
                that.tableLoading = false;
            }).catch(function () {
                that.tableLoading = false;
            });
        },
        // 选中事件切换
        selsChange (val) {
            var valIdx = [];
            for (var i = 0; i < val.length; i++) {
                var arrIDsame = false;
                valIdx.push(val[i]);
            }
            this.arrID = valIdx;
        },
        // 搜索
        searchData (num) {
            let that = this,
                params = {
                    pageSize: that.pageSize,
                    pageNum: 1,
                    systemCode: that.search.systemCode,
                    tableName: that.search.tableName,
                    tableCnName: that.search.tableCnName,
                    tableType: that.search.tableType
                };
            that.pageIndex = 1;
            that.searchStatus = true;
            that.queryData(params);
        },
        // 取消
        cancel () {
            let that = this;
            that.search.systemCode = '';
            that.search.tableName = '';
            that.search.tableCnName = '';
            that.search.tableType = '';
            that.search.tableDesc = '';
            that.searchStatus = false;
            for (let i in this.search) {
                this.searchData[i] = null
            }
            //   that.queryData();
        },
        // 分页方法
        handleCurrentChange (pageIndex) {
            this.pageIndex = pageIndex
            this.searchStatus ? this.searchData() : this.queryData();
        },
        handleSizeChange (pageSize) {
            this.pageIndex = 1
            this.pageSize = pageSize;
            this.searchStatus ? this.searchData() : this.queryData();
        },
        // 刷新
        refreshAll () {
            let that = this;
            that.tableLoading = true;
            that.axios.post('pass/v1/mdtables/updateall').then(function (response) {
                if (response) {
                    that.$message.success(response.data.message)
                }
                that.tableLoading = false;
            }).catch(function () {
                that.tableLoading = false;
            });
        },
        // 选择刷新
        refreshChoice () {
            let that = this,
                params = that.arrID;
            if (!params) {
                this.$message.error('请选择一条数据')
            } else {
                that.tableLoading = true;
                that.axios.post('pass/v1/mdtables/updatepart', JSON.stringify(params), {
                    diy: true,
                    headers: {
                        'Content-Type': 'application/json;charset=UTF-8'
                    }
                }).then(function (response) {
                    if (response.code === '0') {
                        that.$message.success(response.message)
                    }
                    that.tableLoading = false;
                }).catch(function () {
                    that.tableLoading = false;
                });
            }
        },
        getDataSource () {
            let that = this;
            that.axios.get('pass/v1/mdtables/queryDatasource').then(res => {
                if (res.code === '0') {
                    that.dataSource = res.data;
                }
            }).catch(() => { })
        },
        // 编辑 新增 删除 查看 前往其他页面
        addRow () {
            //   this.$router.push({ name: 'librarayDetail', params: { code: 'add' } })
            this.oprtTitle = '新增库表';
            this.status = 'add';
            this.choiceItem = {};
            this.dialogVisible = true;
            this.dialogColose = false;
        },
        editRow (item) {
            // this.$router.push({ name: 'librarayDetail', params: { code: 'edit', data: this.arrID[0] } })
            this.oprtTitle = '修改库表';
            this.status = 'edit';
            this.choiceItem = item;
            this.dialogVisible = true;
            this.dialogColose = false;
        },
        deletRow (item) {
            let that = this;
            const h = this.$createElement;
            this.$msgbox({
                title: '删除数据',
                message: h('p', null, [
                    h('span', null, '确定要删除该条数据吗？ ')
                ]),
                showCancelButton: true,
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                beforeClose: (action, instance, done) => {
                    if (action === 'confirm') {
                        instance.confirmButtonText = '删除中...';
                        that.axios.delete('pass/v1/mdtables/' + item.id).then(function (response) {
                            if (response) {
                                done();
                                that.queryData();
                            }
                            that.tableLoading = false;
                        }).catch(function () {
                            that.tableLoading = false;
                        });
                    } else {
                        done();
                    }
                }
            }).then(action => {
                this.$message.success('删除成功');
            });
        },
        showRow (item) {
            // this.$router.push({ name: 'librarayDetail', params: { code: 'show', data: this.arrID[0] } })
            this.oprtTitle = '查看库表';
            this.status = 'show';
            this.dialogVisible = true;
            this.choiceItem = item;
            this.dialogColose = false;
        },
        goPage (pageName) {
            let that = this;
            if (that.arrID.length > 1) {
                that.$message.error('最多选择一条数据');
            } else if (!that.arrID.length) {
                that.$message.error('请选择一条数据');
            } else {
                localStorage.setItem('tableName', that.arrID[0].tableName)
                let menuList = window.top.document.getElementsByClassName('el-menu-item');
                let tabList = window.top.document.getElementsByClassName('el-tabs__item');
                for (let i = 0; i < tabList.length; i++) {
                    if (tabList[i].childNodes[0].innerText.replace(/\s/g, '') === pageName) {
                        tabList[i].childNodes[1].click();
                    }
                }
                for (let i = 0; i < menuList.length; i++) {
                    if (menuList[i].innerHTML === pageName) {
                        setTimeout(() => {
                            menuList[i].click();
                        }, 100)
                    }
                }
            }
        },
        // 表格计算属性
        typeFormat (row, column) {
            let type = row[column.property],
                typeName = '';
            if (type === '1') {
                typeName = '系统表'
            } else if (type === '2') {
                typeName = '业务（应用）表'
            } else {
                typeName = '平台表'
            }
            return typeName;
        },
        statusFormat (row, column) {
            let status = '';
            if (column.property === 'isVirtual') {
                status = row[column.property] === 1 ? '数据结构来源于API ' : '实体表';
            } else {
                status = row[column.property] === 1 ? '无效 ' : '有效';
            }
            return status;
        },
        singleTableExport () {
            if (!this.arrID.length) {
                this.$message.error('至少选择一条数据导出');
            } else {
                let that = this;
                let id = '';
                for (let i = 0; i < that.arrID.length; i++) {
                    if (i === 0) {
                        id += that.arrID[i].tableId
                    } else {
                        id += ',' + that.arrID[i].tableId
                    }
                }
                that.axios.get('pass/v1/mdtables/exportSingleTable', {
                    params: {
                        id
                    },
                    responseType: 'blob'
                }
                ).then(res => {
                    if (res) {
                        var blob = new Blob([res], { type: 'application/actet-stream;charset=utf-8' });
                        var filename = that.arrID.length > 1 ? 'tables.xlsx' : that.arrID[0].tableId + '.xlsx';
                        var downloadElement = document.createElement('a');
                        var href = window.URL.createObjectURL(blob); // 创建下载的链接
                        downloadElement.style.display = 'none';
                        downloadElement.href = href;
                        downloadElement.download = filename; // 下载后文件名
                        document.body.appendChild(downloadElement);
                        downloadElement.click(); // 点击下载
                        document.body.removeChild(downloadElement); // 下载完成移除元素
                        window.URL.revokeObjectURL(href); // 释放掉blob对象
                    }
                })
            }
        },
        dataSourceExport () {
            if (this.arrID.length > 1) {
                this.$message.error('最多选择一个系统');
            } else if (!this.arrID.length) {
                this.$message.error('至少选择一个系统');
            } else {
                let that = this;
                that.sysBtnLaoding = true;
                that.axios.get('pass/v1/mdtables/exportSingleAllTable', {
                    params: {
                        systemCode: that.arrID[0].systemCode
                    },
                    responseType: 'blob'
                }).then(res => {
                    if (res) {
                        var blob = new Blob([res], { type: 'application/actet-stream;charset=utf-8' });
                        var filename = that.arrID[0].systemCode + '.zip';
                        var downloadElement = document.createElement('a');
                        var href = window.URL.createObjectURL(blob); // 创建下载的链接
                        downloadElement.style.display = 'none';
                        downloadElement.href = href;
                        downloadElement.download = filename; // 下载后文件名
                        document.body.appendChild(downloadElement);
                        downloadElement.click(); // 点击下载
                        document.body.removeChild(downloadElement); // 下载完成移除元素
                        window.URL.revokeObjectURL(href); // 释放掉blob对象
                    }
                    that.sysBtnLaoding = false;
                }).catch(() => {
                    that.sysBtnLaoding = false;
                })
            }
        },
        handleClose () {
            this.dialogColose = true;
            this.dialogVisible = false;
        },
        saveRow (item) {
            let index = this.getRowIndex(item);
            this.dialogVisible = false;
            this.$nextTick(() => {
                this.$refs['singleTable'].setCurrentRow(this.tableData[index]);
            })
        },
        detailAddRow (item) {
            this.tableData.unshift(item);
            this.dialogVisible = false;
            this.$nextTick(() => {
                this.$refs['singleTable'].setCurrentRow(this.tableData[0]);
            })
        },
        getRowIndex (item) {
            let index = 0;
            for (let i = 0; i < this.tableData.length; i++) {
                if (this.tableData[i].id === item.id) {
                    for (let a in item) {
                        this.tableData[i][a] = item[a]
                    }
                    index = i;
                    break;
                }
            }
            return index
        },
        localTableName (name) {
            let that = this,
                params = {
                    pageSize: that.pageSize,
                    pageNum: 1,
                    systemCode: name,
                    tableName: '',
                    tableCnName: '',
                    tableType: ''
                };
            that.pageIndex = 1;
            that.searchStatus = true;
            that.queryData(params);
        }
    },
    beforeDestroy () {
        localStorage.removeItem('tableName')
    }
}
</script>

<style scoped>
.page {
    padding: 15px;
}
header {
    width: 100%;
    height: 50px;
    background: rgb(248, 248, 248);
    padding-left: 10px;
    font-size: 15px;
    color: #000;
    line-height: 50px;
    margin-bottom: 10px;
}
/* 搜索 */
.searchArea {
    /* border-bottom: solid 1px rgb(68, 68, 68); */
    text-align: left;
}
.searchItem {
    width: 15%;
    margin-right: 10px;
    display: inline-block;
}
/* .searchItem .el-input {
  width: 200px;
} */
.searchItem .el-select {
    width: 100%;
}
.searchButton {
    width: 100%;
    text-align: center;
}
.searchButton button {
    display: inline-block;
}
/* 控制条 */
.controlBar {
    /* text-align: right; */
    padding-top: 7px;
    border-top: 1px solid #ccc;
    margin-top: -7px;
}
/* .controlBar {
  padding: 0px 10px 10px 10px;
  border-bottom: solid 1px rgb(68, 68, 68);
  text-align: left;
  margin-top: 10px;
}
.controlBar ul li {
  list-style: none;
  width: 60px;
  height: 40px;
  cursor: pointer;
  display: inline-block;
  margin-right: 5px;
}
.controlBar ul li:hover {
  color: #70baf2;
}
.controlBar ul li i {
  width: 60px;
  height: 20px;
  font-size: 20px;
  text-align: center;
}
.controlBar ul li span {
  display: inline-block;
  width: 60px;
  height: 20px;
  font-size: 12px;
  line-height: 20px;
  text-align: center;
} */
.table {
    margin-top: 10px;
    margin-bottom: 10px;
}
</style>
