<template>
    <div class="content">
        <div class="tabs">
            <ul>
                <li v-for="(tab,i) in tabs" @click="goTab(tab.url)" :class="{'active':tabIndex == i}">
                    {{tab.name}}
                </li>
            </ul>
        </div>
        <div class="panel">
            <div class="panel-body">
                <div class=" panel_control">
                    <div class="pline">
                        <em>策略名称:</em>
                        <el-input v-model="panel.tagname" placeholder=""></el-input>
                    </div>
                    <div class="pline">
                        <el-button size="medium" type="primary" @click="query">查询</el-button>
                    </div>
                    <div class="pline pull-right">
                        <el-button size="medium" type="primary" @click="addList">添加</el-button>
                        <el-button size="medium" type="primary" @click="editList">修改</el-button>
                        <el-button size="medium" type="primary" @click="delList">删除</el-button>
                    </div>
                </div>
            </div>
        </div>
        <el-table
                :data="tableData"
                is-horizontal-resize
                :default-sort="{prop: 'date', order: 'descending'}"
                v-loading="loading"
                element-loading-background="rgba(0, 0, 0, 0.8)"
                class=""
                @selection-change="handleSelectionChange"
                stripe
                ref="multipleTable"
                @row-click="handle"
        >
            <el-table-column type="expand">
                <template slot-scope="props">
                    <el-table
                            :data="props.row.Value.SignalList"
                            style="width: 100%">
                        <el-table-column
                                prop="Type"
                                label="无线协议"
                                :formatter="filterWirelessTypeName"

                        >
                        </el-table-column>
                        <el-table-column
                                prop="Range"
                                label="扫描距离"
                                :formatter="filterDistanceName"
                                sortable
                        >
                        </el-table-column>
                        <el-table-column
                                prop="begin"
                                label="起始频率"
                                sortable
                        >
                        </el-table-column>
                        <el-table-column
                                prop="end"
                                label="截止频率"
                                sortable
                        >
                        </el-table-column>
                    </el-table>
                </template>
            </el-table-column>
            <el-table-column
                    type="selection"
                    width="55">
            </el-table-column>
            <el-table-column
                    type="index"
                    label="序号"
                    width="60"
                    sortable
            >
            </el-table-column>
            <el-table-column
                    prop="Name"
                    label="策略名称"
            >
            </el-table-column>
            <el-table-column
                    prop="Value.IsRecording"
                    label="信号录制"
                    sortable
            >
                <template slot-scope="scope">
                    <span class="red" v-if="scope.row.Value.IsRecording" style="color: #72FF99">已启用</span>
                    <span v-else style="color: red">已禁用</span>
                </template>
            </el-table-column>
            <el-table-column
                    prop="CreateAt"
                    label="创建时间"
                    sortable
                    :formatter="filterTime"
            >
            </el-table-column>
        </el-table>
        <br>
        <el-pagination
                background
                :total="pageination.total"
                :page-size="pageination.pageItem"
                @current-change="pageChange"
        ></el-pagination>
    </div>
</template>

