<template>
    <div class="wapper">
        <v-tour name="importTour" :steps="steps" :options="tourOptions"></v-tour>
        <div class="header_btn">
            <el-button type="primary" @click="handleCreate">批量创建</el-button>
            <el-button type="plain">取消</el-button>
        </div>
        <div class="uoload_wapper">
            <div class="file-upload-bg" id="uoloadWapper">
                <div style=" display: flex;align-items: center;justify-content: center; height:50px;margin-top:25px">
                    <i class="el-icon-upload"></i>
                </div>
                <div class="file-upload-desc">仅允许导入xls、xlsx格式文件，文件大小不超过10m</div>
                <div class="file-upload-btn">
                    <el-upload class="custom-el-upload" style="display:inline-block" ref="upload"
                        :on-change="handleFileChange" :file-list="fileList" :auto-upload="false" :on-remove="handleRemove"
                        action="#" accept=".xlsx, .xls">
                        <el-button type="primary">上传文件</el-button>
                    </el-upload>
                    <div @click="handleDownTemplate" class="xzIcon">
                        <i class="el-icon-download"></i>
                        <span>下载模板</span>
                    </div>
                </div>
                <div class="file-upload-progress">
                    <el-progress v-show="progressFlag" style="width:70%" :percentage="loadProgress"></el-progress>

                </div>
            </div>
        </div>
        <div class="tab_wapper">
            <div class="tab_top">
                <div>
                    <span class="yulan">预览</span>
                    <el-button type="primary" @click="handleExport">导出</el-button>
                </div>
                <div class="line"></div>
            </div>
            <el-table :data="tableData" style="width: 100%" v-loading="loading" border :key="isUpdate"
                @selection-change="handleSelection" ref="importTable">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column align="center" label="总行行政网格名称" prop="topGridName" show-overflow-tooltip></el-table-column>
                <el-table-column align="center" prop="gridName" label="网格名称" show-overflow-tooltip>
                </el-table-column>
                <el-table-column align="center" prop="gridDutyType" label="责任类型" show-overflow-tooltip>
                    <template slot-scope="scope">
                        <span v-if="scope.row.gridDutyType == '1'">责任网络</span>
                        <span v-if="scope.row.gridDutyType == '2'">竞争网络</span>
                    </template>
                </el-table-column>
                <el-table-column align="center" prop="adminDivisionList" label="关联行政区划"
                    show-overflow-tooltip></el-table-column>
                <el-table-column align="center" prop="userList" label="关联机构" show-overflow-tooltip></el-table-column>
                <el-table-column align="center" prop="result" label="创建结果" show-overflow-tooltip>
                    <template slot-scope="scope">
                        <div v-if="scope.row.result">
                            <el-tag type="success" v-if="scope.row.resultStatus">{{ scope.row.result }}</el-tag>
                            <el-tag type="danger" v-else>{{ scope.row.result }}</el-tag>
                        </div>
                        <div v-else class="resultLoading" v-loading="resultLoading"
                            element-loading-spinner="el-icon-loading"></div>
                    </template>
                </el-table-column>
            </el-table>
        </div>
    </div>
