<script>
import axios from "axios";
import { getVideoListService, quashVideoService } from "@/api/video.js";
import { delayVideoService } from "@/api/video.js";
import router from "@/router/index.js";
import Cookies from "js-cookie";

export default {
  data() {
    return {
      ip: "",
      tableData: [],
      file_sum_size: 0,
      tokenData: {
        token: localStorage.getItem("token"),
        ip: localStorage.getItem("ip"),
        userId: localStorage.getItem("userId"),
        username: localStorage.getItem("username"),
        hour: 0,
        entrydate: [],
      },
      searchForm: {
        hour: 0,
        entrydate: [],
      },
    };
  },

  // methods 是一些用来更改状态与触发更新的函数
  // 它们可以在模板中作为事件处理器绑定
  methods: {
    async getVideoList() {
      let result = {};
      try {
        // console.log("this entrydate:", this.tokenData.entrydate[0]);
        // console.log("type time:",typeof this.tokenData.entrydate[0])
        // if(this.tokenData.entrydate.length > 0) {
        //   // get the date from the date picker
        //   Cookies.set("entrydate", [this.tokenData.entrydate[0], this.tokenData.entrydate[1]]);
        // }
        result = await getVideoListService(this.tokenData);
      } catch (e) {
        console.log(e);
      }
      let data = result.data;
      let len = data?data.length:0;

      for (let i = 0; i < len; i++) {
        //this.file_sum_size += parseFloat(data[i].file_size);
        data[i].FileSize = parseFloat(data[i].FileSize/ 1024 / 1024).toFixed(
          2
        );
      }
      console.log("file_size", this.file_sum_size, "len=", len);
      this.tableData = data;
    },
    logout() {
      //退出登录
      localStorage.clear();
      router.push("/login");
    },
    handleMenuSelect(val) {
      router.push(val);
    },
    async quashOption() {
      // 撤销操作
      let result=await quashVideoService(this.tokenData);
      if (result.code == 0) {
        alert(result.message);
        this.getVideoList();
      } else {
        alert("操作失败");
      }
    },
    onSubmit() {
      getVideoList({ token: token });
    },
    handleSizeChange() {
      alert("每页记录数变化" + val);
    },
    handleCurrentChange() {
      alert("页码发生变化" + val);
    },
    playVideo(index) {
      var id = this.tableData[index].ID;
      var name = this.tableData[index].VideoName;
      localStorage.setItem("video_id", id);
      localStorage.setItem("video_name", name);
      //alert("id=" + id + " name=" + name);
      router.push("/video");
    },
    async downloadVideo(index) {
      var id = this.tableData[index].ID;
      var name = this.tableData[index].VideoName;
      var vurl =
        "https://gep.ljsea.xyz/video/mp4?filename=" +
        name +
        "&id=" +
        id +
        "&userId=" +
        localStorage.getItem("userId") +
        "&ip=" +
        this.ip +
        "&token=" +
        localStorage.getItem("token"); //视频地址
      //下载文件
      try {
        // 发送请求到后端获取视频文件
        const response = await axios({
          url: vurl,
          method: "GET",
          responseType: "blob", // 告诉axios我们期望的响应是一个blob
          headers: {
            // 如果有必要，设置其他请求头
            "Content-Type": "video/mp4",
          },
        });

        // 创建Blob对象
        const videoBlob = new Blob([response.data], { type: "video/mp4" });

        // 创建一个指向Blob对象的URL
        const videoUrl = URL.createObjectURL(videoBlob);

        // 使用a标签下载文件
        const link = document.createElement("a");
        link.href = videoUrl;
        link.download = name; // 设置下载文件的名称
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        // 释放URL对象
        URL.revokeObjectURL(videoUrl);
      } catch (error) {
        console.error("下载视频时发生错误:", error);
      }
    },
    async delayVideo(index) {
      var id = this.tableData[index].ID;
      var days = 15;
      var delay_data = {
        id: id,
        option: "one",
        ip: this.ip,
        delay: days,
        userId: this.tokenData.userId,
        token: this.tokenData.token,
      };
      try {
        var d_re = await delayVideoService(delay_data);
        if (d_re.code == 0) {
          alert(d_re.message);
        } else {
          alert("操作失败");
        }
      } catch (e) {
        console.log(e);
      }
    },
    async delayAllVideo() {
      var days = 15;
      var delay_data = {
        id: -1,
        option: "all",
        ip: this.ip,
        delay: days,
        userId: this.tokenData.userId,
        token: this.tokenData.token,
      };
      try {
        var d_re = await delayVideoService(delay_data);
        if (d_re.code == 0) {
          alert(d_re.data);
        } 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);
      }
    },
    toDeviceM() {
      router.push("/device");
    },
    // 修改条纹颜色
    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");
    await this.getIpClient();
    // if( Cookies.get("entrydate")){
    //   console.log("entrydate:",Cookies.get("entrydate"));
    //   this.tokenData.entrydate = [Object(Cookies.get("entrydate")[0]),Object(Cookies.get("entrydate")[1])];
    // }

    this.getVideoList();
  },
};
</script>