<script>
    import Global from '../Global.js'
    import dialog_referrer_list from '../components/dialog_referrer_list'
    import {
        DetectorQuery,
        GetChildRegionSelect,
        DetectorEditStatus,
        RegionPictureGetByRegionId,
        DetectorAdd,
        RegionList,
        DetectorList,
        DetectorEdit,
        GetDetectorCoords,
        GeFullRegionSelect,
        ScanStrategyListDetail,
        ScanStrategyDel
    } from '../api/getApiRes.js'

    let qs = require('qs');
    export default {
        data() {
            return {
                // dialog
                dialog_state: false,
                dialog_title: '',
                dialog_type: '',//类型，1是添加，2是修改
                dialog: {
                    mac: '',
                    comId: 1,
                    regionlevelOneId: 0,
                    regionId: 0,
                    tagname: '',
                    longitude: 0,
                    latitude: 0,
                    HardwareVersion: '',
                    FirmwareVersion: '',
                    FirmwareScanM4Version: '',
                    FirmwareScanM0Version: '',
                    purchasesrc: '',
                    location: '',
                    coords_memo: '',
                    memo: '',
                    plateImgSrc: '',
                    regionlevelOneIdOptions: [],
                    regionIdRoomOptions: [],
                    points: [],
                    CoordsId: 0,
                    status: 0,
                },
                tabIndex: 0,
                tabs: [
                    {name: '扫描策略管理', url: 'tactics'},
                ],
                // panel 配置项目
                panel: {
                    usercode: '',
                    username: '',
                    compname: '',
                    keyword: '',
                    USERCODE: '',
                    taskstatus: 99,
                    regionid: 0,
                    regionid2: '',
                    regionidOptions: [],
                    regionidOptions2: [],
                    options: [
                        {value: 99, label: '全部'},
                        {value: 1, label: '进行中'},
                        {value: 2, label: '已完成'},
                    ],
                    time1: globalBt3(2),
                },
                pageination: {
                    pageItem: 100,
                    pageoptions: pageOptions(),
                    total: 500,
                    pageIndex: 1,
                },
                draw: 1,
                start: 0,
                recordsTotal: 0,
                tableData: [],
                allTableData: [],
                limit: '10',
                multipleSort: false,
                loading: true,
                fileList: [],
                multipleSelection: [],
                detectedmac: '',
            }
        },
        mounted() {
            if (this.$route.query.RegionId) {
                this.panel.regionid = this.$route.query.RegionId;
                this.panel.tagname = this.$route.query.TagName;
            }

            this.getTableQuery();
        },
        watch: {
            '$route': function (val) {
                if (val.path == '/tactics') {
                    this.getTableQuery();
                }
            },
        },
        methods: {
            handle(row, column, event) {
                this.$refs.multipleTable.toggleRowSelection(row);
            },
            // 页面数据查询
            getTableQuery() {
                let that = this;
                // this.getGetChildRegionSelect(0, 1);
                this.getGeFullRegionSelect();
                that.loading = true;
                // 查询检测策略。上级区域id，区域id必传。regionid传0，查询supregionid对应所有子区域的检测策略。 如果supregionid，regionid都传0，默认查询企业ID下所有检测策略
                let param = {
                    token: localStorage.token,
                    name: that.panel.tagname,//标签名
                };
                let postdata = qs.stringify(param);
                ScanStrategyListDetail(postdata).then(res => {
                    let json = res;
                    if (json.Code == 0) {
                        that.loading = false;
                        if (json.Rs) {

                            // 把起始频率回填
                            json.Rs.map(function (item) {
                                item.Value.SignalList.map(function (row) {
                                    if (row.Type == 13) {
                                        row.begin = item.Value.Freq06G[0].Begin;
                                        row.end = item.Value.Freq06G[0].End;
                                    }
                                })
                            });

                            that.allTableData = json.Rs;
                            that.recordsTotal = json.Rs.length;
                        } else {
                            that.allTableData = [];
                            that.recordsTotal = 0;
                        }
                        // 设置分页数据
                        that.setPaginations();
                    } else {
                        that.$message.error(json.Memo + '，错误代码：' + json.Code);
                    }
                })
            },
            // 获取下级列表
            getGeFullRegionSelect() {
                let that = this;
                let param = {
                    token: localStorage.token,
                };
                let postdata = qs.stringify(param);
                RegionList(postdata).then(res => {
                    let json = res;
                    if (json.Code == 0) {
                        if (!json.Rs) {
                            that.$message.error('区域列表为空，请先添加有效区域');
                            return false
                        }
                        that.panel.regionidOptions = json.Rs;
                        that.panel.regionidOptions.unshift({Id: 0, Name: "全部", DisplayName: "全部"});
                    } else {
                        that.$message.error(json.Memo + '，错误代码：' + json.Code);
                    }
                })
            },
            // dialog获取下级列表
            dialoggetGeFullRegionSelect() {
                let that = this;
                let param = {
                    token: localStorage.token,
                };
                let postdata = qs.stringify(param);
                RegionList(postdata).then(res => {
                    let json = res;
                    if (json.Code == 0) {
                        that.dialog.regionlevelOneIdOptions = json.Rs;
                        that.dialog.regionId = json.Rs[0].Id;
                    } else {
                        that.$message.error(json.Memo + '，错误代码：' + json.Code);
                    }
                })
            },
            // dialog获取区域下级菜单
            dialogGetGetChildRegionSelect(regionId, level) {
                let that = this;
                let param = {
                    token: localStorage.token,
                    regionId: regionId,
                };
                let postdata = qs.stringify(param);
                RegionList(postdata).then(res => {
                    let json = res;
                    if (json.Code == 0) {
                        that.dialog.regionlevelOneIdOptions = json.Rs;
                        that.dialog.regionlevelOneId = regionId;
                        // if (level == 1) {
                        //     console.log(json.Rs);
                        //     that.dialog.regionlevelOneIdOptions = json.Rs;
                        //     that.dialog.regionlevelOneId = regionId;
                        // } else {
                        //     if (json.Rs) {
                        //         console.log(123);
                        //         that.dialog.regionIdRoomOptions = json.Rs;
                        //         that.dialog.regionId = regionId;
                        //     } else {
                        //         that.dialog.regionIdRoomOptions = [];
                        //         that.dialog.regionId = '';
                        //     }
                        // }
                    } else {
                        that.$message.error(json.Memo + '，错误代码：' + json.Code);
                    }
                })
            },
            // 跳转tab页面
            goTab(url) {
                this.$router.push({path: url});
            },
            // 查询按钮
            query() {
                this.getTableQuery();
                this.$message.success('查询完毕');
            },

            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            // 设置分页数据
            setPaginations() {
                // 分页属性
                let that = this;
                that.pageination.total = that.recordsTotal;
                // 默认分页
                that.tableData = that.allTableData.filter((item, index) => {
                    return index < that.pageination.pageItem;
                });
            },
            // 每页显示数量
            handleSizeChange() {
                let that = this;
                that.tableData = that.allTableData.filter((item, index) => {
                    return index < that.pageination.pageItem;
                });
                that.draw = that.pageination.pageItem;
                // that.getTableQuery();
            },
            // 翻页
            pageChange(pageIndex) {
                let that = this;
                // 获取当前页
                let index = that.pageination.pageItem * (pageIndex - 1);
                // 数据总数
                let nums = that.pageination.pageItem * pageIndex;
                // 容器
                let tables = [];
                for (var i = index; i < nums; i++) {
                    if (that.allTableData[i]) {
                        tables.push(that.allTableData[i])
                    }
                    this.tableData = tables;
                }
                that.start = index * that.draw;
                // that.getTableQuery();
            },
            // 自动排序
            sortChange(params) {
                console.log(params)
            },
            // 过滤时间
            filterFmtDate(value, row, column) {
                return globalfmtDate(column, 11);
            },
            addList() {
                this.$router.push(
                    {
                        path: '/addTactics', query: {tid: 0}
                    }
                )
            },
            delList() {
                let that = this;
                // checkNum
                if (!this.multipleSelection.length) {
                    that.$message({
                        showClose: true,
                        message: '错了哦，需要先选中至少一条记录',
                        type: 'error'
                    });
                    return false
                }
                if (this.multipleSelection.length > 1) {
                    this.$message({
                        showClose: true,
                        message: '错了哦，只能选中一条记录',
                        type: 'error'
                    });
                    return false
                }
                let Id = that.multipleSelection[0].Id;

                let param = {
                    token: localStorage.token,
                    id: Id,
                };
                let postdata = qs.stringify(param);

                this.$confirm('此操作将永久删除该策略, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    ScanStrategyDel(postdata).then(res => {
                        let json = res;
                        if (json.Code == 0) {
                            that.$message({
                                showClose: true,
                                message: '选中的策略已删除！',
                                type: 'success'
                            });
                            // 重载列表
                            that.getTableQuery();
                            that.dialog_state = false;
                        } else {
                            that.$message.error(json.Memo + '，错误代码：' + json.Code);
                        }
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            editList() {
                let that = this;
                // checkNum
                if (!this.multipleSelection.length) {
                    this.$message({
                        showClose: true,
                        message: '错了哦，需要先选中一条记录',
                        type: 'error'
                    });
                    return false
                }
                if (this.multipleSelection.length > 1) {
                    this.$message({
                        showClose: true,
                        message: '错了哦，只能选中一条记录',
                        type: 'error'
                    });
                    return false
                }
                let row = this.multipleSelection[0];
                this.$router.push(
                    {
                        path: '/addtactics', query: {tid: row.Id, name: row.Name, Value: JSON.stringify(row.Value)}
                    }
                );
            },
            // 自动补全MAC
            autoCompleteMac() {
                let text = this.dialog.mac;
                if (text.length == 2 || text.length == 5 || text.length == 8 || text.length == 11 || text.length == 14) {
                    this.dialog.mac = this.dialog.mac.toUpperCase() + ":"
                }
                if (text.length > 14) {
                    this.dialog.mac = this.dialog.mac.toUpperCase()
                }
            },
            // 探测记录
            goPhoneRecord(row) {
                this.$router.push({
                    path: '/phoneSign',
                    query:
                        {
                            detectorid: row.Id,
                            comId: 1,
                            regionId: row.RegionId,
                        }
                });
            },
            // 探测记录
            goWifiRecord(row) {
                this.$router.push({
                    path: '/wifiSign',
                    query:
                        {
                            detectorid: row.Id,
                            comId: 1,
                            regionId: row.RegionId,
                        }
                });
            },
            dialog_cancel() {
                let that = this;
                that.dialog_state = false;
            },
            dialog_ok() {
                if (this.dialog_type == 1) {
                    this.confirmAddEquip();
                } else {
                    this.confirmEditEquip();
                }
            },
            // 提交增加新策略
            confirmAddEquip() {
                let that = this;
                // checkVal
                if (!that.dialog.mac) {
                    this.$message.error('错了哦，mac不能为空');
                    return false
                }
                if (!checkMac(that.dialog.mac)) {
                    this.$message.error('错了哦，mac格式不正确');
                    return false
                }
                if (!that.dialog.regionId) {
                    this.$message.error('错了哦，所属区域不能为空');
                    return false
                }
                if (!that.dialog.tagname) {
                    this.$message.error('错了哦，标签名不能为空');
                    return false
                }
                if (that.dialog.tagname.length > 20) {
                    this.$message.error('错了哦，标签名不能超过20个字符');
                    return false
                }
                this.selectRegionLabel(that.dialog.regionId);
                let param = {
                    token: localStorage.token,
                    mac: that.dialog.mac,
                    comId: 1,
                    regionId: that.dialog.regionId,
                    name: that.dialog.tagname,
                    HardwareVersion: that.dialog.HardwareVersion,
                    FirmwareVersion: that.dialog.FirmwareVersion,
                    FirmwareScanM4Version: that.dialog.FirmwareScanM4Version,
                    FirmwareScanM0Version: that.dialog.FirmwareScanM0Version,
                    location: that.dialog.location,
                    purchasesrc: that.dialog.purchasesrc,
                    x: that.dialog.points[0].x,
                    y: that.dialog.points[0].y,
                    // coords_memo: that.dialog.coords_memo,
                    memo: that.dialog.memo,
                };
                let postdata = qs.stringify(param);
                DetectorAdd(postdata).then(res => {
                    let json = res;
                    if (json.Code == 0) {
                        that.$message({
                            showClose: true,
                            message: '策略添加成功！',
                            type: 'success'
                        });
                        // 重载列表
                        that.getTableQuery();
                        that.dialog_state = false;

                    } else {
                        that.$message.error(json.Memo + '，错误代码：' + json.Code);
                    }
                });
            },
            // 提交修改策略信息
            confirmEditEquip() {
                let that = this;
                // checkVal
                if (!that.dialog.mac) {
                    this.$message.error('错了哦，mac不能为空');
                    return false
                }
                if (!checkMac(that.dialog.mac)) {
                    this.$message.error('错了哦，mac格式不正确');
                    return false
                }

                if (!that.dialog.regionId) {
                    this.$message.error('错了哦，所属区域不能为空');
                    return false
                }
                if (!that.dialog.tagname) {
                    this.$message.error('错了哦，标签名不能为空');
                    return false
                }
                if (that.dialog.tagname.length > 20) {
                    this.$message.error('错了哦，标签名不能超过20个字符');
                    return false
                }
                this.selectRegionLabel(that.dialog.regionId);
                let param = {
                    token: localStorage.token,
                    id: that.dialog.eqId,
                    mac: that.dialog.mac,
                    comId: 1,
                    regionId: that.dialog.regionId,
                    name: that.dialog.tagname,
                    HardwareVersion: that.dialog.HardwareVersion,
                    FirmwareVersion: that.dialog.FirmwareVersion,
                    FirmwareScanM4Version: that.dialog.FirmwareScanM4Version,
                    FirmwareScanM0Version: that.dialog.FirmwareScanM0Version,
                    location: that.dialog.location,
                    purchasesrc: that.dialog.purchasesrc,
                    x: that.dialog.points[0].x,
                    y: that.dialog.points[0].y,
                    coords_memo: that.dialog.coords_memo,
                    memo: that.dialog.memo,
                    coordsType: 1,//坐标状态 0：禁用， 1：启用， 9：删除，没有就传0
                    coordsID: that.dialog.CoordsId,
                    status: that.dialog.status,
                };

                let postdata = qs.stringify(param);
                DetectorEdit(postdata).then(res => {
                    let json = res;
                    if (json.Code == 0) {
                        that.$message({
                            showClose: true,
                            message: '策略添加成功！',
                            type: 'success'
                        });
                        // 重载列表
                        that.getTableQuery();
                        that.dialog_state = false;

                    } else {
                        that.$message.error(json.Memo + '，错误代码：' + json.Code);
                    }
                });
            },
            // 修改策略状态
            getDetectorEditStatus(detectorid, status, text) {
                let that = this;
                let param = {
                    token: localStorage.token,
                    detectorid: detectorid,
                    status: status,
                };
                let postdata = qs.stringify(param);
                DetectorEditStatus(postdata).then(res => {
                    let json = res;
                    if (json.Code == 0) {
                        that.$message({
                            showClose: true,
                            message: text + '成功！',
                            type: 'success'
                        });
                        // table 重载
                        that.getTableQuery();
                    } else {
                        that.$message.error(json.Memo + '，错误代码：' + json.Code);
                    }
                })
            },
            // 禁用
            pauseRow(row) {
                let that = this;
                this.$confirm('是否禁用' + row.TagName + '策略？', '禁用操作', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    that.getDetectorEditStatus(row.Id, 0, '禁用');
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消禁用'
                    });
                });
            },
            // 获取区域位置的平面图
            getRegionPictureGetByRegionId(regionID) {
                let that = this;
                let param = {
                    token: localStorage.token,
                    regionID: regionID,
                    regionId: regionID,
                };
                let postdata = qs.stringify(param);
                that.dialog.plateImgSrc = '../assets/img/main/grid.png'
                // RegionPictureGetByRegionId(postdata).then(res => {
                //     let json = res;
                //     that.dialog.plateImgSrc = '';
                //     if (json.Code == 0) {
                //         that.dialog.plateImgSrc = json.EncodeString;
                //     } else {
                //         that.$message.error(json.Memo + '，错误代码：' + json.Code);
                //     }
                // })
            },
            // 启用
            runRow(row) {
                console.log(row);
                let that = this;
                this.$confirm('是否启用' + row.TagName + '策略？', '启用操作', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    that.getDetectorEditStatus(row.Id, 1, '启用');
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消启用'
                    });
                });
            },
            // 添加探测器位置的点坐标
            addPoint(e) {
                let x = e.offsetX;
                let y = e.offsetY;
                this.dialog.points = [{x: x, y: y}];
            },
            // 获取位置的文字内容
            selectRegionLabel(id) {
                let that = this;
                let selectedWorkName = {};
                // selectedWorkName = that.dialog.regionIdRoomOptions.filter(item => {
                selectedWorkName = that.dialog.regionlevelOneIdOptions.filter(item => {
                    if (item.Id === id) {
                        console.log(item.Name);
                        that.dialog.location = item.Name;
                    }
                });
            },
            // 过滤设备类型
            filterWirelessTypeName(value, row, column) {
                return filterWirelessType(column);
            },
            filterDistanceName(value, row, column) {
                return filterWirelessRangeText(column)
            },
            filterTime(val, row, column) {
                return nonTfmtDate(column, 10);
            }
        }

        ,
        components: {
            dialog_referrer_list
        }
    }
