<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">
                    <el-row :gutter="20">
                        <el-col :span="6">
                            <em>登记时间:</em>
                            <el-date-picker
                                    v-model="panel.time1"
                                    type="daterange"
                                    range-separator="至"
                                    start-placeholder="开始日期"
                                    end-placeholder="结束日期">
                            </el-date-picker>
                        </el-col>
                        <el-col :span="4">
                            <em>时限类型:</em>
                            <el-select v-model="panel.timeLimit">
                                <el-option
                                        v-for="item in panel.options"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value">
                                </el-option>
                            </el-select>
                        </el-col>
                        <el-col :span="4">
                            <em>关键词:</em>
                            <el-input v-model="panel.qrcodename" placeholder="请输入关键词"></el-input>
                        </el-col>
                        <el-col :span="4">
                            <el-button size="small" type="primary" @click="query">查询</el-button>
                        </el-col>
                    </el-row>
                </div>
            </div>
        </div>
        <div class="contorl">
            <el-button size="small" type="primary" @click="addList">添加</el-button>
            <el-button size="small" type="primary" @click="changeList">修改</el-button>
            <el-button size="small" type="primary" @click="delList">删除</el-button>
        </div>
        <el-table
                :data="tableData"
                class=""
                stripe
                is-horizontal-resize
                v-loading="loading"
                element-loading-background="rgba(0, 0, 0, 0.8)"
                @selection-change="handleSelectionChange"
        >
            <el-table-column
                    type="selection"
                    width="55">
            </el-table-column>
            <el-table-column
                    prop="QrId"
                    label="二维码编号"
            >
            </el-table-column>
            <el-table-column
                    prop="CreateTime"
                    label="创建时间"
                    width="180">
                <template slot-scope="scope">
                    {{scope.row.CreateTime |fmtDate}}
                </template>
            </el-table-column>
            <el-table-column
                    prop="Frequency"
                    label="有效时长（分钟）"
            >
            </el-table-column>
            <el-table-column
                    prop="DetIdStr"
                    label="探测器"
                    width="180">
                <!--探测器详细信息 todo-->
            </el-table-column>
            <el-table-column
                    prop="QrName"
                    label="二维码名字">
            </el-table-column>
            <el-table-column
                    prop="Tel"
                    label="联系电话">
            </el-table-column>
            <el-table-column
                    prop="Memo"
                    label="备注">
            </el-table-column>
            <el-table-column
                    prop="QrId"
                    label="操作">
                <template slot-scope="scope">
                    <el-button class="control_btn" type="text" @click="goPoster(scope.row)">海报</el-button>
                    <el-button class="control_btn" type="text" @click="goQrcode(scope.row)">二维码</el-button>
                    <el-button class="control_btn red" type="text" @click="pauseQrcode(scope.row)">禁用</el-button>
                </template>
            </el-table-column>
        </el-table>
        <br>
        <el-pagination
                background
                :total="pageination.total"
                :page-size="pageination.pageItem"
                @current-change="pageChange"
        ></el-pagination>

        <dialog_referrer_list
                :show="dialog_state"
                :title="dialog_title"
                :large="true"
                @dialog_cancel="dialog_cancel"
                @dialog_ok="dialog_ok"
        >
            <div class="dialogContent">
                <el-row :gutter="20">
                    <el-col :span="10">
                        <label>
                            二维码名称 *
                        </label>
                        <el-input v-model="dialog.comname"></el-input>
                    </el-col>
                    <el-col :span="10">
                        <label>
                            电话 *
                        </label>
                        <el-input v-model="dialog.tel"></el-input>
                    </el-col>
                    <el-col :span="10">
                        <label>
                            房间号 *
                        </label>
                        <el-input v-model="dialog.qrname"></el-input>
                    </el-col>
                    <el-col :span="10">
                        <label>
                            备注
                        </label>
                        <el-input v-model="dialog.memo"></el-input>
                    </el-col>
                    <el-col :span="10">
                        <label>
                            房间所属探测器
                        </label>
                        <!--改成list todo -->
                        <el-checkbox-group v-model="dialog.checkList">
                            <el-checkbox :label="det.Id" v-for="det in dialog.detOptions">{{det.Name}}</el-checkbox>
                        </el-checkbox-group>
                    </el-col>
                    <el-col :span="10">
                        <label>
                            海报有效期 *
                        </label>
                        <el-radio v-model="dialog.timeType" label="1">无限期</el-radio>
                        <el-radio v-model="dialog.timeType" label="2">有时限</el-radio>

                    </el-col>
                    <el-col :span="10" v-if="dialog.timeType == 2">
                        <label>
                            有效期时长
                        </label>
                        <el-input class="short" v-model="dialog.frequency"></el-input>
                        <el-select class="short shortRight" v-model="dialog.validType" placeholder="时间单位">
                            <el-option
                                    v-for="item in dialog.timeOptions"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                            </el-option>
                        </el-select>
                    </el-col>
                    <el-col :span="10">
                        <label>
                            单位形象图
                        </label>
                        <el-upload
                                action="/api/v1/Detector/QrCodeUpload"
                                ref="upload"
                                list-type="picture-card"
                                :data="dialog"
                                :on-success="handleImgSuccess"
                                :before-upload="handleImgbefore"
                                :auto-upload="true">
                            <i slot="default" class="el-icon-plus"></i>
                            <div slot="file" slot-scope="{file}">
                                <img
                                        class="el-upload-list__item-thumbnail"
                                        :src="file.url" alt=""
                                >
                                <span class="el-upload-list__item-actions">
        <span
                class="el-upload-list__item-preview"
                @click="handlePictureCardPreview(file)"
        >
          <i class="el-icon-zoom-in"></i>
        </span>
        <span
                v-if="!disabled"
                class="el-upload-list__item-delete"
                @click="handleDownload(file)"
        >
          <i class="el-icon-download"></i>
        </span>
      </span>
                            </div>
                        </el-upload>
                        <img
                                v-if="dialog.imgSrc"
                                class="editImg"
                                :src="dialog.imgSrc" alt=""
                        >
                        <el-dialog :visible.sync="dialogVisible">
                            <img width="100%" :src="dialogImageUrl" alt="">
                        </el-dialog>
                    </el-col>
                </el-row>
            </div>
        </dialog_referrer_list>
    </div>
