
<template>
    <div class="CameraManagement">
        <el-row :gutter="20">
            <!-- <el-col :span="2">
                <span style="line-height:32px;">工具栏:</span>
            </el-col>
            <el-col :span="12">
                <el-input
                    placeholder="请输入内容"
                    v-model="searchParams"
                    class="input-with-select"
                    @keyup.enter.native="getDeviceList"
                >
                    <el-button slot="append" icon="el-icon-search" @click="getDeviceList"></el-button>
                </el-input>
            </el-col>-->
            <el-col :span="8">
                <el-button @click="add" type="primary" icon="el-icon-document-add">新建</el-button>
            </el-col>
        </el-row>
        <hr style="border-top: 2px solid #eee;margin: 10px 0;" />
        <el-row>
            <el-table :data="deviceList">
                <el-table-column prop="id" label="序号" width="120px"></el-table-column>
                <el-table-column prop="name" label="名称"></el-table-column>
                <el-table-column prop="deviceNo" label="设备序列号"></el-table-column>
                <el-table-column prop="status" label="摄像头状态"></el-table-column>
                <el-table-column prop="description" label="描述"></el-table-column>
                <el-table-column label="最后一次">
                    <template slot-scope="scope">
                        <span>{{ new Date(scope.row.updated).toLocaleDateString() }}</span>
                    </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="200">
                    <template slot-scope="scope">
                        <el-button
                            @click="handlePlay(scope.row)"
                            type="text"
                            v-if="isCamera(scope.row.categoryId)"
                        >播放</el-button>
                        <el-button @click="edit(scope.row)" type="text" size="small">编辑</el-button>
                        <el-popconfirm title="是否删除此设备的信息？" @onConfirm="del(scope.row)">
                            <el-button slot="reference" type="text" size="small">删除</el-button>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
        </el-row>

        <!-- 设备信息新建、编辑 -->
        <el-dialog :title="isAdd?'新建设备信息':'编辑设备信息'" :visible.sync="isShowDialog" append-to-body>
            <el-form :model="formData" ref="cameraForm" :rules="rules" label-width="100px">
                <el-form-item label="名称：" prop="name">
                    <el-input v-model="formData.name" placeholder="请输入名称"></el-input>
                </el-form-item>

                <el-form-item label="摄像头类型：">
                    <el-cascader
                        :options="cameraInfoTree"
                        :props="{ checkStrictly: true, children: 'childs', label: 'nodeName' ,value:'id'}"
                        v-model="formData.categoryId"
                        clearable
                    >
                        <template slot-scope="{ node, data }">
                            <span>{{ data.nodeName }}</span>
                            <span v-if="!node.isLeaf">({{ data.childs.length }})</span>
                        </template>
                    </el-cascader>
                </el-form-item>

                <el-form-item label="设备序列号：" prop="deviceNo">
                    <el-input v-model="formData.deviceNo" placeholder="设备序列号"></el-input>
                </el-form-item>

                <el-form-item label="配置信息：">
                    <el-row
                        type="flex"
                        justify="space-between"
                        :gutter="20"
                        style="margin-bottom:10px"
                        v-for="(item,index) in meta"
                        :key="index"
                    >
                        <el-col :span="3" style="text-align:right">rtsp：</el-col>
                        <el-col :span="7">
                            <el-input placeholder="请输入内容" v-model="item.rtsp"></el-input>
                        </el-col>
                        <el-col :span="3" style="text-align:right">ws：</el-col>
                        <el-col :span="7">
                            <el-input placeholder="请输入内容" v-model="item.ws"></el-input>
                        </el-col>
                        <el-col :span="4">
                            <el-button
                                v-show="index==meta.length-1"
                                @click="plus"
                                type="primary"
                                icon="el-icon-plus"
                                circle
                            ></el-button>
                            <el-button
                                v-show="index==meta.length-1&meta.length>1"
                                @click="minus"
                                type="primary"
                                icon="el-icon-minus"
                                circle
                            ></el-button>
                        </el-col>
                    </el-row>
                </el-form-item>

                <el-form-item label="状态：">
                    <el-select v-model="formData.status" placeholder="请选择">
                        <el-option label="链接中" :value="0"></el-option>
                        <el-option label="链接中" :value="1"></el-option>
                        <el-option label="链接中" :value="2"></el-option>
                        <el-option label="链接中" :value="3"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="描述：">
                    <el-input
                        type="textarea"
                        :rows="2"
                        v-model="formData.description"
                        placeholder="输入描述"
                    ></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer">
                <el-button @click="isShowDialog=false">取 消</el-button>
                <el-button type="primary" @click="submitForm('cameraForm')">保 存</el-button>
            </div>
        </el-dialog>
        <!-- 摄像头播放 -->
        <el-dialog :title="videoData.title" @close="handleStop" :visible.sync="isShowVideo">
            <rtsp-player ref="rtspPlayer" :rtspData="videoData"></rtsp-player>
        </el-dialog>
    </div>
