<template>
    <a-dialog class="export-config" title="导出配置" :visible="visible" @close="$emit('close:modal')" width="65%">
        <a-form ref="form" :model="form" :rules="rules" label-width="115px">
            <a-row :gutter="7">
                <a-col :span="8">
                    <a-form-item label="文件名称" prop="fileName">
                        <a-input v-model="form.fileName" placeholder="文件名称"></a-input>
                    </a-form-item>
                </a-col>
                <a-col :span="8">
                    <a-form-item label="表名称" prop="sheetName">
                        <a-input v-model="form.sheetName" placeholder="表名称"></a-input>
                    </a-form-item>
                </a-col>
                <a-col :span="8">
                    <a-form-item label="标题" prop="title">
                        <a-input v-model="form.title" placeholder="标题"></a-input>
                    </a-form-item>
                </a-col>
                <a-col :span="8">
                    <a-form-item label="是否冻结表头" prop="freezeHead">
                        <a-radio v-model="form.freezeHead" label="Y">是</a-radio>
                        <a-radio v-model="form.freezeHead" label="N">否</a-radio>
                    </a-form-item>
                </a-col>
                <a-col :span="8">
                    <a-form-item label="是否冻结首行" prop="freezeFirstRow">
                        <a-radio v-model="form.freezeFirstRow" label="Y">是</a-radio>
                        <a-radio v-model="form.freezeFirstRow" label="N">否</a-radio>
                    </a-form-item>
                </a-col>
                <a-col :span="8">
                    <a-form-item label="是否添加索引列" prop="addIndex">
                        <a-radio v-model="form.addIndex" label="Y">是</a-radio>
                        <a-radio v-model="form.addIndex" label="N">否</a-radio>
                    </a-form-item>
                </a-col>
                <a-col :span="8">
                    <a-form-item label="是否自动调整列宽" prop="autoColWidth">
                        <a-radio v-model="form.autoColWidth" label="Y">是</a-radio>
                        <a-radio v-model="form.autoColWidth" label="N">否</a-radio>
                    </a-form-item>
                </a-col>
            </a-row>
        </a-form>
        <a-table ref="table" height="500px" border @selection-change="selection" :data="form.columnList"
            max-height='60vh' :header-cell-style="{ 'background': '#f5f7fa' }" @cell-click="handleCellClick"
            row-class-name="col-title">
            <a-table-column align="center" type="selection" width='55'></a-table-column>
            <!-- <a-table-column label='操作' width="80">
        <template slot-scope="scope">
          <a-button
            type="text"
            icon="a-icon-edit"
            size="mini"
            @click="handleEdit(scope, scope.row)">修改</a-button>
        </template>