</template>

<script>
    import Global from '../Global.js'
    import dialog_referrer_list from '../components/dialog_referrer_list'
    import {
        GetRegionAndDectorSelect,
        GetQrcodeList,
        QrCodeAdd,
        QrCodeEdit,
        QrcodeEditStatus,
    } from '../api/getApiRes.js'

    let qs = require('qs');
    export default {
        data() {
            return {
                // dialog
                dialog_state: false,
                dialog_title: '添加二维码',
                dialog_type: '',//类型，1是添加，2是修改
                tabIndex: 0,
                tabs: [
                    {name: '二维码管理', url: 'qrcodemanage'},
                ],
                // panel 配置项目
                panel: {
                    qrcodename: '',
                    timeLimit: 0,
                    options: [
                        {value: 0, label: '全部'},
                        {value: 1, label: '无期限'},
                        {value: 2, label: '有时限'},
                    ],
                    time1: globalBt2(),
                },
                dialog: {
                    shopID: 1,//One and always is one
                    comID: 1,//One and always is one
                    qrcodeid: 0,//One and always is one
                    token: localStorage.token,
                    comname: '',
                    tel: '',
                    qrname: '',
                    detId: '',
                    detidstr: '',
                    frequency: '',
                    timeType: '1',
                    memo: '',
                    imagekey: '',
                    imgSrc: '',
                    validType: 0,
                    detOptions: [],
                    checkList: [],
                    timeOptions: [
                        {value: 0, label: '分钟'},
                        {value: 1, label: '小时'},
                        {value: 2, label: '天'},
                        {value: 3, label: '月（30天）'},
                        {value: 4, label: '年'},
                    ],
                },
                pageination: {
                    pageItem: 10,
                    pageoptions: pageOptions(),
                    total: 300,
                    pageIndex: 1,
                },
                draw: 1,
                start: 0,
                recordsTotal: 0,
                tableData: [],
                allTableData: [],
                limit: '10',
                multipleSort: false,
                loading: true,
                fileList: [],
                dialogVisible: false,
                disabled: false,
                plateTitle: '',
                plateImg: false,
                loftListState: false,
                multipleSelection: [],
                detectedmac: '',
                plateImgSrc: '',
                dialogImageUrl: '',
            }
        },
        mounted() {
            this.getTableQuery();
            this.getDetList();
        },
        methods: {
            // 跳转tab页面
            goTab(url) {
                this.$router.push({path: url});
            },
            // 查询按钮
            query() {
                this.getTableQuery();
                this.$message.success('查询完毕');
            },
            handleImgbefore(file) {
                this.dialog.image = file;
                this.dialog.imgSrc = '';
            },
            handleImgSuccess(res, file) {
                let that = this;
                if (res.Code == 0) {
                    that.dialog.imagekey = res.Key
                } else {
                    that.$message.error(res.Memo);
                }
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
                console.log(val);
            },
            // 获取探测器列表
            getDetList() {
                let param = {
                    'token': localStorage.token,
                };
                let postdata = qs.stringify(param);
                GetRegionAndDectorSelect(postdata).then(res => {
                    let json = res;
                    if (json.Code == 0) {
                        this.dialog.detOptions = json.DectectorRs;
                    }
                })
            },
            // 页面数据查询
            getTableQuery() {
                let that = this;
                that.loading = true;
                let param = {
                    token: localStorage.token,
                    comid: 0,
                    qrcodename: that.panel.qrcodename,
                    timeLimit: that.panel.timeLimit,
                    cdtbt: globaltime2String(that.panel.time1[0]) + ' 00:00:01',//开始时间
                    cdtet: globaltime2String(that.panel.time1[1]) + ' 23:59:59',//结束时间
                    start: 1,//
                    tableMax: 300,//
                };
                let postdata = qs.stringify(param);
                GetQrcodeList(postdata).then(res => {
                    let json = res;
                    that.loading = false;
                    if (json.Code == 0) {
                        if (json.Rs) {
                            that.allTableData = json.Rs;
                            that.recordsTotal = json.Rs.length;
                        } else {
                            that.allTableData = [];
                            that.recordsTotal = 0;
                        }

                        // 设置分页数据
                        that.setPaginations();
                    } else {
                        that.$message.error(json.Memo);
                    }
                })
            },
            // 设置分页数据
            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) {
                let that = this;
                return globalfmtDate(column, 11);
            },
            addList() {
                this.dialog_state = true;
                this.dialog_title = '添加二维码';
                this.dialog_type = 1;
                // clear
                this.dialog.detId = '';
                this.dialog.timeType = '1';
                this.dialog.memo = '';
                this.dialog.checkList = [];
            },
            delList() {
                let that = this;
                // checkNum
                if (!this.multipleSelection.length) {
                    that.$message({
                        showClose: true,
                        message: '错了哦，需要先选中至少一条记录',
                        type: 'error'
                    });
                    return false
                }
                let qrcodeid = that.multipleSelection[0].QrId;

                let param = {
                    token: localStorage.token,
                    qrcodeid: qrcodeid,
                    status: 9,//0禁用1启用9删除
                };
                let postdata = qs.stringify(param);

                this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    QrcodeEditStatus(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);
                        }
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            changeList() {
                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
                }
                this.dialog_state = true;
                this.dialog_title = '修改二维码';
                that.dialog_type = 2;
                let row = this.multipleSelection[0];
                this.dialog.comname = row.ComName;
                this.dialog.qrcodeid = row.QrId;
                this.dialog.tel = row.Tel;
                this.dialog.qrname = row.QrName;
                this.dialog.memo = row.Memo;
                this.dialog.checkList = row.DetIdStr.split(',').map(Number);
                // 为0时候表示无限期
                // 获取时限类型
                let timeType = parseInt(row.Frequency);
                if (timeType == 0) {
                    that.dialog.timeType = "1";
                } else {
                    that.dialog.timeType = "2";
                }
            },
            // 探测记录
            goRecord(row) {
                console.log(row);
                this.$router.push({path: '/record', query: {row: row}});
            },
            dialog_cancel() {
                let that = this;
                that.dialog_state = false;
            },
            dialog_ok() {
                console.log(this.dialog_type);
                if (this.dialog_type == 1) {
                    this.confirmAddQrcode();
                } else {
                    this.confirmEditQrcode();
                }
            },
            // 确认添加新的二维码
            confirmAddQrcode() {
                // checkVal
                let that = this;
                // checkVal
                if (!that.dialog.comname) {
                    this.$message.error('错了哦，区域名称不能空');
                    return false
                }
                if (that.dialog.comname.length > 20) {
                    this.$message.error('错了哦，区域名称不能超过20个字符');
                    return false
                }
                if (!that.dialog.qrname) {
                    this.$message.error('错了哦，二维码名称不能空');
                    return false
                }
                if (that.dialog.qrname.length > 20) {
                    this.$message.error('错了哦，二维码名称不能超过20个字符');
                    return false
                }
                if (!that.dialog.tel) {
                    this.$message.error('错了哦，电话名称不能空');
                    return false
                }

                let detidstr = that.dialog.checkList;
                if (!detidstr) {
                    this.$message.error('错了哦，至少勾选一个探测器');
                    return false
                }
                let extime = 0;
                if (that.dialog.timeType == 0) {
                    extime = 0;//无限时
                } else {
                    switch (parseInt(that.dialog.validType)) {
                        case 0://分钟
                            extime = that.dialog.frequency * 1;
                            break;
                        case 1://小时
                            extime = that.dialog.frequency * 60;
                            break;
                        case 2://天
                            extime = that.dialog.frequency * 60 * 24;
                            break;
                        case 3://月
                            extime = that.dialog.frequency * 60 * 24 * 30;
                            break;
                        case 4://年
                            extime = that.dialog.frequency * 60 * 24 * 30 * 12;
                            break;
                    }
                }

                let param = {
                    token: localStorage.token,
                    comname: that.dialog.comname,
                    comid: 1,
                    qrname: that.dialog.qrname,
                    tel: that.dialog.tel,
                    memo: that.dialog.memo,
                    detidstr: detidstr.join(',') + ',',
                    frequency: extime,
                    imagekey: that.dialog.imagekey,
                };
                let postdata = qs.stringify(param);
                QrCodeAdd(postdata).then(res => {
                    let json = res;
                    if (json.Code == 0) {
                        that.$message({
                            showClose: true,
                            message: '创建成功,前往二维码页面进行查看！',
                            type: 'success'
                        });

                        // 二维码页面 页面跳转
                        that.$router.push({
                            path: '/createmeetingqrcode',
                            query: {
                                shopname: that.dialog.comname,
                                qrname: that.dialog.qrname,
                                qrcodeId: json.Id,
                            }
                        });

                        // 重载列表
                        that.getTableQuery()

                    } else {
                        that.$message.error(json.Memo);
                    }
                });

                that.dialog_state = false;

            },
            // 确认修改旧的二维码
            confirmEditQrcode() {
                // checkVal
                let that = this;
                // checkVal
                if (!that.dialog.comname) {
                    this.$message.error('错了哦，区域名称不能空');
                    return false
                }
                if (that.dialog.comname.length > 20) {
                    this.$message.error('错了哦，区域名称不能超过20个字符');
                    return false
                }
                if (!that.dialog.qrname) {
                    this.$message.error('错了哦，二维码名称不能空');
                    return false
                }
                if (that.dialog.qrname.length > 20) {
                    this.$message.error('错了哦，二维码名称不能超过20个字符');
                    return false
                }
                if (!that.dialog.tel) {
                    this.$message.error('错了哦，电话名称不能空');
                    return false
                }

                let detidstr = that.dialog.checkList;
                if (!detidstr) {
                    this.$message.error('错了哦，至少勾选一个探测器');
                    return false
                }
                let extime = 0;
                if (that.dialog.timeType == 0) {
                    extime = 0;//无限时
                } else {
                    switch (parseInt(that.dialog.validType)) {
                        case 0://分钟
                            extime = that.dialog.frequency * 1;
                            break;
                        case 1://小时
                            extime = that.dialog.frequency * 60;
                            break;
                        case 2://天
                            extime = that.dialog.frequency * 60 * 24;
                            break;
                        case 3://月
                            extime = that.dialog.frequency * 60 * 24 * 30;
                            break;
                        case 4://年
                            extime = that.dialog.frequency * 60 * 24 * 30 * 12;
                            break;
                    }
                }

                let param = {
                    token: localStorage.token,
                    comname: that.dialog.comname,
                    comid: 1,
                    qrname: that.dialog.qrname,
                    tel: that.dialog.tel,
                    memo: that.dialog.memo,
                    detidstr: detidstr.join(',') + ',',
                    frequency: extime,
                    imagekey: that.dialog.imagekey,
                    qrcodeid: that.dialog.qrcodeid,
                };
                let postdata = qs.stringify(param);
                QrCodeEdit(postdata).then(res => {
                    let json = res;
                    if (json.Code == 0) {
                        that.$message({
                            showClose: true,
                            message: '创建成功,前往二维码页面进行查看！',
                            type: 'success'
                        });

                        // 二维码页面 页面跳转
                        that.$router.push({
                            path: '/createmeetingqrcode',
                            query: {
                                shopname: that.dialog.comname,
                                qrname: that.dialog.qrname,
                                qrcodeId: json.Id,
                            }
                        });

                        // 重载列表
                        that.getTableQuery()

                    } else {
                        that.$message.error(json.Memo);
                    }
                });

                that.dialog_state = false;

            },
            // 禁用二维码
            pauseQrcode(row) {
                let that = this;
                let param = {
                    token: localStorage.token,
                    qrcodeid: row.QrId,
                    status: 0//新状态0禁用1启用 9删除
                };
                let postdata = qs.stringify(param);
                this.$confirm('是否禁用' + row.QrName + '的二维码？', '禁用操作', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // // ajax todo
                    // RegionStatusEdit(postdata).then(res => {
                    //     let json = res;
                    //     if (json.Code == 0) {
                    that.$message({
                        type: 'success',
                        message: `禁用成功`
                    });
                    that.getTableQuery();
                    // } else {
                    //     that.$message.error(json.Memo);
                    // }
                    // })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消禁用'
                    });
                });
            },
            // 查看海报
            goPoster(node) {
                this.$router.push({
                    path: '/poster',
                    query: {
                        shopname: 1,
                        ComName: node.ComName,
                        qrname: node.QrName,
                        qrcodeId: node.QrId,
                        vfcode: node.Vfcode,
                    }
                })
            },
            // 查看二维码
            goQrcode(node) {
                this.$router.push({
                    path: '/createmeetingqrcode',
                    query: {
                        shopname: 1,
                        ComName: node.ComName,
                        qrname: node.QrName,
                        qrcodeId: node.QrId,
                        vfcode: node.Vfcode,
                    }
                })
            },
        },
        filters: {
            fmtDate: function (value) {
                let res = '';
                if (!value) {
                    return '---';
                } else {
                    res = new Date(+new Date(value) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '');
                    return res;
                }
            }
        }
        ,
        components: {
            dialog_referrer_list
        }
    }
