<template>
    <div id="handsonStep2">
        <div class="btns-view">
            <el-button style="width:164px" @click="aiDiscern">AI自动识别</el-button>
            <el-button @click="discern(1)">批量识别对象类型关键字</el-button>
            <el-button @click="discern(2)">批量识别对象参数关键字</el-button>
            <el-button style="width:164px" @click="examine">检查&微调</el-button>
            <div style="float:right;">
                <el-button @click="reset">刷新</el-button>
                <el-button @click="saveData">保存</el-button>
            </div>
        </div>
        <div id="handsontableSteps1" class="middle_sty" v-loading="isLoading">
            <handsontable-component v-if="!!pages.total" @delete="delePoint" @mouseDown="clickTable" @change="changeHand" ref="handsontable"></handsontable-component>
            <div v-else class="center">
                <i class="icon-wushuju iconfont"></i> 暂无数据
            </div>
        </div>
        <div class="right">
            <pagination :page="pages" @change="changePage"></pagination>
        </div>
        <own-dialog :width="'60%'" :title="title" :dialogVisible="isDialogShow" @cancel="close">
            <find-keyword ref="findKeyword" :type="type" @change="changeHand"></find-keyword>
        </own-dialog>
        <own-dialog :width="'1200px'" :index="true" title="关键内容设别——检查&微调" :dialogVisible="examineDialog" @cancel="close">
            <!-- <find-keyword ref="findKeyword" :type="type"></find-keyword> -->
            <examine-main></examine-main>
        </own-dialog>
        <!-- <own-dialog :width="'1000px'" :index="true" title="关键内容设别——检查&微调" :dialogVisible="examineDialog" @cancel="close"> -->
        <!-- <find-keyword ref="findKeyword" :type="type"></find-keyword> -->
        <!-- <examine-main></examine-main>
                </own-dialog> -->
        <own-dialog :width="'500px'" :index="true" title="位置标签" :dialogVisible="localtionDialog" @cancel="localFalgChange">
            <localtion-falg :renderData="renderData" @changeTag="changeLoc"></localtion-falg>
        </own-dialog>
        <own-dialog :width="'500px'" :footer="footer" :index="true" :escape="false" :isModel="false" title="AI自动识别" :dialogVisible="aiDialog" @confirm="isTrue" @cancel="aiClose">
            <!-- <localtion-falg :renderData="renderData" @changeTag="changeLoc"></localtion-falg> -->
            <div v-if="hadTrue" style="height: 100px;">
                <el-progress :text-inside="true" :stroke-width="18" :percentage="usedNum"></el-progress>
                <p v-if="content.Current != content.Sum" class="center">正在识别，请稍后……（{{content.Current}}/{{content.Sum}}）</p>
                <p v-else class="center" style="margin-top:10px;">目前已识别 <i class="el-button--text">{{content.DiscernCount}}</i> 个点位，识别率为  <i class="el-button--text">{{content.DiscernRate}}</i></p>
            </div>
            <div v-else>
                <p>确认要人工智能识别么？</p>
            </div>
        </own-dialog>
    </div>
