<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="88px"
    >
      <el-form-item label="监控名称" prop="monitorName">
        <el-input
          v-model="queryParams.monitorName"
          placeholder="请输入监控名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="区域" prop="regionId">
        <el-select
          v-model="queryParams.regionId"
          filterable
          placeholder="请选择区域"
        >
          <el-option
            v-for="item in regionOptions"
            :key="item.id"
            :label="item.regionName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['app:monitor:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-refresh"
          size="mini"
          @click="handleSync"
          v-hasPermi="['app:monitor:sync']"
          >同步</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['app:monitor:remove']"
          >删除</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="monitorList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="ID" align="center" prop="id" width="80" /> -->
      <el-table-column label="监控名称" align="center" prop="monitorName" />
      <el-table-column label="区域名称" align="center" prop="region.regionName" />
      <el-table-column label="设备品牌" align="center" prop="monitorBrand" />
      <el-table-column label="IP" align="center" prop="ipAddr" />
      <el-table-column
        label="操作"
        align="center"
        width="240"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-video-camera"
            @click="handleOpenVideo(scope.row)"
            >实时监控</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['app:monitor:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['app:monitor:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!--视频播放-->
    <el-dialog title="实时监控" :visible.sync="videoOpen" width="700px" append-to-body @close="handleCloseVideo">
      <LivePlayer :videoUrl="videoUrl" fluent autoplay live stretch></LivePlayer>
    </el-dialog>
    <!-- 添加或修改监控设备对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" :disabled="isView" label-width="80px">
        <el-form-item label="监控名称" prop="monitorName">
          <el-input v-model="form.monitorName" placeholder="请输入监控名称" />
        </el-form-item>
        <el-form-item label="区域名称" prop="regionId">
          <el-select
          v-model="form.regionId"
          filterable
          placeholder="请选择区域"
        >
          <el-option
            v-for="item in regionOptions"
            :key="item.id"
            :label="item.regionName"
            :value="item.id"
          ></el-option>
        </el-select>
        </el-form-item>
        <el-form-item label="设备品牌" prop="monitorBrand">
          <el-input v-model="form.monitorBrand" placeholder="请输入设备品牌" />
        </el-form-item>
        <el-form-item label="IP" prop="ipAddr">
          <el-input v-model="form.ipAddr" placeholder="请输入IP" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="!isView">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listMonitor,
  getMonitor,
  delMonitor,
  syncMonitor,
  addMonitor,
  updateMonitor,
  playStart,
  playStop
} from "@/api/app/monitor";
import LivePlayer from '@liveqing/liveplayer'
import { getAllRegion } from "@/api/app/region";
export default {
  name: "Monitor",
  components: {
    LivePlayer
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 监控设备表格数据
      monitorList: [],
      regionOptions: [],
      // 弹出层标题
      title: "",
      isView:false,
      // 是否显示弹出层
      open: false,
      videoOpen:false,
      videoUrl:"",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        monitorName: null,
        regionId: null,
      },
      deviceId:null,
      channelId:null,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        monitorName: [
          { required: true, message: "监控名称不能为空", trigger: "blur" },
          {
            min: 1,
            max: 10,
            message: "监控名称输入超出最大长度限制（10位）",
            trigger: "blur",
          },
        ],
        regionId: [
          { required: true, message: "区域不能为空", trigger: "change" }
        ],
        monitorBrand: [
          {
            min: 0,
            max: 10,
            message: "设备名称输入超出最大长度限制（10位）",
            trigger: "blur",
          },
        ],
        ipAddr: [
          { required: true, message: "IP地址不能为空", trigger: "blur" },
          {
              pattern: /^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
              message: 'IPv4地址格式输入错误',
              trigger: 'blur'
          },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getRegion();
  },
  methods: {
    /** 查询监控设备列表 */
    getList() {
      this.loading = true;
      listMonitor(this.queryParams).then((response) => {
        this.monitorList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getRegion() {
      getAllRegion().then((response) => {
        this.regionOptions = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        monitorName: null,
        regionId: null,
        monitorBrand: null,
        ipAddr: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 同步按钮操作 */
    handleSync() {
      this.loading = true;
      syncMonitor().then((response) => {
        this.loading = false;
        this.$modal.msgSuccess("同步成功");
        this.getList();
      }).catch((e)=>{
        this.loading = false;
        this.$modal.msgError("同步失败");
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.isView = false;
      this.title = "添加监控设备";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getMonitor(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.isView = false;
        this.title = "修改监控设备";
      });
    },

    /** 查看按钮操作 */
    handleView(row) {
      this.reset();
      const id = row.id || this.ids;
      getMonitor(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.isView = true;
        this.title = "查看监控设备";
      });
    },
    //打开监控
    handleOpenVideo(row) {
      this.videoOpen = true;
      this.deviceId = row.deviceId;
      this.channelId = row.channelId;
      playStart({deviceId:row.deviceId,channelId:row.channelId}).then((response) => {
          //console.log(response)
          if(response.data){
            this.videoUrl = response.data.https_flv;
            //4432是 视频流的实际端口，需要把它替换成https的4431，然后通过nginx代理到4432
            this.videoUrl = this.videoUrl.replace(":4432",":4431")
          }

      });
    },
    handleCloseVideo(){
      this.videoUrl ="";
      playStop({deviceId:this.deviceId,channelId:this.channelId}).then((response) => {
          console.log(response)
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateMonitor(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMonitor(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除监控设备编号为"' + ids + '"的数据项？')
        .then(function () {
          return delMonitor(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "app/monitor/export",
        {
          ...this.queryParams,
        },
        `monitor_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
