<template>
    <div class="batchTableComent">
        <dialog-table :visible.sync="visible" :title="title" width="60%" @close="$emit('update:visible', false)">
            <template v-slot:btns>
                <el-button type="primary" plain size="mini" icon="el-icon-delete" @click="del('btach')">批量删除</el-button>
                <el-button type="primary" plain size="mini" icon="el-icon-delete" @click="del('all')">全部删除</el-button>
            </template>

            <template v-slot:table>
                <el-table
                    v-loading="loading"
                    :data="tableData"
                    border
                    @selection-change="$event => multipleSelection = $event"
                    :max-height="500"
                >
                    <el-table-column type="selection" width="50"></el-table-column>
                    <el-table-column v-for="(item, index) in colsList" :key="index" :label="item.label" :prop="item.prop" width="150" :show-overflow-tooltip="true">
                        <template slot-scope="scope">
                            <template v-if="item.prop == 'filterCount'">
                                <el-tooltip v-if="scope.row.filterCount" effect="dark" placement="top" :content="scope.row.filterCount">
                                    <span style="cursor: pointer">{{ scope.row.filterCount.split(/\)\sAND\s\(/g).filter(el => el != '' && /[^\s]/g.test(el)).length }}</span>
                                </el-tooltip>
                                <span v-else>0</span>
                            </template>
                            <template v-else>
                                <span :style="item.prop == 'focusFields' ? 'cursor: pointer' : ''">{{ scope.row[item.prop] }}</span>
                            </template>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="70">
                        <template slot-scope="scope">
                            <el-tooltip effect="dark" placement="top" :content="'根据' + (type == 'collection' ? '收藏' : '历史') + '条件查询'">
                                <i @click="search(scope.row)" style="cursor: pointer;color: #6aa6ce;margin-right: 3px;" class="el-icon-search"></i>
                            </el-tooltip>
                            <el-tooltip effect="dark" placement="top" :content="'删除' + (type == 'collection' ? '收藏' : '历史') + '条件'">
                                <i @click="del('single', scope.row)" style="cursor: pointer;color: #ec5759" class="el-icon-delete"></i>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                </el-table>
            </template>

            <template v-slot:pagination>
                <el-pagination
                    :current-page="start"
                    :page-sizes="[10, 20, 50, 100]"
                    :page-size="limit"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"
                    @size-change="sizeChange"
                    @current-change="currentChange"
                >
                </el-pagination>
            </template>
        </dialog-table>
    </div>
</template>

