<template>
  <div class="radio">
    <el-loading></el-loading>
    <el-card class="box-card">
      <el-scrollbar height="100%" always class="audioGroup">
        <div class="audioPL" v-for="(item, i) in frequencyL" :key="item.imgUrl">
          <el-image
            class="play"
            :src="item.imgUrl"
            @click="() => selectGB(item, i)"
            :style="{
              'box-shadow':
                form.frequency === item.code
                  ? ' 0 0 60px #eee'
                  : '0 0 10px #666',
              'opacity':
                form.frequency === item.code
                  ? '1'
                  : '0.8',
              'animation-play-state': !item.playState ? 'paused' : 'running',
            }"
          >
            <template #error>
              <div style="text-align: center;line-height: 50px">
                <el-icon :size="40" color="#999"><picture-rounded /></el-icon>
              </div>
            </template>
          </el-image>
        </div>
      </el-scrollbar>
      <br />
      <el-form
        ref="form"
        :model="form"
        size="small"
        :inline="true"
        label-width="80px"
      >
        <el-form-item label="日期">
          <el-date-picker
            v-model="form.value"
            type="date"
            :clearable="false"
            placeholder="请选择日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="时段">
          <el-time-picker
            v-model="form.picker"
            is-range
            clearable
            editable
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          >
          </el-time-picker>
        </el-form-item>
        <el-form-item label="节目名称">
          <el-input v-model="form.title" placeholder="请输入节目名称" />
        </el-form-item>
        <el-form-item style="float: right">
          <el-button type="primary" @click="getlist">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <br />
    <el-table
      :header-cell-style="{ backgroundColor: '#f4f5f7', color: '#606266' }"
      :data="radioList"
      style="width: 100%"
    >
      <el-table-column type="index" />
      <el-table-column align="center" prop="name" label="广播" />
      <el-table-column align="center" prop="programName" label="节目" />
      <el-table-column align="center" label="播出时间">
        <template #default="scope">
          {{ scope.row.startTime }} - {{ scope.row.endTime }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template #default="scope">
          <el-button
            size="mini"
            v-if="
              playselect.localUrl !== baseUrl + scope.row.savePath
                ? true
                : !playselect.playState
            "
            @click="() => play(scope.row)"
          >
            播放
          </el-button>
          <el-button
            size="mini"
            v-if="
              playselect.localUrl === baseUrl + scope.row.savePath
                ? playselect.playState
                : false
            "
            @click="() => pause(scope.row)"
          >
            暂停
          </el-button>
          <el-button
            size="mini"
            :loading="load['download' + scope.row.savePath] ? true : false"
            @click="() => download(scope.row)"
          >
            下载
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <br />

    <!-- audio ui -->
    <el-row class="audioui">
      <el-col :span="12">
        <el-image
          class="play"
          :src="playselect.imgUrl"
          :style="{
            width: '50px',
            height: '50px',
            'animation-play-state': !playselect.playState
              ? 'paused'
              : 'running',
          }"
        >
          <template #error>
            <div style="text-align: center;line-height: 50px">
              <el-icon :size="40" color="#999"><picture-rounded /></el-icon>
            </div>
          </template>
        </el-image>

        <el-icon
          :size="30"
          v-if="!playselect.playState"
          @click="() => pplay(playselect)"
          color="#333"
        >
          <video-play />
        </el-icon>
        <el-icon
          :size="30"
          v-else
          color="#333"
          @click="() => pause(playselect)"
        >
          <video-pause />
        </el-icon>
      </el-col>
      <el-col :span="12" style="padding: 7px 0 0 15px;">
        <el-slider
          @input="volume"
          :format-tooltip="v => vol(v)"
          v-model="volumeNum"
        ></el-slider>
      </el-col>
    </el-row>
    <el-pagination
      v-model:currentPage="page"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
    </el-pagination>
    <audio id="playaudio" controls />
  </div>
</template>

<script>
// @ is an alias to /src
import { VideoPlay, VideoPause, PictureRounded } from "@element-plus/icons";