</a-table-column> -->

            <a-table-column label='列名' align="center" prop='title' :show-overflow-tooltip='true'>
                <template slot-scope="scope">
                    <div v-if="scope.row.titleEditable"> <a-input v-model="scope.row.title" placeholder="列名"></a-input>
                    </div>
                    <div v-else> {{ scope.row.title }} </div>
                </template>
            </a-table-column>
            <a-table-column label='变量名' align="center" prop='field' :show-overflow-tooltip='true'>
                <template slot-scope="scope">
                    <div v-if="scope.row.fieldEditable"> <a-input v-model="scope.row.field" placeholder="变量名"></a-input>
                    </div>
                    <div v-else> {{ scope.row.field }} </div>
                </template>
            </a-table-column>
            <a-table-column label='对齐方式' align="center" prop='alignZh' :show-overflow-tooltip='true'>
                <template slot-scope="scope">

                    <div v-if="scope.row.alignEditable">
                        <a-select v-model="scope.row.align">
                            <a-select-option v-for="item in alignOptions" :key="item.value" :title="item.label"
                                :value="item.value"></a-select-option>
                        </a-select>
                    </div>
                    <div v-else> {{ scope.row.alignZh }} </div>

                </template>
            </a-table-column>
            <a-table-column label='宽度' align="center" prop='width' :show-overflow-tooltip='true'>
                <template slot-scope="scope">
                    <div v-if="scope.row.widthEditable"><a-input-number size="small" :controls="false"
                            v-model="scope.row.width"></a-input-number> </div>
                    <div v-else> {{ scope.row.width }} </div>

                </template>
            </a-table-column>
            <a-table-column label='格式化' align="center" prop='formatZh' :show-overflow-tooltip='true'>
                <template slot-scope="scope">

                    <div v-if="scope.row.formatEditable">
                        <a-select v-model="scope.row.format" clearable>
                            <a-select-option v-for="item in formatOptions" :key="item.value" :title="item.label"
                                :value="item.value"></a-select-option>
                        </a-select>
                    </div>
                    <div v-else> {{ scope.row.formatZh }} </div>
                </template>
            </a-table-column>
        </a-table>
        <template #footer>
            <a-button size="small" icon="a-icon-close" @click="$emit('close:modal')">关闭</a-button>
            <a-button type="primary" size="small" icon="a-icon-check" @click="saveConfig">确定</a-button>
        </template>

        <export-column-config :column="column" v-if="exportConfigColumnVisible"
            :exportConfigColumnVisible="exportConfigColumnVisible" @close:modal='exportConfigColumnVisible = false'
            @save="saveColumn"></export-column-config>
    </a-dialog>
</template>