</script>

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

    .tabs ul {
        width: 168px;
    }

    table span {
        cursor: pointer;
    }

    .control_btn {
        float: left;
        margin: 0 4px;
    }

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

    .modal-content .el-select {
        display: block;
    }

    /deep/ .modal-content .el-select .el-input .el-select__caret {
        position: relative;
        top: 10px;
        line-height: 0px !important;
    }

    /deep/ .el-radio {
        width: 45%;
        height: 35px;
        float: left;
        padding-top: 10px;
    }

    /deep/ .el-radio__input {
        float: left;
    }

    /deep/ .el-radio__inner {
        float: left;
    }

    /deep/ .el-radio__label {
        float: left;
    }

    .short {
        width: 40%;
        float: left;
        margin-right: 10px;
    }

    .red {
        color: red !important;
    }

    /deep/ .modal-body {
        width: 100%;
        height: 400px;
        overflow: hidden;
        display: block;
        margin: 0 auto;
        margin-bottom: 40px;
    }

    /*upload*/
    /deep/ .el-upload--picture-card {
        float: left;
        background: none;
        border: 1px solid #005EA2;
        color: #005EA2;
    }

    /deep/ .el-upload--picture-card i {
        color: #005EA2;
    }

    .editImg {
        width: 140px;
        height: 140px;
        float: left;
        margin-left: 30px;
    }

</style>