</template>
<script>
import { importSecData, fileSecTemplate, templateSecCreate, secResultExport } from '@/api/grid/list/gridlist.js'
import { downloadFiles } from '@/utils'
import { Message } from "element-ui";
export default {
    data() {
        return {
            steps: [
                {
                    target: '#uoloadWapper',
                    content: '<div style="font-size:20px;line-height:25px">批量导入创建</div><br><span>支持导入excel文件批量建立总行行政网格、进行分配</span>',
                    overlay: true,
                    params: {
                        placement: 'bottom',
                        highlight: true,
                        mask: true
                    }
                },
                {
                    target: '#uoloadWapper',
                    content: '<div style="font-size:20px;line-height:25px">批量导入创建</div><br><span>支持导入excel文件批量建立总行行政网格、进行分配</span>',
                    overlay: true,
                    params: {
                        placement: 'bottom',
                        highlight: true,
                        mask: true
                    }
                },
                {
                    target: '#uoloadWapper',
                    content: '',
                    overlay: true,
                    before: () => {
                        return this.$router.push({ path: '/grid/create/create' }).then(() => {
                            return new Promise(resolve => {
                                const checkElement = () => {
                                    sessionStorage.setItem('isTour', 2)
                                    if (document.querySelector('#uoloadWapper')) {
                                        resolve()
                                    } else {
                                        setTimeout(checkElement, 100)
                                    }
                                }
                                checkElement()
                            })
                        })
                    }
                },
            ],
            tourOptions: {
                highlight: true,
                labels: {
                    buttonSkip: '跳过',
                    buttonPrevious: '上一步',
                    buttonNext: '下一步',
                    buttonStop: '完成'
                },
                enabledButtons: {
                    buttonSkip: true,
                    buttonPrevious: true,
                    buttonNext: true,
                    buttonStop: true,
                },
                useKeyboardNavigation: true,
                startTime: 0,
                stopOnTargetNotFound: true,
                debug: false,
            },
            fileList: [],
            tableData: [],
            loading: false,
            progressFlag: false,
            loadProgress: 0,
            isUpdate: 0,
            selectData: [],
            resultLoading: false,
            firstGaridList: [],
        }
    },
    computed: {
        isTour() {
            return sessionStorage.getItem('isTour')
        },
    },
    mounted() {
        if (this.isTour == '1') {
            setTimeout(() => {
                this.startTour()
            }, 1000)
        }
    },
    methods: {
        startTour() {
            this.$tours['importTour'].start(1)
            const tour = this.$tours['importTour']
            tour.previousStep = function () {
                sessionStorage.setItem('isTour', '0')
                sessionStorage.setItem('isPrevious', 'first')
                this.$router.push({ path: '/grid/create/create' })
            }
        },
        handleDownTemplate() {
            let resultName = `批量导入支行行政网格模板${new Date().getTime()}.xlsx`
            fileSecTemplate().then(res => {
                downloadFiles(res, resultName)
            })
        },
        handleSubmit() {
            const formData = new FormData()
            formData.append('file', this.$refs.upload.uploadFiles[0]?.raw)
            importSecData(formData).then(res => {
                if (res.code == 200) {
                    this.tableData = res.data

                }
            })

        },
        handleFileChange(file, fileList) {

            if (fileList.length > 0) {
                this.fileList = [fileList[fileList.length - 1]]
            }
            if (file.status === 'ready') {
                this.progressFlag = true;
                this.loadProgress = 0;
                const interval = setInterval(() => {
                    if (this.loadProgress >= 100) {
                        clearInterval(interval)
                        return;
                    }
                    this.loadProgress += 1;
                    if (this.loadProgress == 100) {
                        this.handleSubmit()
                    }
                }, 20)
            }
            if (file.status == 'success') {
                this.progressFlag = false;
                this.loadProgress = 100;
            }

        },
        handleRemove() {
            this.tableData = []
            this.loadProgress = 0;
            this.progressFlag = false
        },
        async handleCreate() {
            this.resultLoading = true
            for (let i = 0; i < this.tableData.length; i++) {
                try {
                    let obj = await this.getTemplateCreate(this.tableData[i])
                    if (obj.resultStatus) {
                        this.tableData[i].result = obj.msg
                        this.tableData[i].resultStatus = obj.resultStatus
                        this.isUpdate += 1
                    } else {
                        this.tableData[i].result = obj.msg
                        this.tableData[i].resultStatus = obj.resultStatus
                        this.isUpdate += 1
                    }

                } catch (error) {
                    console.error('失败')
                }
            }
        },
        getTemplateCreate(item) {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    resolve(templateSecCreate(item))
                }, 1000)
            })
        },
        handleSelection(val) {
            this.selectData = val
            console.log(this.selectData, ' this.selectData')
        },
        handleExport() {
            if (this.selectData.length == 0) {
                Message.warning("请先选择导出数据");
            } else {
                secResultExport(this.selectData).then(res => {
                    downloadFiles(res, `${new Date().getTime()}.xlsx`)
                    this.$refs.importTable.clearSelection();
                })
            }

        }
    },

};
</script>

<style lang="scss" scoped>
.wapper {
    padding: 30px;
    background-color: #fff;
}

.header_btn {
    text-align: right;
}



.file-upload-download {
    cursor: pointer;
}

.line {
    width: 100%;
    height: 1px;
    background-color: #ccc;
    margin: 10px 0;
}

.yulan {
    margin-right: 20px;
}

.uoload_wapper {
    display: flex;
    justify-content: center;
}

.file-upload-bg {
    width: 702px;
    background: #F7F8FA;
}

.el-icon-upload {
    text-align: center;
    font-size: 47.36px;
    color: #CCCCCC;
}

.file-upload-desc {
    font-weight: 400;
    font-size: 14px;
    color: #666666;
    letter-spacing: 0;
    text-align: center;
    line-height: 12px;
    margin-top: 8px;
}

.file-upload-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20px;
}

.file-upload-download {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 15px;
    font-size: 14px;
}

.file-upload-progress {
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 20px 0;
    font-size: 14px;
}

.custom-el-upload {
    margin-right: 20px;
}

.resultLoading {
    width: 100%;
    height: 40px;

    ::v-deep .el-loading-spinner {
        height: 40px;
        line-height: 40px;
    }
}

.xzIcon {
    color: #4886f8;
    cursor: pointer;
}

::v-deep .v-step::after {
    content: '';
    position: absolute;
    width: 100px;
    height: 100px;
    background-image: url('../../../../assets/images/arrow.gif');
    background-repeat: no-repeat;
    background-size: contain;
    top: 0;
    left: 50%;
    z-index: 9999999;
}

::v-deep .v-step[data-popper-placement^="bottom"]::after {
    top: -165%;
    left: 37%;
}
</style>

<style>@import '../../tour.css';</style>