<script>
import { message as Message } from 'ant-design-vue'
import { executeExport } from '@/api/common'
import { downloadFile } from '@/utils/util';
import { Base64 } from 'js-base64'
export default {
    props: {
        exportConfigVisible: Boolean,
        exportRquestConfig: Object,
        exportExcelMeta: Object
    },
    data () {
        return {
            visible: this.exportConfigVisible,
            form: {
                addIndex: 'N',
                autoColWidth: 'N',
                columnList: [],
                fileName: "",
                freezeHead: 'N',
                sheetName: "",
                title: "",
                freezeFirstRow: 'N',
            },
            rules: {

            },
            column: {},
            exportConfigColumnVisible: false,
            isSelected: true,
            formatOptions: [
                {
                    label: '整数',
                    value: '#,###'
                },
                {
                    label: '保留两位',
                    value: '#,###.00'
                },
                {
                    label: '保留4位',
                    value: '#,###.0000'
                },
                {
                    label: '保留4位',
                    value: '#,###.000000'
                }
            ],
            alignOptions: [
                {
                    label: '居左',
                    value: 'left'
                },
                {
                    label: '居中',
                    value: 'center'
                },
                {
                    label: '居右',
                    value: 'right'
                }
            ],
            checkList: [],
        }
    },
    mounted () {
        let dialog = document.querySelector('.export-config')
        //给dialog绑定一个事件，此事件触发时如果点击的元素在table内则不触发，否则触发
        dialog.addEventListener('click', (e) => {
            let target = e.target
            let table = document.querySelector(".export-config .a-table")

            if (!table.contains(target)) {
                this.resetEditable()
            }

        })
    },
    methods: {
        saveConfig () {
            const { columnList, freezeHead, freezeFirstRow, addIndex, autoColWidth, fileName } = this.form
            if (this.checkList.length == 0) {
                this.$message({
                    message: "请至少选择一列进行导出！",
                    type: "error"
                })
                return
            }
            let message = Message({
                message: '&nbsp;&nbsp;正在保存...',
                iconClass: 'a-icon-loading',
                showClose: "true",
                dangerouslyUseHTMLString: 'true'
            })
            let { headers, url, ...others } = this.exportRquestConfig

            //处理数据
            let temp = JSON.parse(JSON.stringify(this.form))
            temp.freezeHead = freezeHead === 'Y' ? true : false
            temp.freezeFirstRow = freezeFirstRow === 'Y' ? true : false
            temp.addIndex = addIndex === 'Y' ? true : false
            temp.autoColWidth = autoColWidth === 'Y' ? true : false

            let orderList = this.checkList.map(item => item.order)
            temp.columnList = []
            columnList.forEach(item => {
                if (orderList.includes(item.order)) {
                    temp.columnList.push(item)
                }
            })

            temp.columnList.sort((a, b) => {
                return a.order - b.order
            })


            headers = {
                export: true,
                exportConfig: Base64.encode(JSON.stringify(temp)),
                ...headers,
            }


            executeExport(url, headers, others).then(resp => {
                if (resp.type == 'application/json') {
                    //将Blob对象转换成字符串
                    let message = ''
                    resp.text().then(data => {
                        message = JSON.parse(data).errMessage
                        Message({
                            message: "导出失败！" + message,
                            type: "error"
                        })
                    })
                } else {
                    //开始下载
                    downloadFile(resp, fileName + ".xlsx")
                }
                message.close()
                this.$emit("close:modal")
            })


        },
        selection (selection) {
            this.checkList = JSON.parse(JSON.stringify(selection))
        },
        handleEdit (scope) {
            let { row } = scope
            this.column = row
            this.exportConfigColumnVisible = true
            this.isSelected = scope.isSelected
        },
        init () {
            const { freezeFirstRow, freezeHead, addIndex, autoColWidth } = this.form
            if (!freezeFirstRow) {
                this.form.freezeFirstRow = 'N'
            } else {
                this.form.freezeFirstRow = 'Y'
            }
            if (!freezeHead) {
                this.form.freezeHead = 'N'
            } else {
                this.form.freezeHead = 'Y'
            }
            if (!addIndex) {
                this.form.addIndex = 'N'
            } else {
                this.form.addIndex = 'Y'
            }
            if (!autoColWidth) {
                this.form.autoColWidth = 'N'
            } else {
                this.form.autoColWidth = 'Y'
            }


            this.form.columnList.forEach((item, index) => {
                item.order = index
            })
            this.resetEditable()

            this.$nextTick(() => {
                this.$refs.table.toggleAllSelection()
            })
        },
        saveColumn (data) {
            let { columnList } = this.form
            for (let index = 0; index < columnList.length; index++) {
                const element = columnList[index];
                if (element.order == data.order) {
                    this.$set(this.form.columnList, index, data)
                }
            }
            this.$refs.table.toggleRowSelection(data, this.isSelected)
        },
        handleInput (val, scope) {
        },
        handleCellClick (row, column, cell, event) {

            this.resetEditable()

            let property = column.property + 'Editable'
            if (column.property == 'alignZh') {
                property = 'alignEditable'
            }
            if (column.property == 'formatZh') {
                property = 'formatEditable'
            }

            this.$set(row, property, true)
        },
        resetEditable () {
            this.form.columnList.forEach((item) => {
                this.$set(item, 'titleEditable', false)
                this.$set(item, 'fieldEditable', false)
                this.$set(item, 'alignEditable', false)
                this.$set(item, 'widthEditable', false)
                this.$set(item, 'formatEditable', false)
            })
        }
    },
    watch: {
        exportExcelMeta: {
            immediate: true,
            handler (val) {
                this.form = JSON.parse(JSON.stringify(val))
                this.init()
            }
        },
        "form.columnList": {
            immediate: true,
            handler (val) {
                for (let i = 0; i < val.length; i++) {
                    const item = val[i];
                    this.alignOptions.forEach(item1 => {
                        if (item.align == item1.value) {
                            item.alignZh = item1.label
                        }
                    })
                    this.formatOptions.forEach(item1 => {
                        if (item.format == item1.value) {
                            item.formatZh = item1.label
                        }
                    })
                }
            }
        },
    }
}
</script>

<style lang="scss">
.export-config {
    .col-title {
        height: 64px;
    }

}
</style>
