<template>
    <div id="handsonStep1">
        <div class="btns-view">
            <el-button style="float:right;margin-top:4px;margin-left:10px;width:120px;" @click="saveData">保存</el-button>
            <el-button style="float:right;margin-top:4px;width:120px;" @click="addRow">新增行</el-button>
            <el-button style="float:right;margin-top:4px;width:120px;" @click="downData">导出配置点位表</el-button>
            <el-button style="float:right;margin-top:4px;width:120px;" @click="updateExcel = true">导入Excel</el-button>
            <el-button style="float:right;margin-top:4px;width:120px;" @click="downloadExcel = true">导出Excel模板</el-button>
            <el-checkbox style="float:right;line-height:40px;" @change="getData" v-model="checked">只显示使用的原始点位</el-checkbox>
            <el-button @click="clickPointVal">获取原始点位当前值</el-button>
        </div>
        <div id="handsontableSteps1" class="middle_sty" v-loading="isLoading">
            <handsontable-component v-if="!!allData.length" @delete="delePoint" ref="handsontable" @mouseDown="clickTable" @change="changeHand"></handsontable-component>
            <div v-else class="center">
                <i class="icon-wushuju iconfont"></i>
                暂无数据
            </div>
        </div>
        <own-dialog :width="'500px'" :index="true" title="位置标签" :dialogVisible="localtionDialog" @cancel="closeFalg">
            <localtion-falg :renderData="renderData" @changeTag="changeLoc"></localtion-falg>
        </own-dialog>
        <own-dialog :width="'500px'" :index="true" title="导出excel模板" :dialogVisible="downloadExcel" :footer="footer" @cancel="close" @confirm="download">
            <span>请选择要导出的模板</span>
            <el-select v-model="exportTemplate" placeholder="请选择模板">
                <el-option label="标准模版" value="0"></el-option>
                <el-option label="设备采集多个参数模版" value="1" :disabled="protocolType!='common'"></el-option>
            </el-select>
        </own-dialog>
        <own-dialog :width="'500px'" :index="true" :footer="footer" title="导入excel" :dialogVisible="updateExcel" @confirm="sureOfUpload" @cancel="close">
            <div class="center" style="height:100px;">
                <upload-file accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" @change="changeFile"></upload-file>
                <p style="font-size:12px;">上传文件大小在1M以内</p>
            </div>
            <div>
                <span>请选择要导入的模板</span>
                <el-select v-model="importTemplate" placeholder="请选择模板">
                    <el-option label="标准模版" value="0"></el-option>
                    <el-option label="设备采集多个参数模版" value="1" :disabled="protocolType!='common'"></el-option>
                </el-select>
            </div>
            <div>
                <el-radio class="radio-left" v-model="radio" label="1">默认使用导入的全部原始点位</el-radio>
                <el-radio class="radio-left" v-model="radio" label="2">默认不使用导入的全部原始点位</el-radio>
            </div>
        </own-dialog>
        <div class="right">
            <pagination :page="pages" @change="changePage"></pagination>
        </div>
    </div>
