<template>
    <el-dialog title="台账信息导入" :visible.sync="dialogFormVisible" class="dialogFormVisible" @close="handleCloseDialog">
        <div v-show="active == 1">
            <h5 class="title">
                1、只可导入维护数据类型为“单个-数值量（Num）、单个-字符量（Str）、单个-布尔量（Bool）、单个-单选枚举量（Eunm）、单个-日期时间量（DTime）”的静态信息点的值。
            </h5>
            <h5 class="title">2、“单个-布尔量（Bool）、单个-单选枚举量（Eunm）”的值需填写选项的编码、“单个-日期时间量（DTime）”的值需填写YYYYMMDD。</h5>
            <h5 class="title">3、第一列为识别设备实例的唯一标识；第二列为实例的设备类型。其他列为信息点，可任意增加信息点列。</h5>
            <h5 class="title">4、设备唯一标识三选一：设备本地编码EquipLocalID、数字化交付编码DigitaIDeliveryID、设备类型ClassCode。</h5>
            <h5 class="title">5、行为对象实例对应该信息点的值。值为空时不做处理，不会清空台账中已维护的值。</h5>
            <el-upload
                class="upload-demo"
                drag
                :action="`${baseUrl}${dataCenter}/object/equip/import/`"
                accept=".xlsx"
                :show-file-list="false"
                :headers="headers"
                name="file"
                multiple
                :on-progress="progress"
                :on-success="success"
                :on-error="error"
            >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将Excel文件拖到此处，或<em>点击上传Excel文件</em></div>
                <div class="el-upload__tip tips" slot="tip">
                    上传的Excel数据将完全覆盖当前设备信息点（原有数据不会保留）
                    <el-button style="float: right;" type="primary" @click="downloadEquipTemplate()">下载模板</el-button>
                    <el-button style="float: right; margin-right: 10px;" v-if="historyKey" type="primary" @click="download(historyKey)">下载上一次导入结果</el-button>
                </div>
            </el-upload>
        </div>
        <div v-show="active == 2">
            <div class="block">
                <el-timeline>
                    <el-timeline-item
                        v-for="(activity, index) in activities"
                        :key="index"
                        :icon="activity.icon"
                        :type="activity.type"
                        :color="activity.color"
                        :size="activity.size"
                    >
                        {{ activity.content }}
                    </el-timeline-item>
                </el-timeline>
            </div>
            <el-button :disabled="!messageKey" @click="download(messageKey)">下载导入结果</el-button>
            <footer slot="footer" style="text-align: right" class="dialog-footer">
                <el-button @click="active = 1">返回</el-button>
                <el-button type="primary" @click="dialogFormVisible = false">确认</el-button>
            </footer>
        </div>
    </el-dialog>
</template>

<script>
import storage from "@/framework/utils/storage";
import { baseUrl, dataCenter } from "@/api/scan/config.js";
import { queryDownloadsKey, equipTemplate } from "@/api/scan/request";
import { mapGetters } from "vuex";

