<template>
    <div>
        <div class="filters-container">

            <el-input v-if="isModulesShow('search')" placeholder="关键字" size="small" v-model="filter1" clearable class="filter-item"></el-input>

            <el-button v-if="isModulesShow('search')" @click="getData" type="primary" size="small" icon="el-icon-search" class="filter-item">搜索
            </el-button>

            <el-button v-if="isModulesShow('query')" @click="showAdvancedQueryDialog = !showAdvancedQueryDialog" type="primary" size="small" icon="el-icon-search" class="filter-item">高级查询
            </el-button>

            <el-button v-if="isModulesShow('add')" @click="$router.push({path:'/commonQuery',query:{code:$route.query.code,column:$route.query.column}})" type="primary" size="small" icon="el-icon-edit" class="filter-item">添加
            </el-button>

            <el-dropdown trigger="click" size="medium" class="table-column-filter">
                <span>
                    筛选数据
                    <i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown" class="table-column-filter-wrapper">
                    <el-checkbox v-for="item in tableColumns" :key="item.name" v-model="item.show">{{item.remark}}
                    </el-checkbox>
                </el-dropdown-menu>
            </el-dropdown>
        </div>
        <el-table :data="tableData" :height="tableHeight" row-key="id" ref="table" @sort-change="changeTableSort">
            <el-table-column type="index" min-width="50" align="center">
            </el-table-column>
            <template v-for="item in tableColumns" v-if="isColumnShow(item.name)">
                <el-table-column v-if="item.formType=='datetime'" :formatter="DateTimeFormatter" sortable="custom" :prop="item.name" :label="item.remark" min-width="100">
                </el-table-column>

                <el-table-column v-else-if="item.formType=='date'" :formatter="DateFormatter" sortable="custom" :prop="item.name" :label="item.remark" min-width="100">
                </el-table-column>

                <el-table-column v-else-if="item.formType=='singleImage'" :prop="item.name" :label="item.remark" min-width="100">
                    <template slot-scope="{row}">
                        <img :src="row[item.name]" @click="showImg(row[item.name])" style="width: 100px;height: 100px;vertical-align: middle;" />
                    </template>
                </el-table-column>
                <el-table-column v-else sortable="custom" :prop="item.name" :label="item.remark" min-width="100">
                </el-table-column>
            </template>
            <el-table-column label="操作" align="center" fixed="right" v-if="isModulesShow('edit')">
                <template slot-scope="scope">

                    <template v-for="subtable in subtables">
                        <el-button @click="$router.push({path:'/commonQuerys',query:{code:subtable.subCode,column:scope.row[subtable.column]+','+subtable.subColumn}})" type="primary" size="small" plain>{{subtable.name}}
                        </el-button>
                    </template>
                    <el-button v-if="isModulesShow('edit')" @click="editRow(scope.row)" type="primary" size="mini" plain>编辑</el-button>
                    <el-button v-if="isModulesShow('del')" @click="deleteRow(scope.row)" type="danger" size="mini" plain>删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination-wrapper">
            <el-pagination background @size-change="pageSizeChange" @current-change="currentPageChange" :current-page="currentPage" :page-sizes="[10, 20, 30, 40, 50]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="totalNumber">
            </el-pagination>
        </div>

        <el-dialog title="查看图片" :visible.sync="imageDialogVisible" size="small">
            <img width="100%" :src="imgSrc" alt="">
        </el-dialog>

        <el-dialog title="高级查询" :visible.sync="showAdvancedQueryDialog">
            <el-button @click="addField" type="text" icon="el-icon-plus">添加</el-button>
            <el-table :data="advancedQueryFields">

                <el-table-column prop="link" label="链接符" align="center">
                    <template slot-scope="{row}">
                        <el-select placeholder="链接" size="small" v-model="row.link" class="filter-item">
                            <el-option label="AND" value="AND">
                            </el-option>
                            <el-option label="OR" value="OR">
                            </el-option>
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column prop="name" label="字段" align="center">
                    <template slot-scope="{row}">
                        <el-select v-model="row.name">

                            <el-option v-for="item in tableColumns" :label="item.remark" :value="item.name" :key="item.name"></el-option>
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column prop="searchMethod" label="搜索方式" width="150" align="center">
                    <template slot-scope="{row}">
                        <el-select v-model="row.searchMethod">
                            <el-option v-for="item in searchMethods" :label="item" :value="item" :key="item"></el-option>
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column prop="value" label="参数" align="center">
                    <template slot-scope="{row}">
                        <el-input v-model="row.value"></el-input>
                    </template>
                </el-table-column>
                <el-table-column width="60" align="center">
                    <template slot-scope="{ row, column, $index }">
                        <el-button @click="removeField($index)" size="small" type="text">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <span slot="footer" class="dialog-footer">

                <el-button @click="advancedQuery" :loading="$store.state.fetchingData">确定</el-button>
            </span>
        </el-dialog>

    </div>