</template>

<script>
import { mapActions } from "vuex";
import rtspPlayer from "../common/rtsp-player/index";

// 表单验证规则
const rules = {
    name: [{ required: true, message: "请输入摄像头名称", trigger: "blur" }],
    deviceNo: [{ required: true, message: "请输入设备序列号", trigger: "blur" }]
};

export default {
    name: "CameraManagement",
    components: { rtspPlayer },
    data() {
        return {
            id: "",
            cameraInfoTree: [],
            deviceList: [],
            isShowDialog: false,
            formData: {
                name: "",
                categoryId: [],
                deviceNo: "",
                status: "",
                description: ""
            },
            meta: [{ rtsp: "", ws: "" }],
            isShowVideo: false,
            videoData: {
                title: null,
                rtsp: null,
                ws: null
            },
            configItems: 2, // 配置项的通道配置项数
            isAdd: true,
            rules
        };
    },
    created() {
        // 获取摄像头 树
        this.getTreeByCode("ip-cam");
    },
    methods: {
        ...mapActions(["fetch"]),
        submitForm(formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    this.save();
                } else {
                    return false;
                }
            });
        },
        // 通过code获取树
        getTreeByCode(code) {
            this.fetch({
                api: "/publics/treenode/getTreeByCode",
                method: "POST",
                data: { code }, //目前只有一个组织,其他参数调整钟
                success: res => {
                    this.id = res.id;
                    this.getDeviceList(res.id);
                    this.getCameraList(res.id);
                },
                fail: err => {
                    console.log(err);
                    if (err.errCode == "request_not_authorize") {
                        this.$message({
                            message: "请重新登录",
                            type: "warning"
                        });
                    }
                }
            });
        },
        getDeviceList(categoryId) {
            this.fetch({
                api: "/device/device/list",
                method: "POST",
                data: { categoryId }, //目前只有一个组织,其他参数调整钟 732971735112749056
                success: res => {
                    this.deviceList = res.content;
                },
                fail: err => {
                    if (err.errCode == "request_not_authorize") {
                        this.$message({
                            message: "请重新登录",
                            type: "warning"
                        });
                    }
                    console.log(err);
                }
            });
        },

        // 请求 拿到摄像头列表
        getCameraList(parentId) {
            this.fetch({
                api: "/publics/treenode/listNodeByParent",
                method: "POST",
                data: {
                    parentId,
                    hasSub: true
                },
                success: res => {
                    this.cameraInfoTree = res;
                },
                fail: err => {
                    if (err.errMsg) this.$message.error(err.errMsg);
                    else this.$message.error("服务器发生异常");
                }
            });
        },
        // 编辑的保存按钮
        save() {
            this.formData.meta = { channel: JSON.stringify(this.meta) };
            let categoryId = this.formData.categoryId;
            if (categoryId instanceof Array) {
                this.formData.categoryId = categoryId[categoryId.length - 1];
            }
            let api = this.isAdd
                ? "/device/device/add"
                : "/device/device/update";
            this.fetch({
                api,
                data: this.formData,
                success: res => {
                    this.getDeviceList(this.id); //重新加载
                    // this.isShowDialog = false;
                    this.$message.success(
                        this.isAdd
                            ? "添加摄像头数据成功！"
                            : "修改摄像头数据成功！"
                    );
                },
                fail: err => {
                    console.log(err);
                    if (err.errMsg) this.$message.error(err.errMsg);
                    else this.$message.error("服务器发生异常");
                }
            });
        },
        // 请求删除
        reqDelete(id) {
            this.fetch({
                api: "/device/delete",
                data: { id },
                success: res => {
                    this.getDeviceList(this.id); //重新加载
                },
                fail: err => {
                    console.log(err);
                    if (err.errMsg) this.$message.error(err.errMsg);
                    else this.$message.error("服务器发生异常");
                }
            });
        },
        add() {
            this.isAdd = true;
            // this.formData = {
            //     name: "",
            //     categoryId: "",
            //     deviceNo: "",
            //     status: "",
            //     sVer: "",
            //     hVer: "",
            //     description: ""
            // };
            // this.meta = [{ rtsp: "", ws: "" }]
            if (this.formData.id) delete this.formData.id;
            this.isShowDialog = true;
        },
        isCamera(hid) {
            return true;
        },
        // 播放
        handlePlay(row) {
            console.log(row);
            if (row.meta.channel && row.meta.channel.length > 0) {
                let channals = JSON.parse(row.meta.channel);
                let rtsp = channals[0].rtsp;
                let ws = channals[0].ws;
                console.log("rtsp==>>  " + rtsp);
                console.log("ws==>>  " + ws);
                if(row.data && row.data["curr-ip"]){//要更换IP
                    ws = ws.replace("ip-addr",row.data["curr-ip"])
                }
                this.videoData = {
                    rtsp,
                    ws,
                    title: row.name
                };
                this.isShowVideo = true;
            } else this.$message.info("配置信息不正确");
        },
        handleStop(done) {
            console.log(this.$refs.rtspPlayer)
            // if (this.$refs.rtspPlayer) this.$refs.rtspPlayer.close();
        },
        // 编辑
        edit(row) {
            console.log(row);
            this.isAdd = false;
            this.isShowDialog = true;
            this.formData = row;
            this.meta = JSON.parse(row.meta.channel);
            // this.createArr(row.categoryId);
        },
        // 删除
        del(row) {
            console.log(row);
            this.reqDelete(row.id);
        },

        // 配置项增加
        plus() {
            this.meta.push({ rtsp: "", ws: "" });
        },
        // 配置项减少
        minus() {
            if (this.meta.length <= 1) return;
            this.meta.splice(this.meta.length - 1, 1);
        },
        show() {
            this.deviceList.forEach;
        }
        // 传入一个id 生成树（ cameraInfoTree ）的id数组  "732971850158313472"  "732997784550772736"
        /* createArr(id) {
            let tmpArr = [id]
            let tree = this.cameraInfoTree;
            aa(id)
            console.log(tmpArr);
            function aa(id) {
                recursion(tree);
                function recursion(tree) {
                    tree.forEach(item => {
                        if (item.id == id) {
                            let rse = isWarp(item.parentId)
                            console.log(rse)
                            if(rse == 0) {
                                tmpArr.unshift(item.parentId)
                            } else if(rse == 1) {
                                tmpArr.unshift(item.parentId)
                                aa(item.parentId)
                            } 
                            return;
                        } else {
                            if (item.childs && item.childs.length > 0) {
                                // debugger
                                return recursion(item.childs);
                            } else {
                                // tmpArr = []
                                return;
                            }
                        }
                    });
                }
            }
            
            // 判断是否到最外层
            function isWarp(parentId) {
                let res = null
                 tree.forEach(item => {
                    if(item.id == parentId){
                        res = 0 // 刚好到
                    } else if(item.parentId == parentId){
                        res = -1 // 已经到外面一层了
                    } else {
                        res = 1 // 还在内层
                    }
                })
                return res
            }
        } */
    }
};
</script>

<style lang="scss" scoped>
.CameraManagement {
    .dialog {
        .item_row {
            display: flex;
        }
    }
}
</style>