<script>
import dialogTable from './dialogTable.vue'
import i18n from '../../i18n'
import { spliceSql } from '../../utils'
import {
    getConditionCollect,
    getSearchHistory,
    delConditionCollect,
    delSearchHistory,
} from '../../api/fence.js'
export default {
    props: {
        title: {
            type: String,
            require: true
        },
        visible: {
            type: Boolean,
            require: true
        },
        // collection收藏 // history历史记录
        type: {
            type: String,
            require: true
        },
        allFields: {
            type: Array,
            default: () => []
        },
        filterConditionList: {
            type: Array,
            default: () => []
        }
    },
    components: {
        dialogTable
    },
    computed: {
        colsList() {
            return this.type == 'collection' ? this.collectionColsList : this.historyColsList
        }
    },
    watch: {
        visible(val) {
            if (val) this.getList()
            else if (this.isDel && this.type == 'collection') this.$emit('delSuccess')
        }
    },
    data() {
        return {
            collectionColsList: [
                { label: '名称', prop: 'name' },
                { label: '收藏时间', prop: 'collectTime' },
                { label: '查询语句', prop: 'queryStatements' },
                { label: '起始时间', prop: 'startTime' },
                { label: '结束时间', prop: 'endTime' },
                { label: '过滤条件数目', prop: 'filterCount' },
                { label: '关注字段', prop: 'focusFields' }
            ],
            historyColsList: [
                { label: '检索时间', prop: 'queryTime' },
                { label: '查询语句', prop: 'queryStatements' },
                { label: '起始时间', prop: 'startTime' },
                { label: '结束时间', prop: 'endTime' },
                { label: '过滤条件数目', prop: 'filterCount' }
            ],
            tableData: [],
            multipleSelection: [],
            total: 0,
            start: 1,
            limit: 10,
            loading: false,
            isDel: false
        }
    },
    methods: {
        getList() {
            let interfaces = this.type == 'collection'
                ? getConditionCollect
                    : getSearchHistory
            let params = {
                page: {
                    size: this.limit,
                    current: this.start
                }
            }
            this.loading = true
            interfaces(params).then(res => {
                if (res.data.returnCode == 0) {
                    let { data } = res.data
                    this.tableData = data.list
                    this.total = data.page.total
                }
                this.loading = false
            }).catch(() => {
                this.loading = false
            })
        },
        search(row) {
            this.$emit('update:filterConditionList', [])
            if (row.filterCount) {
                let allKeyValue = row.filterCount.split(/\)\sAND\s\(/g).map(el => el.replace(/\(|\)/g, '')).filter(el => el != '')                
                allKeyValue.forEach(el => {
                    let arr = null, addFilterRootSelect = 'AND';
                    let key = '',value = '',symbol = '', name = '', query = '';
                    if (el.includes('AND')) {
                        arr = el.split('AND')
                        addFilterRootSelect = 'AND'
                    } else if (el.includes('OR')) {
                        arr = el.split('OR')
                        addFilterRootSelect = 'OR'
                    } else {
                        arr = [el]
                    }

                    for (let i = 0; i < arr.length; i++) {
                        let keyValue = arr[i].split(':')
                        let sy = ''
                        if (!/NOT|\*|\>|\<|\=|\(|\)/.test(arr[i])) {
                            sy = '1'
                        } else if (!/\*|\>|\<|\=|\(|\)/.test(arr[i])) {
                            sy = '2'
                        } else if (/\*/g.test(arr[i]) && keyValue[1] != '*') {
                            sy = '3'
                        } else if (!/NOT|\*|\<|\=|\(|\)/.test(arr[i])) {
                            sy = '4'
                        } else if (!/NOT|\*|\>|\=|\(|\)/.test(arr[i])) {
                            sy = '5'
                        } else if (!/NOT|\*|\<|\(|\)/.test(arr[i])) {
                            sy = '6'
                        } else if (!/NOT|\*|\>|\(|\)/.test(arr[i])) {
                            sy = '7'
                        } else if (!/NOT|\*|\>|\<|\=/.test(arr[i])) {
                            sy = '8'
                        } else if (!/\*|\>|\<|\=/.test(arr[i])) {
                            sy = '9'
                        } else if (keyValue[1] == '*') {
                            sy = '10'
                        } else {
                            sy = '11'
                        }
                        keyValue[0] = keyValue[0].replace(/NOT|\>|\<|\=|\*|\(|\)/g, '').trim()
                        keyValue[1] = keyValue[1].replace(/NOT|\>|\<|\=|\*|\(|\)|\"/g, '').trim()
                        let current = this.allFields.filter(item => item.dataStr == keyValue[0].trim())[0] || keyValue[0]
                        key += (keyValue[0] + ',');
                        symbol += (sy + ',');
                        value += (keyValue[1] + ',');
                        name += (`${spliceSql(current.dataName, sy, keyValue[1]).name} ${arr.length - 1 == i ? '' : addFilterRootSelect} `)
                        query += (`${spliceSql(keyValue[0], sy, keyValue[1]).query} ${arr.length - 1 == i ? '' : addFilterRootSelect} `)
                    }
                    this.$emit('add', {
                        key: key.endsWith(',') ? key.substring(0, key.lastIndexOf(',')) : key,
                        value, 
                        symbol,
                        name,
                        query,
                        status: 'positive', 
                        disabled: false
                    })
                })
            }
            this.$emit('query', [row.queryStatements, [row.startTime, row.endTime]]);
            this.$emit('update:visible', false)
        },
        del(type, row = {}) {
            if (type == 'btach' && !this.multipleSelection.length) {
                this.$message.warning(`请选择要删除的${this.type == 'collection' ? '收藏条件' : '历史记录'}`)
                return
            }

            let message = `是否确认删除${type == 'all' ? '全部' : type == 'single' ? '该' : '已选择'}${this.type == 'collection' ? '收藏条件' : '历史记录'}`
            let ids = type == 'all'
                ? []
                    : type == 'single'
                        ? [row.id]
                            : this.multipleSelection.map(el => el.id)

            this.$confirm(message, '提示', {
                type: 'warning',
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                beforeClose: async (action, instance, done) => {
                    if (action == 'confirm') {
                        instance.confirmButtonLoading = true
                        await this.delConditionCollect(ids)
                        instance.confirmButtonLoading = false
                        done()
                    } else done()
                }
            }).catch(() => {})
        },
        delConditionCollect(ids) {
            return new Promise((resolve, reject) => {
                let interfaces = this.type == 'collection'
                    ? delConditionCollect
                     : delSearchHistory
                let params = {
                    ids
                }
                interfaces(params).then(res => {
                    if (res.data.returnCode == 0) {
                        this.$message.success(`删除${this.type == 'collection' ? '收藏条件' : '历史记录'}成功`)
                        this.getList()
                    }
                    this.isDel = true
                    resolve(res.data)
                }).catch(err => {
                    reject(err)
                })
            })
        },
        sizeChange(val) {
            this.start = 1
            this.limit = val
            this.getList()
        },
        currentChange(val) {
            this.start = val
            this.getList()
        },
        t(val) {
            return i18n.zh[val]
        }
    }
}
</script>

<style lang="scss" scoped>
    .btachComent {
        ::-webkit-scrollbar {
            height: 1px;
            width: 11px;
        }
        ::-webkit-scrollbar-thumb {
            border-radius: 2px;
            box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
            background: #dcdee2;
        }
    }
</style>
