<template>
    <div id="handsonStep1">
        <div class="btns-view">
            <el-button style="float:right;margin-top:4px;margin-left:10px;" type="primary" @click="saveData">保存</el-button>
            <el-button style="float:right;margin-top:4px;" type="primary" @click="addRow">新增行</el-button>
            <el-button style="float:right;margin-top:4px;" type="primary" @click="downData">下载数据</el-button>
            <el-button style="float:right;margin-top:4px;" type="primary" @click="updateExcel = true">导入Excel</el-button>
            <el-button style="float:right;margin-top:4px;" type="primary" @click="downloadExcel = true">导出Excel模板</el-button>
            <el-checkbox style="float:right;line-height:40px;" v-model="checked">只显示使用的原始点位</el-checkbox>
            <el-button type="primary">获取原始点位当前值</el-button>
        </div>
        <div id="handsontableSteps1" v-loading="isLoading">
            <handsontable-component v-if="!!allData.length" ref="handsontable" @mouseDown="clickTable" @change="changeHand"></handsontable-component>
            <div v-else class="center">暂无数据</div>
        </div>
        <own-dialog :width="'580px'" :index="true" title="位置标签" :dialogVisible="localtionDialog" @cancel="close">
            <localtion-falg :renderData="renderData"></localtion-falg>
        </own-dialog>
        <own-dialog :width="'580px'" :index="true" title="导出excel模板" :dialogVisible="downloadExcel" @cancel="close">
            <div class="center">
                <el-button type="text" @click="download">下载模板</el-button>
            </div>
        </own-dialog>
        <own-dialog :width="'580px'" :index="true" title="导出excel模板" :dialogVisible="updateExcel" @cancel="close">
        </own-dialog>
        <div class="center">
            <pagination :page="pages" @change="changePage"></pagination>
        </div>
    </div>