export default {
    data() {
        return {
            active: 1,
            dialogFormVisible: false,
            messageKey: "",
            historyKey: "",
            activities: [],
            baseUrl: baseUrl,
            dataCenter: dataCenter,
        };
    },
    computed: {
        ...mapGetters("layout", ["projectId"]),
        headers() {
            return {
                ProjectId: this.projectId,
                Comming: "adm",
                Account: storage.get("user_name"),
            };
        },
    },
    methods: {
        openDialog() {
            this.dialogFormVisible = true;
        },
        /**
         * 获取导入历史key
         */
        getHistoryKey() {
            const params = {
                filters: "type = 'static'",
                orders: "createTime desc",
                pageSize: 1,
            };
            queryDownloadsKey(params, (res) => {
                queryDownloadsKey(params, (res) => {
                    if (res.result === "success" && res.content && res.content.length && res.content[0].key) {
                        this.historyKey = res.content[0].key;
                    } else {
                        this.historyKey = "";
                    }
                });
            });
        },
        progress(event, file, fileList) {
            this.active = 2;
            this.activities = [
                {
                    content: "数据文件处理中..",
                    size: "large",
                    type: "primary",
                    icon: "el-icon-check",
                    color: "#0bbd87",
                },
            ];
        },
        success(event, file, fileList) {
            if (event.result == "success") {
                this.messageKey = event.message;
                if (event.content && event.content[0] && event.content[0].state === "0") {
                    // 全部导入成功
                    this.activities = [
                        {
                            content: "数据文件处理中..",
                            size: "large",
                            type: "primary",
                            icon: "el-icon-check",
                            color: "#0bbd87",
                        },
                        {
                            content: `全部导入成功（导入信息点：${event.content[0].successCount} 条）`,
                            color: "#0bbd87",
                            icon: "el-icon-check",
                            size: "large",
                            type: "success",
                        },
                    ];
                    // 导入成功刷新台账数据
                    this.$emit("upDataDevice");
                } else if (event.content && event.content[0] && event.content[0].state === "1") {
                    // 部分导入成功
                    this.activities = [
                        {
                            content: "数据文件处理中..",
                            size: "large",
                            type: "primary",
                            icon: "el-icon-check",
                            color: "#0bbd87",
                        },
                        {
                            content: `部分导入成功（导入成功：${event.content[0].successCount} 条；导入失败：${event.content[0].failCount} 条）`,
                            color: "#0bbd87",
                            icon: "el-icon-check",
                            size: "large",
                            type: "success",
                        },
                    ];
                    // 导入成功刷新台账数据
                    this.$emit("upDataDevice");
                } else {
                    // 导入失败
                    this.activities = [
                        {
                            content: "数据文件处理中..",
                            size: "large",
                            type: "primary",
                            icon: "el-icon-check",
                            color: "#0bbd87",
                        },
                        {
                            content: "导入失败！",
                            color: "#f56c6c",
                            icon: "el-icon-close",
                            size: "large",
                            type: "primary",
                        },
                    ];
                }
            } else {
                this.messageKey = "";
                if (event.result === "failure" && event.message) {
                    this.activities = [
                        {
                            content: "数据文件处理中..",
                            size: "large",
                            type: "primary",
                            icon: "el-icon-check",
                            color: "#0bbd87",
                        },
                        {
                            content: `导入失败！（${event.message}）`,
                            color: "#f56c6c",
                            icon: "el-icon-close",
                            size: "large",
                            type: "primary",
                        },
                    ];
                } else {
                    this.activities = [
                        {
                            content: "数据文件处理中..",
                            size: "large",
                            type: "primary",
                            icon: "el-icon-check",
                            color: "#0bbd87",
                        },
                        {
                            content: "导入失败！",
                            color: "#f56c6c",
                            icon: "el-icon-close",
                            size: "large",
                            type: "primary",
                        },
                    ];
                }
            }
        },
        error(event, file, fileList) {},
        download(key) {
            const url = `${baseUrl}${dataCenter}/graphic/downloads/point?key=` + key;
            let a = document.createElement("a");
            a.href = url;
            a.download = `${key}.xlsx`;
            a.click();
        },
        /**
         * 台账信息导入模板
         */
        downloadEquipTemplate() {
            equipTemplate(
                {},
                (res) => {
                    console.log("下载台账信息导入模板");
                },
                "台账信息导入模板.xlsx"
            );
        },
        handleCloseDialog() {
            this.messageKey = "";
            this.historyKey = "";
            this.active = 1;
            this.activities = [];
        },
    },
    watch: {
        dialogFormVisible(n, o) {
            // 打开弹窗获取历史导入key值
            if (n) this.getHistoryKey();
        },
    },
};
</script>

<style scoped lang="less">
.dialogFormVisible {
    .time {
        margin: 10px 0;
        font-size: 15px;

        .text {
            margin-right: 10px;
            font-size: 14px;
        }
    }

    .tips {
        color: red;
        font-size: 14px;
        font-weight: bold;
    }

    /deep/ .el-upload {
        width: 100%;
    }

    /deep/ .el-upload-dragger {
        margin: 0 auto;
        width: 100%;
    }
}
</style>
