<template>
    <div class="page-container">
        <div class="flex-wrap search-box">
            <div class="search-item">
                <a-select class="label-option" v-model="searchKey">
                    <a-select-option v-for="(item, index) in searchField" :key="index" :value="item.value">
                        {{ item.label }}
                    </a-select-option>
                </a-select>
            </div>
            <div class="search-item">
                <a-select class="condition-option" v-model="searchOption">
                    <a-select-option
                        v-for="item in conditionOption"
                        :key="item.value"
                        :value="item.value"
                    >
                        {{ item.label }}
                    </a-select-option>
                </a-select>
            </div>
            <div class="search-item">
                <a-input-search
                    v-model="searchValue"
                    class="search-value"
                    placeholder="请输入"
                    :max-length="100"
                    @search="search"
                />
            </div>
            <div class="search-item">
                <a-button @click="refresh">
                    <a-icon type="reload"/>
                </a-button>
            </div>
            <div class="search-item" v-for="(item, index) in barMenu" :key="index" v-if="item.display === 'v'">
                <a-button type="primary" @click="buttonClick(item.id)">
                    {{ item.name }}
                </a-button>
            </div>
        </div>
        <a-row>
            <a-col>
                <a-table
                    :rowKey="(record,index) => {return index}"
                    :columns="columns"
                    :dataSource="dataSource"
                    :scroll="{ x: 800, y: 500 }"
                    :loading="loading"
                    :pagination="pagination"
                    @change="tableChange">
                    <template slot="operation" slot-scope="index, record">
                        <a-space>
                            <span v-for="(item, index) in operation" :key="index">
                                <a-popconfirm
                                    v-if="item.id === 'sys_delete'"
                                    title="确定删除该信息吗"
                                    ok-text="确定"
                                    cancel-text="取消"
                                    @confirm="() => operationClick(item.id, record)"
                                >
                                    <a class="danger" @click.stop="">
                                        删除
                                    </a>
                                </a-popconfirm>
                                <a v-else @click="operationClick(item.id, record)">{{ item.name }}</a>
                            </span>
                        </a-space>
                    </template>
                </a-table>
            </a-col>
        </a-row>
        <a-modal title="导入数据"
                 :visible="showImport"
                 centered
                 @ok="importFile"
                 @cancel="showImport=false">
            <a-form-model>
                <a-form-model-item label="文件">
                    <a-upload :accept="acceptExcel"
                              :fileList="fileList"
                              :remove="removeFile"
                              :customRequest="upload">
                        <a-button><a-icon type="upload" />点击上传</a-button>
                    </a-upload>
                </a-form-model-item>
            </a-form-model>
        </a-modal>
    </div>
</template>

<script>
import pager from "../../../config/pagination.conf";
import bus from "../../../utils/bus"
import config from "../../../config/config"

