<script>
import axios from "axios";
import { inject } from "vue";
import { getDeviceListService } from "@/api/device.js";
import { restartDeviceService } from "@/api/device.js";
import { addDeviceService } from "@/api/device.js";
import { deleteDeviceService } from "@/api/device.js";
import { updateDeviceService } from "@/api/device.js";
import router from "@/router/index.js";
import { ElMessage } from 'element-plus';  
import Menu from "@/views/Menu.vue";
import VideoStream from "@/views/DeviceRealVP.vue";

export default {
  components: {
    VideoStream,
  },
  data() {
    return {
      ip: "",
      tableData: [],
      tokenData: {
        token: localStorage.getItem("token"),
        ip: localStorage.getItem("ip"),
        userId: localStorage.getItem("userId"),
        username: localStorage.getItem("username"),
      },
      addDialogVisible: false,
      updateDialogVisible: false,
      deviceStreamDialogVisible: false,
      playing_device: "",
      searchForm: {
        hour: 0,
        entrydate: [],
      },
      addForm: {
        device_name: "",
        device_ip: "",
        device_status: "",
        device_info: "",
        device_location: "",
        device_type: "",
        auth_id: -1,
        token: localStorage.getItem("token"),
      },
      updateForm: {
        id:0,
        device_name: "",
        device_ip: "",
        device_status: "",
        device_info: "",
        device_location: "",
        device_type: "",
        auth_id: -1,
        token: localStorage.getItem("token"),
      },
    };
  },

  // methods 是一些用来更改状态与触发更新的函数
  // 它们可以在模板中作为事件处理器绑定
  methods: {
    async getDeviceList() {
      let result = {};
      try {
        result = await getDeviceListService(this.tokenData);
      } catch (e) {
        console.log(e);
      }
      let data = result.data;

      //   for(let d in data){
      //     let res = JSON.parse(d);
      //     console.log("res=",res);
      //     this.tableData.push(res);
      //   }
      //   console.log(this.tableData);

      this.tableData = data;
    },
    onSubmit() {
      getDeviceList({ token: token });
    },
    handleSizeChange() {
      alert("每页记录数变化" + val);
    },
    handleCurrentChange() {
      alert("页码发生变化" + val);
    },

    //设置设备重启
    async restartDevice(index) {
      var id = this.tableData[index].ID;
      var restart_data = {
        id: id,
        option: "one",
        ip: this.ip,
        userId: this.tokenData.userId,
        token: this.tokenData.token,
      };
      try {
        var d_re = await restartDeviceService(restart_data);
        if (d_re.code == 0) {
          //alert("重启成功");
          ElMessage.success('重启成功');
        } else {
          alert("操作失败");
          ElMessage.fail('操作失败');
        }
      } catch (e) {
        console.log(e);
      }
    },
    playRealVp(index) {
      var id = this.tableData[index].ID;
      localStorage.setItem("realvp_device_id", id);
      // router.push("/deviceRealVP");
      this.playing_device = id + "    " + this.tableData[index].DeviceName;
      this.deviceStreamDialogVisible = true;
    },
    async deleteDevice(index) {
      // 删除前确认
      if (!confirm("确定删除吗？")) {
        return;
      }


      var id = this.tableData[index].ID;
      var delete_data = {
        id: id,
        userId: this.tokenData.userId,
        token: this.tokenData.token,
      };
      try {
        var d_re = await deleteDeviceService(delete_data);
        if (d_re.code == 0) {
          //alert("删除成功");
          ElMessage.success('删除成功');
          //刷新页面
          this.getDeviceList();
        } else {
          //alert("操作失败");
          ElMessage.fail("操作失败");
        }
      } catch (e) {
        console.log(e);
      }
    },
    async updateButtonDevice(index) {
      var id = this.tableData[index].ID;
      this.updateForm.device_name = this.tableData[index].DeviceName;
      this.updateForm.device_ip = this.tableData[index].DeviceIP;
      this.updateForm.device_status = this.tableData[index].DeviceStatus;
      this.updateForm.device_info = this.tableData[index].DeviceInfo;
      this.updateForm.device_location = this.tableData[index].DeviceLocation;
      this.updateForm.device_type = this.tableData[index].DeviceType;
      this.updateForm.auth_id = this.tableData[index].AuthID;
      this.updateForm.id = id;
      this.updateDialogVisible= true;
    },
    async addDevice() {
      this.addDialogVisible = false;
      let result = {};
      try {
        result = await addDeviceService(this.addForm);
        if (result.code == 0) {
          ElMessage.success("添加成功");
          this.getDeviceList()
        } else {
          //alert("添加失败");
          ElMessage.error("添加失败")
        }
      } catch (e) {
        console.log(e);
      }
    },
    async updateDevice() {
      this.updateDialogVisible = false;
      let result = {};
      try {
        result = await updateDeviceService(this.updateForm);
        if (result.code == 0) {
          //alert("修改成功");
          ElMessage.success("修改成功");
          this.getDeviceList()
        } else {
          alert("修改失败");
        }
      } catch (e) {
        console.log(e);
      }
    },
    async restartAllDevice() {
      var restart_data = {
        id: id,
        ip: this.ip,
        option: "all",
        userId: this.tokenData.userId,
        token: this.tokenData.token,
      };
      try {
        var d_re = await restartDeviceService(restart_data);
        if (d_re.code == 0) {
          //alert("重启成功");
          ElMessage.success("重启成功");
        } else {
          alert("操作失败");
        }
      } catch (e) {
        console.log(e);
      }
    },
    async getIpClient() {
      try {
        const response = await axios.get("https://ipinfo.io/json");
        this.ip = response.data.ip;
        localStorage.setItem("ip", this.ip);
        //console.log(response);
      } catch (error) {
        console.error(error);
      }
    },
    handleMenuSelect(val) {
      router.push(val);
    },
    toVideoList() {
      router.push("/videoList");
    },
    // 修改条纹颜色
    tableRowClassName({ row, rowIndex }) {
      if (row.human === 1) {
        return {
          background: "#488aff",
        };
      } else {
        return "";
      }
    },
  },

  // 生命周期钩子会在组件生命周期的各个不同阶段被调用
  // 例如这个函数就会在组件挂载完成后被调用
  async mounted() {
    let now = new Date();
    if (localStorage.getItem("token") === null) {
      router.push("/login");
    }
    // console.log("mounted");
    //this.getIpClient();
    this.getDeviceList();
  },
};
</script>