</template>
<script>
    import handsontableComponent from "@/components/common/handsontable"
    import getHeaderSetting from "@/utils/point_edit/handson_header"
    import ownDialog from "@/components/el_pack/dialog"
    import localtionFalg from "@/components/config_point/location_flag"
    import pagination from "@/components/common/myPagination"
    import {
        mapGetters,
        mapActions
    } from "vuex";
    import {
        changeHeader,
        showTypes
    } from "@/utils/handsontable/delType"
    import {
        queryPoint,
        updatePoint,
        createPoint,
        downloadTemplete
    } from "@/fetch/point_http"
    import axios from 'axios'
    export default {
        data() {
            return {
                checked: false,
                settings: {},
                hot: null,
                changeFlag: true, //是否发生修改
                localtionDialog: false,
                renderData: {},
                allData: [],
                pages: {
                    size: 10,
                    sizes: [10, 30, 50, 100],
                    total: 0,
                    currentPage: 0
                },
                oldPage: {
                    currentPage: 0,
                    size: 10
                },
                downloadExcel: false,
                isLoading: false,
                updateExcel: false,
            }
        },
        computed: {
            ...mapGetters("project", [
                "projectId",
                "datasourceId",
                "protocolType"
            ])
        },
        created() {},
        mounted() {
            if (!this.protocolType) {
                this.$router.push({
                    path: "/configPoint"
                })
            } else {
                this.getData()
            }
        },
        methods: {
            //关闭弹窗
            close() {
                this.localtionDialog = false
                this.downloadExcel = false
                this.updateExcel = false
            },
            downData() {
                axios({
                    method: 'post',
                    url: `/pointconfig/point/${this.protocolType}/pointlist-export`,
                    data: {DataSourceId: this.datasourceId},
                    responseType: 'blob',
                    headers:{ProjectId: this.projectId}
                }).then(function(res) {
                    var blob = new Blob([res.data], {
                        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
                    });
                    var fileName = res.headers['content-disposition'];
                    if (fileName)
                        fileName = fileName.substring(fileName.indexOf('=') + 1);
                    if ('download' in document.createElement('a')) { // 非IE下载
                        const elink = document.createElement('a')
                        elink.download = fileName
                        elink.style.display = 'none'
                        elink.href = URL.createObjectURL(blob)
                        document.body.appendChild(elink)
                        elink.click()
                        URL.revokeObjectURL(elink.href) // 释放URL 对象
                        document.body.removeChild(elink)
                    } else { // IE10+下载
                        navigator.msSaveBlob(blob, fileName)
                    }
                }).catch(function(err) {
                    console.dirxml(err);
                })
            },
            //下载excel模板
            download() {
                axios({
                    method: 'post',
                    url: `/pointconfig/point/${this.protocolType}/template-export`,
                    data: {},
                    responseType: 'blob'
                }).then(function(res) {
                    var blob = new Blob([res.data], {
                        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
                    });
                    var fileName = res.headers['content-disposition'];
                    if (fileName)
                        fileName = fileName.substring(fileName.indexOf('=') + 1);
                    if ('download' in document.createElement('a')) { // 非IE下载
                        const elink = document.createElement('a')
                        elink.download = fileName
                        elink.style.display = 'none'
                        elink.href = URL.createObjectURL(blob)
                        document.body.appendChild(elink)
                        elink.click()
                        URL.revokeObjectURL(elink.href) // 释放URL 对象
                        document.body.removeChild(elink)
                    } else { // IE10+下载
                        navigator.msSaveBlob(blob, fileName)
                    }
                }).catch(function(err) {
                    console.dirxml(err);
                })
                // downloadTemplete({
                //     data: {
                //         DataSourceId: this.datasourceId,
                //     },
                //     type: this.protocolType
                // },{
                //     responseType: 'blob'
                // },res => {
                //     var blob = new Blob([res.data], {
                //         type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
                //     });
                //     var fileName = res.headers['content-disposition'];
                //     if (fileName)
                //         fileName = fileName.substring(fileName.indexOf('=') + 1);
                //     if ('download' in document.createElement('a')) { // 非IE下载
                //         const elink = document.createElement('a')
                //         elink.download = fileName
                //         elink.style.display = 'none'
                //         elink.href = URL.createObjectURL(blob)
                //         document.body.appendChild(elink)
                //         elink.click()
                //         URL.revokeObjectURL(elink.href) // 释放URL 对象
                //         document.body.removeChild(elink)
                //     } else { // IE10+下载
                //         navigator.msSaveBlob(blob, fileName)
                //     }
                // })
            },
            //点击表格
            clickTable(info, row) {
                let activeCell = this.hot.getActiveEditor()
                this.renderData = info
                console.log(activeCell,'activeCell')
                if (activeCell.prop == "LocationFlag") {
                    this.localtionDialog = true
                }
            },
            addRow() {
                if (!!this.allData.length) {
                    let data = this.hot.getSourceData()
                    data.unshift({})
                    this.hot.loadData(data)
                    this.hot.updateSettings({
                        maxRows: data.length
                    })
                } else {
                    this.allData = [{}]
                    this.createHot()
                }
            },
            //页面发生更改
            changePage() {
                if (!this.changeFlag) {
                    //发生更改，提示是否保存
                    this.$confirm('存在数据未保存, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        this.getData()
                    }).catch(() => {
                        this.pages.currentPage = this.oldPage.currentPage
                        this.pages.size = this.oldPage.size
                        return false
                    });
                } else {
                    this.getData()
                }
            },
            getData() {
                // width = (document.getElementById("app").clientWidth - 50) / header.length
                this.isLoading = true
                let param = {
                    type: this.protocolType,
                    data: {
                        Filters: {
                            DatasourceId: this.datasourceId,
                        },
                        "PageNumber": this.pages.currentPage || 1,
                        "PageSize": this.pages.size,
                    }
                }
                this.oldPage = {
                    size: this.pages.size,
                    currentPage: this.pages.currentPage
                }
                queryPoint(param, res => {
                    console.log(res)
                    this.isLoading = false
                    this.changeFlag = true
                    this.allData = res.Content || []
                    this.pages.total = res.Total
                    this.createHot()
                })
            },
            //创建实例
            createHot() {
                let header, width, settings
                header = getHeaderSetting(this.protocolType)
                settings = {
                    data: this.allData,
                    colHeaders: changeHeader(header),
                    columns: showTypes(header),
                    // colWidths: width,
                    rowHeights: 30,
                    maxRows: this.allData.length
                }
                if (!this.allData.length) {
                    return false
                }
                this.$nextTick(_ => {
                    this.hot = this.$refs.handsontable.init(settings)
                    console.log(this.hot)
                })
            },
            //修改提示
            changeHand(changeData, source) {
                if (!!changeData) {
                    this.changeFlag = false
                }
                return false
            },
            //保存
            saveData() {
                if (!!this.hot) {
                    console.log(this.hot.getSourceData())
                    let data = this.hot.getSourceData(),
                        updateList = [],
                        arr1 = [],
                        createList = [];
                    data.map(item => {
                        // console.log(item.LocationFlag,1111)
                        if (!!item.Id) {
                            // if(!item.LocationFlag){
                            //     item.LocationFlag = []
                            // }
                            console.log(item)
                            delete item.CreateTime
                            delete item.LastUpdate
                            console.log(item)
                            arr1.push(item)
                            updateList.push(item)
                        } else {
                            createList.push(item)
                        }
                    })
                    console.log(updateList, arr1, "updateList")
                    if (updateList.length) {
                        this.update(updateList)
                    }
                    if (createList.length) {
                        this.createList(createList)
                    }
                } else {
                    this.$message.error("请确保存在数据")
                }
            },
            async createList(createList) {
                console.log(createList)
                let i = 0;
                for (i; i < createList.length; i++) {
                    if (createList[i].hasOwnProperty("Description")) {
                        await this.create(createList[i])
                    }
                }
                this.changeFlag = true
            },
            async create(obj) {
                console.log(obj)
                for (let key in obj) {
                    if (key == "LocationFlag" && obj[key] == "") {
                        obj[key] = []
                    }
                    if (obj[key] === "") {
                        obj[key] = null
                    }
                }
                obj.DatasourceId = this.datasourceId
                obj.ProjectId = this.projectId
                await createPoint({
                    data: obj,
                    type: this.protocolType
                }, res => {
                    console.log(res)
                    obj.Id = res.Id
                })
            },
            /**
             * @param {更新list} updateList
             * 
             * 更新点位
             */
            update(updateList) {
                updatePoint({
                    data: {
                        Content: updateList
                    },
                    type: this.protocolType
                }, res => {
                    console.log(res)
                })
            },
            //没有保存的时候弹窗
            noSaveData() {
                return this.changeFlag
            }
        },
        components: {
            handsontableComponent,
            ownDialog,
            localtionFalg,
            pagination
        },
    }
</script>
<style lang="scss" scoped>
    #handsonStep1 {
        flex: 1;
        display: flex;
        flex-flow:column;
        .btns-view {
            height: 40px;
            line-height: 40px;
            margin-bottom: 10px;
        }
        #handsontableSteps1 {
            flex: 1;
            overflow: hidden;
            position: relative;
        }
    }
</style>