export default {
    name: "list",
    data() {
        return {
            templateId: "",
            searchField: [],
            conditionOption: [
                {label: "包含", value: "like"},
                {label: "等于", value: "="},
                {label: "不等于", value: "!="},
                {label: "小于", value: "<"},
                {label: "小于等于", value: "<="},
                {label: "大于", value: ">"},
                {label: "大于等于", value: ">="},
            ],
            searchKey: "",
            searchOption: "like",
            searchValue: "",
            setting: null,
            barMenu: [],
            operation: [],
            table: null,
            loading: false,
            columns: [
                {
                    title: '编号',
                    dataIndex: 'uid',
                    key: 'uid',
                    width: 200,
                    align: 'left'
                }
            ],
            dataSource: [],
            pagination: {
                ...pager
            },
            showImport: false,
            file: "",
            acceptExcel: ".xlsx,.xls,.csv",
            fileList: []
        }
    },
    created() {
        let query = this.$route.query;
        this.templateId = query.template_id;
        if (!this.templateId) {
            this.$message.error("视图模板不存在，请到菜单管理关联视图模板");
        }
        this.getTemplateInfo();
    },
    mounted() {
        bus.$on('refresh', data => {
            if (data === this.table.uid) {
                this.refresh();
            }
        })
    },
    methods: {
        changeTabTitle(title){
            title = title.replace('表', '')
            title += '列表'
            this.$store.commit('changeTabTitle', title)
        },
        getTemplateInfo() {
            let param = {template_id: this.templateId}
            this.api.post('template_info', param).then(result => {
                this.barMenu = result.result.barMenu
                this.operation = result.result.operation
                this.setting = result.result.setting
                this.table = result.result.table
                this.changeTabTitle(this.table.name)
                this.getColumn(result.result.fieldsArr);
                this.getList();
            })
        },
        getColumn(fieldsArr) {
            fieldsArr.forEach(v => {
                if (v.display === 'v') {
                    this.columns.push({
                        title: v.name,
                        dataIndex: v.alias,
                        key: v.alias,
                        width: parseInt(v.width),
                        align: v.align
                    })
                    this.searchField.push({
                        label: v.name,
                        value: v.alias
                    })
                }
            })
            if (this.columns.length > 0) {
                this.searchKey = this.columns[0].key
            }
            if (this.operation.length > 0) {
                this.columns.push({
                    title: "操作",
                    dataIndex: "operation",
                    key: "operation",
                    scopedSlots: {customRender: "operation"},
                    fixed: 'right',
                    width: 150,
                })
            }
        },
        getList() {
            let param = {
                template_id: this.templateId,
                page_index: this.pagination.current,
                page_size: this.pagination.pageSize
            }
            if (this.searchValue) {
                param.where_and = JSON.stringify([
                    [this.searchKey, this.searchOption, this.searchValue]
                ])
            }
            this.loading = true;
            this.api.post('data_list', param).then(result => {
                this.loading = false;
                let pager = result.result;
                this.dataSource = pager.data
                this.pagination.current = pager.page_index
                this.pagination.total = pager.total_records
            }).catch(e => {
                this.loading = false;
            })
        },
        search() {
            this.pagination.current = 1;
            this.getList();
        },
        refresh() {
            this.pagination.current = 1;
            this.searchValue = "";
            this.getList();
        },
        tableChange(pagination, filters, sorter, {currentDataSource}) {
            this.pagination.current = pagination.current;
            this.pagination.pageSize = pagination.pageSize;
            this.getList();
        },
        buttonClick(id) {
            if (id === 'sys_add') {
                this.create();
            } else if (id === 'sys_import') {
                this.showImportFile();
            } else if (id === 'sys_export') {
                this.export();
            } else {
                this.$message.error('不支持的操作');
            }
        },
        create() {
            this.$router.push({
                path: '/data/create?template_id=' + this.setting.add_tpl
            })
        },
        operationClick(id, record) {
            if (id === 'sys_view') {
                this.$router.push({
                    path: '/data/detail/' + record.uid + '/?template_id=' + this.setting.view_tpl
                });
            } else if (id === 'sys_edit') {
                this.$router.push({
                    path: '/data/update/' + record.uid + '/?template_id=' + this.setting.edit_tpl
                });
            } else if (id === 'sys_delete') {
                this.handleDelete(record)
            } else {
                this.$message.error('不支持的操作')
            }
        },
        handleDelete(record) {
            let param = {
                uid: record.uid,
                template_id: this.templateId
            }
            this.api.post('data_delete', param).then(result => {
                this.$message.success('删除成功')
                this.getList()
            })
        },
        showImportFile() {
            this.showImport = true
        },
        upload(item){
            this.file = item.file
            this.fileList = [item.file]
        },
        removeFile(file){
            this.file = ""
            this.fileList = []
        },
        importFile(){
            if (!this.file) {
                this.$message.error('请选择文件')
                return
            }
            let fd = new FormData();
            fd.append("file", this.file) //传文件
            fd.append("template_id", this.templateId)
            this.api.upload('data_import', fd).then(result => {
                this.showImport = false
                this.$message.success('导入成功')
                this.refresh();
            })
        },
        export() {
            let param = {
                template_id: this.templateId,
                page_index: this.pagination.current,
                page_size: this.pagination.pageSize
            }
            if (this.searchValue) {
                param.where_and = JSON.stringify([
                    [this.searchKey, this.searchOption, this.searchValue]
                ])
            }
            this.api.post('data_export', param).then(result => {
                let href = config.file_url + result.result
                let download = document.createElement('a')
                download.href = href
                document.body.appendChild(download)
                download.click()
                document.body.removeChild(download)
            })
        },
        handleChange(info) {
            let fileList = [...info.fileList];
            fileList = fileList.slice(-1);
            this.fileList = fileList;
            console.log(this.fileList, 'file');
        },
    }
}
</script>

<style scoped>

</style>