</template>
<script>
import { mapState } from 'vuex'
import { format } from 'date-fns'
import zh from 'date-fns/locale/zh_cn'

export default {
    created() {
        this.getTableBase();
    },
    data() {
        return {
            totalNumber: 0,
            totalPage: 10,
            currentPage: 1,
            pageSize: 20,
            tableData: [],
            filter1: '',
            filter2: '',
            advancedQuerySearchKey: '',
            tableColumns: [],
            databasetype: 'Mysql',
            tableName: '',
            imgSrc: '',
            imageDialogVisible: false,
            showAdvancedQueryDialog: false,
            advancedQueryFields: [],
            searchMethods: ['=', '!=', '>', '>=', '<', '<=', 'like'],
            searchColumn: '',
            orderByStr: '',
            modules: [],
            dataSourceCode: 'dataSource',
            subtables: [],

        }
    },
    computed: {
        ...mapState(['tableHeight']),
        selection() {
            return this.$refs.table.selection.map(i => i.id);
        }
    },
    methods: {
        getTableBase() {
            this.tableColumns = [];
            this.tableData = [];
            this.modules = [];
            this.filter1 = '';
            this.advancedQuerySearchKey = '';
            this.orderByStr = '';
            this.subtables = [];



            this.$http.get({
                url: '/queryConfig/getOne',
                data: {
                    code: this.$route.query.code,
                }
            }).then(res => {
                if (res.success) {


                    if (res.data) {



                        this.modules = res.data.modules.split(',');

                        this.tableName = res.data.tableName;
                        this.databasetype = res.data.databasetype;
                        this.dataSourceCode = res.data.dataSourceCode;

                        // var tableColumnsStr = res.data.tablecolumns;

                        // var columns = tableColumnsStr.split('_;');


                        // columns.forEach(element => {
                        //     var items = element.split('_,');
                        //     var temp = {
                        //         label: items[0],
                        //         value: items[1],
                        //         type: items[2] ? items[2] : 'text',
                        //         show: true
                        //     }

                        //     this.tableColumns.push(temp);
                        // });

                        var columns = JSON.parse(res.data.configJson)
                        columns.forEach(element => {
                            element.show = true;
                            this.tableColumns.push(element);
                        });

                        if (res.data.subJson) {

                            this.subtables = JSON.parse(res.data.subJson)
                        }



                        this.getData();
                    }

                }
            })
        },
        pageSizeChange(size) {
            this.currentPage = 1;
            this.pageSize = size;
            this.getData();
        },
        currentPageChange(page) {
            this.currentPage = page;
            this.getData();
        },
        getData() {

            if (this.tableColumns.length > 0) {

                var templist = [];

                this.tableColumns.forEach(item => {
                    if (item.formType != 'date' && item.formType != 'datetime' && item.show) {
                        templist.push(item.name);
                    }
                })

                if (templist.length > 0) {

                    this.searchColumn = templist.join('_,');

                }
            }


            if (this.$route.query.column) {
                var tempColumn = this.$route.query.column;
                var tempSearchKey = 'AND' + '_,' + tempColumn.split(',')[1] + '_,' + '=' + '_,' + tempColumn.split(',')[0];
                if (this.advancedQuerySearchKey) {
                    this.advancedQuerySearchKey = this.advancedQuerySearchKey + '_;' + tempSearchKey;
                } else {
                    this.advancedQuerySearchKey = tempSearchKey;
                }
            }


            this.$http.get({
                url: '/commonQuery/page',
                data: {
                    currentPage: this.currentPage,
                    pageNumber: this.pageSize,
                    advancedQuery: this.advancedQuerySearchKey,
                    tableName: this.tableName,
                    databasetype: this.databasetype,
                    searchColumn: this.searchColumn,
                    searchKey: this.filter1,
                    orderByStr: this.orderByStr,
                    dataSourceCode: this.dataSourceCode,
                }
            }).then(res => {
                if (res.success) {

                    this.totalNumber = res.data.page.totalNumber;
                    this.tableData = res.data.pp;
                }
            })
        },
        isColumnShow(column) {
            var row = this.tableColumns.find(i => i.name === column);
            return row ? row.show : false;
        },

        isModulesShow(column) {
            var row = this.modules.find(i => i === column);
            return row ? true : false;
        },

        DateTimeFormatter(row, column, cellValue) {
            if (cellValue) {
                return format(cellValue, 'YYYY/MM/DD HH:mm', { locale: zh })
            }

        },
        DateFormatter(row, column, cellValue) {
            if (cellValue) {
                return format(cellValue, 'YYYY/MM/DD', { locale: zh })
            }

        },
        showImg(img) {
            this.imgSrc = img;
            this.imageDialogVisible = true;
        },

        addField() {
            this.advancedQueryFields.push({
                link: 'AND',
                name: '',
                searchMethod: '=',
                value: '',
            });
        },
        removeField(i) {
            if (this.advancedQueryFields.length > 0) {
                this.advancedQueryFields.splice(i, 1);
            }
        },
        advancedQuery() {

            this.advancedQuerySearchKey = '';

            if (this.advancedQueryFields.length > 0) {

                var templist = [];

                this.advancedQueryFields.forEach(item => {
                    if (item.link && item.name && item.searchMethod && item.value) {
                        var tempItem = item.link + '_,' + item.name + '_,' + item.searchMethod + '_,' + item.value;
                        templist.push(tempItem);
                    }
                })

                if (templist.length > 0) {

                    this.advancedQuerySearchKey = templist.join('_;');
                }
            }

            this.getData();
            this.showAdvancedQueryDialog = false;
        },
        changeTableSort(column) {
            if (column.prop) {

                var order = 'asc'

                if ('descending' == column.order) {
                    order = 'desc';
                }


                this.orderByStr = column.prop + '_,' + order;

                this.getData();
            }
        },
        editRow(row) {
            this.$router.push({
                path: '/commonQuery',
                query: {
                    id: row.id || row.ID,
                    code: this.$route.query.code,
                    column: this.$route.query.column,
                }
            })
        },

        deleteRow(row) {
            this.$alert('删除将无法恢复，确认要删除么？', '警告', { type: 'error' }).then(() => {
                return this.$http.post({
                    url: '/commonQuery/del',
                    data: {
                        tableName: this.tableName,
                        primaryKey: row.id || row.ID,
                        databasetype: this.databasetype,
                        dataSourceCode: this.dataSourceCode,
                    }
                })
            }).then(() => {
                this.$message.success('删除成功');
                this.getData();
            }).catch(action => {
                if (action === 'cancel') {
                    this.$message.info('删除取消');
                } else {
                    this.$message.error('删除失败');
                }
            })
        },


    },
    watch: {
        $route() {
            this.getTableBase()
        }
    },

}
</script>
<style lang="less" scoped>
</style>