<template>
  <div>
    <el-button type="primary" size="mini" @click.prevent="handleMenuSelect('/videoList')"
      >视频列表</el-button
    >
    <el-button type="primary" size="mini" @click.prevent="handleMenuSelect('/device')"
      >设备管理</el-button
    >
    <el-button type="primary" size="mini" @click.prevent="handleMenuSelect('/User')"
      >用户</el-button
    >
    <el-button type="primary" size="mini" @click.prevent="handleMenuSelect('/chat')"
      >聊天</el-button
    >
    <el-button type="primary" size="mini" @click.prevent="handleMenuSelect('/group')"
      >群组</el-button
    >
    <el-button
      type="primary"
      size="mini"
      @click.prevent="handleMenuSelect('/cid')"
      >集成部署</el-button
    >
    <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 label="视频日期">
              <el-date-picker
                v-model="tokenData.entrydate"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              >
              </el-date-picker>
            </el-form-item>

            <el-select v-model="tokenData.hour">
              <el-option label="不选" value="33"></el-option>
              <el-option label="0点" value="00"></el-option>
              <el-option label="1点" value="01"></el-option>
              <el-option label="2点" value="02"></el-option>
              <el-option label="3点" value="03"></el-option>
              <el-option label="4点" value="04"></el-option>
              <el-option label="5点" value="05"></el-option>
              <el-option label="6点" value="06"></el-option>
              <el-option label="7点" value="07"></el-option>
              <el-option label="8点" value="08"></el-option>
              <el-option label="9点" value="09"></el-option>
              <el-option label="10点" value="10"></el-option>
              <el-option label="11点" value="11"></el-option>
              <el-option label="12点" value="12"></el-option>
              <el-option label="13点" value="13"></el-option>
              <el-option label="14点" value="14"></el-option>
              <el-option label="15点" value="15"></el-option>
              <el-option label="16点" value="16"></el-option>
              <el-option label="17点" value="17"></el-option>
              <el-option label="18点" value="18"></el-option>
              <el-option label="19点" value="19"></el-option>
              <el-option label="20点" value="20"></el-option>
              <el-option label="21点" value="21"></el-option>
              <el-option label="22点" value="22"></el-option>
              <el-option label="23点" value="23"></el-option>
            </el-select>

            <el-form-item>
              <el-button type="primary" @click="getVideoList()">查询</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="logout()">退出登录</el-button>
            </el-form-item>
            <el-form-item>
              <el-button
                class="el-button--danger"
                type="primary"
                @click="delayAllVideo('all')"
                >全部延迟删除</el-button
              >
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="toDeviceM()"
                >设备信息</el-button
              >
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="quashOption()"
                >撤销操作</el-button
              >
            </el-form-item>
            <!-- <el-form-item>
            所有文件大小：  {{ parseFloat(this.file_sum_size/1024/1024).toFixed(2) }} GB
            </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="VideoName"
              label="视频名称"
              width="250"
            ></el-table-column>
            <el-table-column label="是否有人" width="30" prop="human">
              <template #default="scope">
                {{ scope.row.human == 1 ? "有" : "无" }}
              </template>
            </el-table-column>
            <el-table-column
              prop="CreateTime"
              label="开始时间"
              width="180"
            ></el-table-column>
            <el-table-column
              prop="EndTime"
              label="结束时间"
              width="180"
            ></el-table-column>
            <el-table-column
              prop="DeleteTime"
              label="预期删除时间"
              width="180"
            ></el-table-column>
            <el-table-column
              prop="FileSize"
              label="文件大小(MB)"
              width="80"
            ></el-table-column>
            <el-table-column
              prop="CameraID"
              label="摄像头"
              width="50"
            ></el-table-column>
            <el-table-column label="操作" width="300">
              <template #default="scope">
                <el-button
                  type="primary"
                  size="mini"
                  @click.prevent="playVideo(scope.$index)"
                  >播放</el-button
                >
                <el-button
                  type="primary"
                  size="mini"
                  @click.prevent="delayVideo(scope.$index)"
                  >延迟删除</el-button
                >
                <el-button
                  type="primary"
                  size="mini"
                  @click.prevent="downloadVideo(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";
}
.el-menu-vertical-demo {
  width: 200px; /* 设置菜单宽度 */
  background-color: #1e2733; /* 设置背景颜色 */
  /* ... 其他样式属性 ... */
}
</style>