import { frequencyList, PLList } from "@/api/index.js";
import config from "@/config/index";
export default {
  name: "radio",
  data() {
    return {
      volumeNum: 0,
      baseUrl: "",
      playselect: {},
      load: {},
      form: {
        value: "",
        frequency: "",
        title: "",
        picker: [],
      },
      page: 1,
      pageSize: 10,
      total: 0,
      frequencyL: [],
      radioList: [],
    };
  },
  mounted() {
    this.volumeNum = window.localStorage.volumeNum || 100;
    this.volume();
    let D = new Date(new Date() - 86400000);
    let Y = D.getFullYear();
    let M = D.getMonth() + 1;
    let Day = D.getDate();
    M <= 9 ? (M = "0" + M) : "";
    Day <= 9 ? (Day = "0" + Day) : "";
    this.form = {
      value: [Y, M, Day].join("-"),
      frequency: "",
    };
    frequencyList().then(res => {
      let li = res || [];
      this.frequencyL = li;
      this.form.frequency = li[0].code;
      this.getlist();
      this.baseUrl = config.base.url2 + "/";
    });
  },
  computed: {},
  methods: {
    vol(val) {
      return "音量:" + val;
    },
    selectGB(item) {
      this.form.frequency = item.code;
      this.getlist();
    },
    handleCurrentChange(page) {
      this.page = page;
      this.getlist();
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.getlist();
    },
    getlist() {
      let dt = this.form.value;
      if (typeof dt !== "string") {
        dt = new Date(dt);
        let Y = dt.getFullYear();
        let M = dt.getMonth() + 1;
        let D = dt.getDate();
        M <= 9 ? (M = "0" + M) : "";
        D <= 9 ? (D = "0" + D) : "";
        dt = "" + Y + M + D;
      } else {
        dt = dt.replace(/-/g, "");
      }
      let p = {
        dt,
        page: this.page,
        pageSize: this.pageSize,
      };
      this.form.frequency && (p.code = this.form.frequency);
      this.form.title && (p.programName = this.form.title);
      if (this.form.picker && this.form.picker.length) {
        p.startTime = this.formatpicker(0);
        p.endTime = this.formatpicker(1);
      }

      PLList(p).then(res => {
        this.total = res.total || 0;
        this.radioList = res.data || [];
      });
    },
    formatpicker(num) {
      let T = this.form.picker[num],
        H = T.getHours(),
        M = T.getMinutes(),
        D = T.getSeconds();
      H > 9 ? "" : (H = "0" + H);
      M > 9 ? "" : (M = "0" + M);
      D > 9 ? "" : (D = "0" + D);
      return H + ":" + M + ":" + D;
    },
    pause() {
      let audio = document.getElementById("playaudio");
      if (audio) audio.pause();
      this.playselect.playState = false;
    },
    play(row) {
      // 重新播放
      if (!row.imgUrl) return;
      let playselect = row;
      playselect.localUrl = this.baseUrl + row.savePath;
      playselect.playState = true;
      this.playselect = playselect;
      this.$nextTick(() => {
        let audio = document.getElementById("playaudio");
        this.volumeNum = ((audio.volume || 0) * 100).toFixed(0) - 0;
        window.localStorage.volumeNum = this.volumeNum;
        audio.src = this.playselect.localUrl;
        audio.load();
        audio.play();
      });
    },
    pplay(row) {
      // 播放
      if (!row.imgUrl) return;
      let playselect = row;
      playselect.localUrl = this.baseUrl + row.savePath;
      playselect.playState = true;
      this.playselect = playselect;
      document.getElementById("playaudio").play();
    },
    download(row) {
      // download
      this.load["download" + row.savePath] = true;
      let xhttp,
        that = this;
      if (window.XMLHttpRequest) xhttp = new XMLHttpRequest();
      else xhttp = new window.ActiveXObject("Microsoft.XMLHTTP");
      xhttp.responseType = "blob";
      xhttp.open("GET", this.baseUrl + row.savePath, true);
      xhttp.send();
      xhttp.addEventListener(
        "progress",
        res => {
          console.log(res, (res.loaded / res.total) * 100);
          that.load["download" + row.savePath] =
            ((res.loaded / res.total) * 100).toFixed(0) - 0;
        },
        false
      );
      xhttp.onreadystatechange = function() {
        if (this.readyState != 4 || this.status != 200) return;
        // 组装a标签
        let elink = document.createElement("a");
        // 设置下载文件名
        elink.download =
          row.dt + "-" + row.name + "-" + row.programName + ".mp3";
        elink.style.display = "none";
        elink.href = URL.createObjectURL(this.response);
        document.body.appendChild(elink);
        elink.click();
        document.body.removeChild(elink);
        delete that.load["download" + row.savePath];
      };
    },
    volume() {
      if (!document.getElementById("playaudio")) return;
      document.getElementById("playaudio").volume = this.volumeNum / 100;
      window.localStorage.volumeNum = this.volumeNum;
    },
  },
  beforeUnmount: function() {},
  components: { VideoPlay, VideoPause, PictureRounded },
};
</script>

<style>
.radio {
  margin: 10px 15px;
  background: #fff;
}
.radio .el-loading-spinner {
  height: 100%;
}
#playaudio {
  opacity: 0;
  position: absolute;
  z-index: -1;
}

.play {
  cursor: pointer;
  border-radius: 50%;
  background-size: 100% 100%;
  background-repeat: no-repeat;
  vertical-align: middle;
  animation-name: example;
  box-shadow: 0 0 10px #eee;
  animation-duration: 3s;
  width: 100px;
  height: 100px;
  animation-direction: normal;
  animation-iteration-count: infinite;
  animation-timing-function: linear;
  margin-right: 5px;
  display: inline-block;
}
.radio .el-icon {
  vertical-align: middle;
}
.radio .el-pagination {
  text-align: right;
}

@keyframes example {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.audioui {
  float: left;
  width: 200px;
  border: 1px solid #eee;
  border-radius: 5px;
  padding: 5px 20px 5px 8px;
  line-height: 35px;
}

.audioGroup {
  height: 200px;
  white-space: nowrap;
  background-image: linear-gradient(to right, #c55c60, #bd8946);
}
.audioGroup .audioPL {
  display: inline-block;
  width: 130px;
  padding-top: 50px;
  height: 200px;
  text-align: center;
}

.audioGroup .el-scrollbar__thumb {
  background-color: #fff;
}
</style>