</script>

<style scoped>
    @import "../assets/css/panel.css";
    @import "../assets/css/dialog.css";

    .tabs ul {
        width: 168px;
        float: left;
    }

    table span {
        cursor: pointer;
    }

    .down_btn {
        float: left;
    }

    .content {
        width: 98%;
        overflow: hidden;
        display: block;
        margin: 0 auto;
        padding-left: 20px;
    }

    .selectStyle {
        width: 100%;
        color: #005EA2;
    }

    .selectStyle ::placeholder {
        color: #005EA2;
    }

    /deep/ .modal .el-select .el-input .el-select__caret {
        position: relative;
        top: 35px;
    }

    .imgContianer {
        width: 100%;
        height: 340px;
        overflow: hidden;
        display: block;
        margin: 0 auto;
    }

    .imgContianer img {
        width: 100%;
        height: 100%;
        overflow: hidden;
        display: block;
        margin: 0 auto;
    }

    .pointers {
        position: relative;
        bottom: 340px;
        width: 100%;
        height: 100%;
        overflow: hidden;
        display: block;
        margin: 0 auto;
    }

    .imgContianer i {
        position: relative;
        width: 10px;
        height: 10px;
        float: left;
        border-radius: 250px;
        background: #FFDD00;
    }

    /deep/ .modal-dialog {
        height: 80px;
        margin-top: 20px;
    }

    /deep/ textarea {
        color: #6DC1FF;
    }

    /deep/ .el-table__empty-text {
        color: #015B9E;
    }

    /deep/ .el-input.is-disabled .el-input__inner {
        background-color: #015B9E;
    }

    .red {
        color: red;
    }

    .yellow {
        color: #fd0;
    }
    /deep/ .el-table__expand-icon {
        color: #fff;
    }
</style>