</template>
<script>
    import tools from "@/utils/scan/tools"
    import handsontableComponent from "@/components/common/handsontable"
    import examineMain from "@/components/config_point/examine_main"
    import headerArr from "@/utils/point_edit/steps2.js"
    import localtionFalg from "@/components/config_point/location_flag"
    import {
        changeHeader,
        showTypes
    } from "@/utils/handsontable/delType"
    import ownDialog from "@/components/el_pack/dialog"
    import {
        mapGetters,
        mapActions
    } from "vuex";
    import {
        queryPoint,
        updatePoint,
        deletePoint,
        AIFindPoint,
        AIPlan
    } from "@/fetch/point_http"
    import findKeyword from "@/components/config_point/find_keyword"
    import pagination from "@/components/common/myPagination"
    export default {
        data() {
            return {
                checked: false,
                settings: {},
                copyMain: [],
                isDialogShow: false,
                msg: "",
                hot: null,
                title: "",
                type: "",
                examineDialog: false,
                changeFlag: true,
                pages: {
                    size: 50,
                    sizes: [10, 30, 50, 100, 150, 200],
                    total: 0,
                    currentPage: 0
                },
                oldPage: {
                    currentPage: 0,
                    size: 10
                },
                localtionDialog: false,
                renderData: {},
                isLoading: false,
                aiDialog: false,
                hadTrue: false,//是否确定人工智能升级
                usedNum: 0,//识别百分比
                footer:{},
                content: {
                    Current: 1,//当前识别
                    DiscernCount: 1,//已识别个数
                    DiscernRate: 1,//识别比例
                    Sum: 2,//总数
                }
            }
        },
        created() {
            if (!this.protocolType) {
                this.$router.push({
                    path: "/configPoint"
                })
            }
        },
        mounted() {
            this.getData()
        },
        computed: {
            ...mapGetters("project", [
                "datasourceId",
                "protocolType"
            ]),
            projectId () {
                return this.$store.getters['layout/projectId']
            }
        },
        methods: {
            clickTable(info, row) {
                // let activeCell = this.hot.getActiveEditor()
                // this.renderData = info
                // console.log(activeCell, 'activeCell')
                // if (activeCell.prop == "LocationFlag") {
                //     this.localtionDialog = true
                // }
            },
            //人工智能识别
            aiDiscern(){
                this.hadTrue = false
                this.footer = {}
                this.aiDialog = true
            },
            //确认人工识别
            isTrue(){
                AIFindPoint({
                    data: {
                        DataSourceId: this.datasourceId
                    },
                    type: this.protocolType
                },res => {
                    this.timer = setInterval(() => {
                        this.getSchedule()
                    }, 1000)
                    this.hadTrue = true
                    this.footer = null
                })
            },
            async getSchedule(){
                await AIPlan({
                    type: this.protocolType,
                    data: {
                        DataSourceId: this.datasourceId
                    }
                },res => {
                    this.content = res.Content[0]
                    this.usedNum = (this.content.Current/this.content.Sum).toFixed(2)*100
                    if (this.usedNum >= 100) {
                        clearInterval(this.timer)
                        this.aiDialog = false
                        this.reset()
                    }
                })
            },
            changeLoc(val) {
                this.renderData.LocationFlag = val
                this.changeFlag = false
            },
            //关闭人工智能弹窗
            aiClose(){
                this.aiDialog = false
                clearInterval(this.timer)
            },
            //刷新
            reset() {
                if (!this.changeFlag) {
                    this.$confirm("表格数据尚未保存，确定刷新吗？").then(_ => {
                        this.changeFlag = true
                        this.pages.currentPage = this.oldPage.currentPage
                        this.pages.size = this.oldPage.size
                        this.getData()
                    })
                } else {
                    this.getData()
                }
            },
            //删除点位
            delePoint(delData) {
                let param = {
                    data: delData.map(item => {
                        return item.Id
                    }),
                    type: this.protocolType
                }
                console.log(param, 'param')
                this.$confirm('你确定要删除点位吗？').then(_ => {
                    console.log(param, 'param')
                    deletePoint(param, res => {
                        this.$message.success("删除成功")
                        this.getData()
                    })
                }).catch(_ => {
                    this.$message("取消删除")
                    this.getData()
                })
            },
            //页面发生更改
            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()
                }
            },
            /**
             *  @param num 代表着1类型2参数
             * 
             */
            discern(num) {
                if (num == 1) {
                    this.title = "关键内容识别——批量识别对象类型关键字"
                    this.type = "type"
                } else if (num == 2) {
                    this.title = "关键内容识别——批量识别对象参数关键字"
                    this.type = "arguments"
                }
                this.isChangeDo(this.dialogDo,this.elseDo,true)
            },
            isChangeDo(func,elseDo,falg = false){
                if (!this.changeFlag) {
                    //发生更改，提示是否保存
                    this.$confirm('存在数据未保存, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        func(falg)
                    }).catch(() => {
                        elseDo()
                    });
                } else {
                    func(falg)
                }
            },
            //否则
            elseDo(){
                this.pages.currentPage = this.oldPage.currentPage
                this.pages.size = this.oldPage.size
                return false
            },
            //处理弹窗
            dialogDo(flag){
                if(!!flag && !this.changeFlag){
                    this.changeFlag = !this.changeFlag
                }
                this.isDialogShow = true
                this.$nextTick(() => {
                    this.$refs.findKeyword.changeType(this.type)
                })
            },
            close() {
                this.isDialogShow = false
                this.examineDialog = false
                this.isChangeData()
            },
            localFalgChange() {
                this.localtionDialog = false
            },
            //判断是否修改，修改调用修改接口，否则调用获取最新数据
            isChangeData() {
                if (!this.changeFlag) {
                    this.saveData(false)
                } else {
                    this.getData()
                }
            },
            //点击检查按钮
            examine() {
                this.isChangeDo(this.examineTrue,this.elseDo,true)
            },
            examineTrue(flag){
                if(!!flag && !this.changeFlag){
                    this.changeFlag = !this.changeFlag
                }
                this.examineDialog = true
            },
            //保存
            saveData(falg) {
                if (!!this.hot) {
                    let data = this.hot.getSourceData(),
                        changeData;
                    changeData = data.map(item => {
                        return {
                            Id: item.Id,
                            DatasourceId: item.DatasourceId,
                            ProjectId: item.ProjectId,
                            Description: item.Description || null,
                            KeyEquipmentParameter: item.KeyEquipmentParameter || null,
                            Remarks: item.Remarks || null,
                            LocationFlag: item.LocationFlag || null,
                            KeyEquipmentType: item.KeyEquipmentType || null
                        }
                    })
                    updatePoint({
                        data: {
                            Content: changeData
                        },
                        type: this.protocolType
                    }, res => {
                        console.log(res)
                        if (falg) {
                            this.$message.success("保存成功")
                        }
                        this.changeFlag = true
                        this.getData()
                    })
                } else {
                    this.$message.error("请确保存在数据")
                }
            },
            //发生更改
            changeHand(changeData, source) {
                console.log(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
                        }
                    }
                }
                console.log(this.changeFlag)
                return false
            },
            //获取初始数据
            getData() {
                this.isLoading = true
                let width, param, settings
                // width = (document.getElementById("app").clientWidth - 50) / headerArr.length
                param = {
                    type: this.protocolType,
                    data: {
                        Filters: {
                            DatasourceId: this.datasourceId,
                            Used: true
                        },
                        "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)
                    settings = {
                        data: res.Content,
                        colHeaders: changeHeader(headerArr),
                        columns: showTypes(headerArr),
                        // colWidths: width,
                        rowHeights: 30,
                        maxRows: res.Content.length,
                        contextMenu: {
                            items: {
                                remove_row: {
                                    name: "删除点位"
                                }
                            }
                        }
                    }
                    this.copyMain = JSON.parse(JSON.stringify(res.Content))
                    this.pages.total = res.Total
                    this.isLoading = false
                    if (!this.pages.total) {
                        return false
                    }
                    this.$nextTick(_ => {
                        this.hot = this.$refs.handsontable.init(settings)
                    })
                    console.log(this.hot)
                })
            },
            noSaveData() {
                return this.changeFlag
            }
        },
        components: {
            handsontableComponent,
            ownDialog,
            findKeyword,
            examineMain,
            pagination,
            localtionFalg
        }
    }
</script>
<style lang="scss" scoped>
    #handsonStep2 {
        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>