</template>
<script>
    import tools from "@/utils/scan/tools"
    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 "@/assets/js/chosen.jquery.min";
    // import "@/assets/js/handsontable-chosen-editor";
    // import Handsontable from "handsontable-pro"
    import {
        mapGetters,
        mapActions
    } from "vuex";
    import {
        changeHeader,
        showTypes
    } from "@/utils/handsontable/delType"
    import {
        queryPoint,
        updatePoint,
        createPoint,
        downloadTemplete,
        uploadPointFile,
        uploadPointFile2,
        deletePoint,
        getPointValue
    } from "@/fetch/point_http"
    import uploadFile from "@/components/common/uploadFile"
    import axios from 'axios'
    export default {
        data() {
            return {
                checked: false,
                settings: {},
                hot: null,
                changeFlag: true, //是否发生修改
                localtionDialog: false,
                renderData: {},
                allData: [],
                copyMain: [],
                pages: {
                    size: 50,
                    sizes: [10, 30, 50, 100, 150, 200],
                    total: 0,
                    currentPage: 0
                },
                oldPage: {
                    currentPage: 0,
                    size: 10
                },
                downloadExcel: false,
                isLoading: false,
                updateExcel: false,
                radio: '1',
                file: "", //上传的文件
                footer: {
                    cancel: '取消',
                    confirm: '确定'
                },
                exportTemplate:'0',
                importTemplate:'0'
            }
        },
        computed: {
            ...mapGetters("project", [
                "datasourceId",
                "protocolType"
            ]),
            projectId () {
                return this.$store.getters['layout/projectId']
            }
        },
        created() {},
        mounted() {
            if (!this.datasourceId) {
                this.$router.push({
                    path: "/point/pointsetting"
                })
            } else {
                this.getData()
            }
        },
        methods: {
            //关闭弹窗
            close() {
                this.downloadExcel = false
                this.updateExcel = false
                this.getData()
            },
            closeFalg() {
                this.localtionDialog = false
            },
            clickPointVal(){
                let data = this.hot.getSourceData()
                if(!data || !data.length){
                    return false
                }
                let param = {
                    data: {
                        DataSourceId: this.datasourceId,
                        PointIds: data.map(item => {
                            return item.Id
                        })
                    },
                    type: this.protocolType
                }
                getPointValue(param,res => {
                    if(!!res.Content && res.Content.length){
                        data.map(item => {
                            res.Content.map(child => {
                                if(item.Id == child.PointId){
                                    item.pointValue = child.Data.Data
                                    item.pointDate = child.Data.Time
                                }
                            })
                            return item
                        })
                    }
                })
            },
            changeLoc(val) {
                this.renderData.LocationFlag = val
                this.changeFlag = false
            },
            downData() {
                let param = {
                    method: 'post',
                    url: `/pointconfig/point/${this.protocolType}/pointlist-export`,
                    data: {
                        DataSourceId: this.datasourceId
                    },
                    responseType: 'blob',
                    headers: {
                        ProjectId: this.projectId
                    }
                }
                axios(param).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) {
                })
            },
            //删除点位
            delePoint(delData) {
                let param = {
                    data: delData.map(item => {
                        return item.Id
                    }),
                    type: this.protocolType
                }
                console.log(delData,'delllll')
                if (!delData.length) {
                    return false
                }
                if(!!delData){
                    console.log(delData,'delData')
                    if(!delData[0].Id){
                        return false
                    }
                }
                this.$confirm('你确定要删除点位吗？').then(_ => {
                    deletePoint(param, res => {
                        this.$message.success("删除成功")
                        this.getData()
                    })
                }).catch(_ => {
                    this.$message("取消删除")
                    this.getData()
                })
            },
            //下载excel模板
            download() {
                let url = `/pointconfig/point/${this.protocolType}/template-export`
                if(this.exportTemplate=='1'){
                    url += '2'
                }
                axios({
                    method: 'post',
                    url: url,
                    data: {
                        DataSourceId: this.datasourceId
                    },
                    headers: {
                        ProjectId: this.projectId
                    },
                    responseType: 'blob'
                }).then(function(res) {
                    console.log(res)
                    var blob = new Blob([res.data], {
                        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
                    });
                    var fileName = decodeURI(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) {
                })
            },
            //点击表格
            clickTable(info, row) {
                let activeCell = this.hot.getActiveEditor()
                if(activeCell.prop == "Used"){
                    info.Used = !info.Used
                }
                if (activeCell.prop == "LocationFlag") {
                    this.renderData = info
                    this.localtionDialog = true
                }
            },
            addRow() {
                if (!!this.allData.length) {
                    let data = this.hot.getSourceData()
                    data.unshift({
                        Used: true,
                        LocationFlag: []
                    })
                    this.hot.loadData(data)
                    this.hot.updateSettings({
                        maxRows: data.length
                    })
                } else {
                    this.allData = [{
                        Used: true,
                        LocationFlag: []
                    }]
                    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,
                    }
                }
                if (this.checked) {
                    param.data.Filters.Used = true
                }
                this.oldPage = {
                    size: this.pages.size,
                    currentPage: this.pages.currentPage
                }
                queryPoint(param, res => {
                    this.isLoading = false
                    this.changeFlag = true
                    this.allData = res.Content || []
                    this.copyMain = JSON.parse(JSON.stringify(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),
                    rowHeights: 30,
                    maxRows: this.allData.length,
                     contextMenu: {
                        items: {
                            remove_row: {
                                name: "删除点位"
                            }
                        }
                    }
                }
                if (!this.allData.length) {
                    return false
                }
                this.$nextTick(_ => {
                    this.hot = this.$refs.handsontable.init(settings)
                })
            },
            //修改提示
            changeHand(changeData, source) {
                if (!!changeData) {
                    let tableData = this.hot.getSourceData()
                    for(let i = 0; i < tableData.length; i++){
                        let forFlag = true
                        if(!tools.isObjectValueEqual(this.copyMain[i],tableData[i])) {
                            this.changeFlag = false
                            forFlag = false
                            break
                        } else if (i == tableData.length - 1 && forFlag) {
                            this.changeFlag = true
                        }
                    }
                }
                return false
            },
            //保存
            saveData() {
                if (!!this.hot) {
                    console.log(this.hot.getSourceData(),'getSourceData')
                    let data = this.hot.getSourceData(),
                        updateList = [],
                        arr1 = [],
                        createList = [];
                    data.map(item => {
                        if (!!item.Id) {
                            delete item.CreateTime
                            delete item.LastUpdate
                            if(item.hasOwnProperty('pointDate')){
                                delete item.pointDate
                            }
                            if(item.hasOwnProperty('pointValue')){
                                delete item.pointValue
                            }
                            arr1.push(item)
                            updateList.push(item)
                        } else {
                            createList.push(item)
                        }
                    })
                    console.log(updateList,createList, arr1, "updateList")
                    if (createList.length || updateList.length) {
                        let flag = true
                        if (createList.length) {
                          for (let i = 0; i < createList.length; i++) {
                            if (!(
                                (createList[i].hasOwnProperty("SlaveId") &&
                                 createList[i].SlaveId &&
                                 createList[i].hasOwnProperty("RegistersAddress") &&
                                 createList[i].RegistersAddress &&
                                 createList[i].hasOwnProperty("RegistersQuality") &&
                                 createList[i].RegistersQuality &&
                                 createList[i].hasOwnProperty("ConvertType") &&
                                 createList[i].ConvertType
                                ) ||
                                (createList[i].hasOwnProperty("DeviceId") &&
                                 createList[i].DeviceId &&
                                 createList[i].hasOwnProperty("InstanceNumber") &&
                                 createList[i].InstanceNumber &&
                                 createList[i].hasOwnProperty("DataType") &&
                                 createList[i].DataType
                                ) ||
                                (createList[i].hasOwnProperty("Item") &&
                                 createList[i].Item
                                ) ||
                                (createList[i].hasOwnProperty("GroupAddress") &&
                                 createList[i].GroupAddress
                                ) ||
                                (createList[i].hasOwnProperty("Topic") &&
                                 createList[i].Topic
                                ) ||
                                (createList[i].hasOwnProperty("Exchange") &&
                                 createList[i].Exchange &&
                                 createList[i].hasOwnProperty("Type") &&
                                 createList[i].Type &&
                                 createList[i].hasOwnProperty("RoutingKey") &&
                                 createList[i].RoutingKey
                                ) ||
                                (createList[i].hasOwnProperty("JoinedInfo") &&
                                 createList[i].JoinedInfo
                                )
                              )) {
                                this.$message("请输入所有必填字段（带“*”列为必填列）")
                                flag = false
                                return false
                            } else if (!(createList[i].hasOwnProperty("Description") && createList[i].Description)) {
                               this.$message("请输入全部的原始点位描述")
                               flag = false
                               return false
                            }
                          }
                        }
                        if (flag) {
                            this.createList(createList)
                            if (updateList.length) {
                                this.update(updateList)
                            }
                        }
                    }
                } else {
                    this.$message.error("请确保存在数据")
                }
            },
            async createList(createList) {
                for (let i = 0; i < createList.length; i++) {
                    await this.create(createList[i])
                }
                this.changeFlag = true
            },
            async create(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 => {
                    obj.Id = res.Id
                    this.getData()
                })
            },
            /**
             * @param {更新list} updateList
             *
             * 更新点位
             */
            update(updateList) {
                updatePoint({
                    data: {
                        Content: updateList
                    },
                    type: this.protocolType
                }, res => {
                    this.getData()
                })
            },
            //没有保存的时候弹窗
            noSaveData() {
                return this.changeFlag
            },
            //上传文件
            changeFile(file) {
                this.file = file[0] || ''
            },
            //确定上传
            sureOfUpload() {
                if (!!this.file) {
                    //有文件进行上传
                    let param = {
                        data: new FormData(),
                        type: this.protocolType
                    };
                    param.data.set('DataSourceId', this.datasourceId)
                    param.data.set('Used', this.radio == 1 ? true : false)
                    param.data.set('multipartFile', this.file.raw)
                    if(this.importTemplate=='1'){
                        uploadPointFile2(param, res => {
                            this.$message.success("上传成功")
                            this.getData()
                            this.updateExcel = false
                        })
                    } else {
                        uploadPointFile(param, res => {
                            this.$message.success("上传成功")
                            this.getData()
                            this.updateExcel = false
                        })
                    }
                } else {
                    this.$message.info("请选择文件")
                }
            }
        },
        components: {
            handsontableComponent,
            ownDialog,
            localtionFalg,
            pagination,
            uploadFile
        },
    }
</script>
<style lang="scss" scoped>
    .radio-left {
        display: block;
        line-height: 30px;
        margin-left: 100px;
    }
    #handsonStep1 {
        flex: 1;
        display: flex;
        flex-flow: column;
        padding-bottom: 10px;
        .btns-view {
            height: 40px;
            line-height: 40px;
            margin-bottom: 10px;
            padding: 0 10px;
        }
        #handsontableSteps1 {
            flex: 1;
            overflow: hidden;
            position: relative;
            margin: 0 10px;
        }
    }
</style>