<template>
  <div>
    <Menu></Menu>
    <el-container style="height: 700px; border: 1px solid #eee">
      <el-header style="font-size: 40px; background-color: rgb(238, 241, 246)"
        >监控设备列表</el-header
      >
      <el-container>
        <el-main>
          <!-- 表单 -->
          <el-form :inline="true" :model="tokenData" class="demo-form-inline">
            <el-form-item>
              <el-button
                class="el-button--danger"
                type="primary"
                @click="getDeviceList()"
                >查询</el-button
              >
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="restartAllDevice('all')"
                >重启全部设备</el-button
              >
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="addDialogVisible = true"
                >添加设备</el-button
              >
            </el-form-item>
            <el-form-item>
              <el-dialog
                v-model="addDialogVisible"
                title="添加设备"
                width="50%"
                :before-close="handleClose"
              >
                <!-- 内容主体区域 -->
                <el-form
                  ref="addFormRef"
                  :model="addForm"
                  :rules="addFormRules"
                  label-width="70px"
                >
                  <el-form-item label="设备名称" prop="device_name">
                    <el-input
                      v-model="addForm.device_name"
                      autocomplete="on"
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="设备IP" prop="device_ip">
                    <el-input v-model="addForm.device_ip"></el-input>
                  </el-form-item>
                  <el-form-item label="设备状态" prop="device_status">
                    <el-select v-model="addForm.device_status">
                      <el-option label="在线" value="在线"></el-option>
                      <el-option label="离线" value="离线"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="设备类型" prop="device_type">
                    <el-input v-model="addForm.device_type"></el-input>
                  </el-form-item>
                  <el-form-item label="设备位置" prop="device_location">
                    <el-input v-model="addForm.device_location"></el-input>
                  </el-form-item>
                  <el-form-item label="设备信息" prop="device_info">
                    <el-input v-model="addForm.device_info"></el-input>
                  </el-form-item>
                </el-form>
                <!-- 底部区域 -->
                <template #footer>
                  <span class="dialog-footer">
                    <el-button @click="addDialogVisible = false"
                      >取消</el-button
                    >
                    <el-button type="primary" @click="addDevice()"
                      >确定</el-button
                    >
                  </span>
                </template>
              </el-dialog>
            </el-form-item>
            <el-form-item>
                <el-dialog
                title="实时播放"
                v-model="deviceStreamDialogVisible"
                width="60%"
                height="60%"
                center
              >
              <div>
                视频播放({{playing_device }})：
                <VideoStream v-if="deviceStreamDialogVisible"></VideoStream>
              </div>
              </el-dialog>
            </el-form-item>

            <el-form-item>
              <el-dialog
                v-model="updateDialogVisible"
                title="修改设备"
                width="50%"
                :before-close="handleClose"
              >
                <!-- 内容主体区域 -->
                <el-form
                  ref="updateFormRef"
                  :model="updateForm"
                  :rules="updateFormRules"
                  label-width="70px"
                >
                  <el-form-item label="设备名称" prop="device_name">
                    <el-input
                      v-model="updateForm.device_name"
                      autocomplete="on"
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="设备IP" prop="device_ip">
                    <el-input v-model="updateForm.device_ip"></el-input>
                  </el-form-item>
                  <el-form-item label="设备状态" prop="device_status">
                    <el-select v-model="updateForm.device_status">
                      <el-option label="在线" value="在线"></el-option>
                      <el-option label="离线" value="离线"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="设备类型" prop="device_type">
                    <el-input v-model="updateForm.device_type"></el-input>
                  </el-form-item>
                  <el-form-item label="设备位置" prop="device_location">
                    <el-input v-model="updateForm.device_location"></el-input>
                  </el-form-item>
                  <el-form-item label="设备信息" prop="device_info">
                    <el-input v-model="updateForm.device_info"></el-input>
                  </el-form-item>
                </el-form>
                <!-- 底部区域 -->
                <template #footer>
                  <span class="dialog-footer">
                    <el-button @click="updateDialogVisible = false"
                      >取消</el-button
                    >
                    <el-button type="primary" @click="updateDevice()"
                      >确定</el-button
                    >
                  </span>
                </template>
              </el-dialog>
            </el-form-item>
          </el-form>

          <!-- 表格  :row-style="this.tableRowClassName"-->
          <el-table :data="tableData" width="100%" border>
            :row-style="this.tableRowClassName"
            <el-table-column prop="ID" label="id" width="80"></el-table-column>
            <el-table-column
              prop="DeviceName"
              label="设备名称"
              width="100"
            ></el-table-column>
            <el-table-column
              prop="DeviceLocation"
              label="设备位置"
              width="180"
            ></el-table-column>
            <el-table-column
              prop="DeviceIP"
              label="设备ip"
              width="120"
            ></el-table-column>
            <el-table-column
              prop="DeviceStatus"
              label="设备状态"
              width="80"
            ></el-table-column>
            <el-table-column
              prop="DeviceType"
              label="设备类型"
              width="120"
            ></el-table-column>
            <el-table-column
              prop="DeviceInfo"
              label="设备信息"
              width="150"
            ></el-table-column>
            <el-table-column label="操作" width="350">
              <template #default="scope">
                <el-button
                  type="primary"
                  size="mini"
                  @click.prevent="restartDevice(scope.$index)"
                  >重启</el-button
                >
                <el-button
                  type="primary"
                  size="mini"
                  @click.prevent="updateButtonDevice(scope.$index)"
                  >修改</el-button
                >
                <el-button
                  type="primary"
                  size="mini"
                  @click.prevent="deleteDevice(scope.$index)"
                  >删除</el-button
                >
                <el-button
                  type="primary"
                  size="mini"
                  @click.prevent="playRealVp(scope.$index)"
                  >播放实时</el-button
                >
                <!-- <el-button type="danger" size="mini">删除</el-button> -->
              </template>
            </el-table-column>
          </el-table>
          <br />

          <!-- 分页条 -->
          <!-- Pagination 分页 -->
          <!-- <el-pagination
            background
            layout="total,sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :total="1000"
          ></el-pagination> -->
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>
<style>
.blueRowbg {
  background: "#488aff";
}
</style>