<template>
  <div class="pagemain">
    <div class="pageTitle">
      {{ $t("route.program") }}
    </div>
    <div class="pageCon">
      <div class="toptipbox">
        <div class="ltip">{{ $t("table.programTip") }}</div>
        <div class="rtip">
          <span>{{ $t("table.storageSpaces") + ":" }} {{ total }}</span>
          <span
            style="margin-left: 12px"
          >{{ $t("table.freeSpace") + ":" }} {{ surplus || 0 }}</span>
        </div>
      </div>
      <div class="operatebox">
        <el-upload
          class="upload-demo"
          action="#"
          :auto-upload="false"
          accept=".mp3, .MP3, .Mp3, .mP3"
          :show-file-list="false"
          :on-change="handleChange"
        >
          <el-button
            type="primary"
            style="width: 92px; margin-left: 12px; margin-top: 32px"
          >
            {{ $t("table.upload") }}
          </el-button>
        </el-upload>
        <el-form
          class="detail-form program-form"
          label-width="80px"
          label-position="right"
          :model="formData"
        >
          <el-form-item :label="$t('table.aiVol')">
            <el-slider
              v-model="formData.aiVol"
              :step="1"
              :max="10"
              @change="aiVolChange"
            />
          </el-form-item>
          <el-form-item :label="$t('table.aoVol')" style="margin-left: 12px">
            <el-slider
              v-model="formData.aoVol"
              :step="1"
              :max="10"
              @change="aoVolChange"
            />
          </el-form-item>
        </el-form>
      </div>
      <el-table
        :key="randomKey"
        v-loading="listLoading"
        :data="listData"
        element-loading-text="加载中.."
        :border="true"
        fit
        highlight-current-row
        height="calc(100vh - 372px)"
        style="width: 80%; margin-top: 20px;"
        @cell-dblclick="editData"
      >
        <el-table-column align="center" label="ID" width="95" prop="id" />
        <el-table-column :label="$t('table.name')" align="center" prop="name">
          <template slot-scope="scope">
            <el-input
              v-if="scope.row[scope.column.property + 'isShow']"
              :ref="scope.column.property"
              v-model="scope.row.name"
              @blur="alterData(scope.row, scope.column)"
            />
            <span v-else>{{ scope.row.name }}</span>
          </template>
        </el-table-column>

        <el-table-column
          :label="$t('table.size')"
          :formatter="sizeFormat"
          align="center"
          width="120"
          prop="size"
        />
        <el-table-column
          :label="$t('table.actions')"
          align="center"
          width="160"
        >
          <template slot-scope="scope">
            <el-button
              v-if="
                scope.row.path &&
                  scope.row.path !== 'Undefined' &&
                  scope.row.path !== 'undefined' &&
                  scope.row.path !== 'Null' &&
                  scope.row.path !== 'null'
              "
              type="text"
              size="mini"
              :disabled="
                !scope.row.path ||
                  scope.row.path === 'Undefined' ||
                  scope.row.path === 'undefined' ||
                  scope.row.path === 'Null' ||
                  scope.row.path === 'null'
              "
              @click="handleAudit(scope.row)"
            >
              {{
                !scope.row.auditState ? $t("table.audition") : $t("table.stop")
              }}
            </el-button>
            <el-button type="text" size="mini" @click="handlePlay(scope.row)">
              {{
                scope.row.playStatus === "0"
                  ? $t("table.play")
                  : $t("table.stop")
              }}
            </el-button>
            <el-button
              size="mini"
              type="text"
              style="color: red"
              @click="handleDelete(scope.row, scope.$index)"
            >
              {{ $t("table.delete") }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="width: 80%">
        <aplayer
          v-if="showPlayer"
          ref="videoPlayRef"
          :music="videoPlay"
          :autoplay="true"
        />
      </div>
    </div>
  </div>
</template>

<script>
import {
  programList,
  programDelete,
  programUpload,
  programEdit,
  programStart, programStop,
  deviceInfo, deviceEdit,
  playstatus
} from '@/api/index.js'
import aplayer from 'vue-aplayer'
export default {
  name: 'BasicInfo',
  components: {
    aplayer
  },
  data() {
    return {
      randomKey: Math.random(),
      listData: [],
      total: 0,
      surplus: 0,
      surplusNum: 0, // 未格式化的剩余空间大小
      listLoading: true,
      showPlayer: false,
      videoPlay: {
        title: '',
        artist: '',
        src: '',
        pic: ''
      },
      formData: {
        aoVol: 0,
        aiVol: 0
      },
      timer: null
    }
  },
  mounted() {
    this.getList()
  },
  beforeDestroy() {
    if (this.timer) clearInterval(this.timer)
  },
  methods: {
    editData(row, column) {
      row[column.property + 'isShow'] = true
      // refreshTable是table数据改动时，刷新table的
      this.refreshTable()
      this.$nextTick(() => {
        this.$refs[column.property] && this.$refs[column.property].focus()
      })
    },
    alterData(row, column) {
      var index = row.name.lastIndexOf('.')
      // 获取文件后缀判断文件格式
      var ext = row.name.substr(index + 1)
      if (ext !== 'mp3' && ext !== 'MP3' && ext !== 'Mp3' && ext !== 'mP3') {
        this.$message({
          type: 'warning',
          message: this.$i18n.t('table.fileEditTip')
        })
        return
      }
      const param = {
        id: row.id,
        name: row.name
      }
      programEdit(param).then(res => {
        if (res.code === 200) {
          this.$message({
            type: 'success',
            message: this.$i18n.t('table.fileName') + this.$i18n.t('table.edit') + this.$i18n.t('table.success')
          })
        } else if (res.code === 624) {
          this.$message({
            type: 'error',
            message: res.message
          })
        } else {
          this.$message({
            type: 'error',
            message: this.$i18n.t('table.fileName') + this.$i18n.t('table.edit') + this.$i18n.t('table.failed')
          })
        }
        row[column.property + 'isShow'] = false
        this.refreshTable()
      })
    },
    refreshTable() {
      this.randomKey = Math.random()
    },
    // 上传文件
    handleChange(files) {
      if (files.size > this.surplusNum) {
        this.$message({
          type: 'error',
          message: this.$i18n.t('table.fileSurplusSizeTip')
        })
        return
      }
      const type = files.name.substring(files.name.lastIndexOf('.') + 1)
      if (type !== 'mp3' && type !== 'MP3' && type !== 'Mp3' && type !== 'mP3') {
        this.$message({
          type: 'error',
          message: this.$i18n.t('table.fileTypeTip')
        })
        return
      }
      if (files.size / 1024 / 1024 > 40) {
        this.$message({
          type: 'error',
          message: this.$i18n.t('table.fileSizeTip')
        })
        return
      }
      const formDate = new FormData()
      // 添加入参
      formDate.append('file', files.raw)
      const loading = this.$loading({
        lock: true,
        text: this.$i18n.t('table.fileUpload'),
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      programUpload(formDate).then(res => {
        loading.close()
        if (res.code === 200) {
          this.$message({
            type: 'success',
            message: this.$i18n.t('table.upload') + this.$i18n.t('table.success')
          })
          this.getList()
        } else if (res.code === 620 || res.code === 621 || res.code === 622) {
          this.$message({
            type: 'error',
            message: res.message
          })
        } else {
          this.$message({
            type: 'error',
            message: this.$i18n.t('table.upload') + this.$i18n.t('table.failed')
          })
        }
      }).catch(res => {
        loading.close()
        this.$message({
          type: 'error',
          message: this.$i18n.t('table.upload') + this.$i18n.t('table.failed')
        })
      })
    },
    // 文件列表
    getList() {
      this.listLoading = true
      programList({}).then(res => {
        if (res.code === 200) {
          this.total = this.sizeFormat({
            size: res.data.total
          })
          this.surplus = this.sizeFormat({
            size: res.data.surplus
          })
          this.surplusNum = res.data.surplus
          if (res.data && res.data.files && res.data.files.length > 0) {
            for (var i = 0; i < res.data.files.length; i++) {
              res.data.files[i].auditState = false // 试听状态
              if (res.data.files[i].playStatus === '1') {
                this.timeFun(res.data.files[i])
              }
            }
            this.listData = res.data.files
          } else {
            this.listData = []
          }
          this.getDeviceInfo()
        } else {
          this.$message.error(res.message)
        }
      })
      this.listLoading = false
    },
    // 文件大小处理
    sizeFormat(row, column, cellValue) {
      var size = row.size
      if (!size) {
        return ''
      }
      var num = 1024.00
      if (size < num) {
        return size + 'B'
      }
      if (size < Math.pow(num, 2)) {
        return (size / num).toFixed(2) + 'KB'
      } // kb
      if (size < Math.pow(num, 3)) {
        return (size / Math.pow(num, 2)).toFixed(2) + 'MB'
      } // M
      if (size < Math.pow(num, 4)) {
        return (size / Math.pow(num, 3)).toFixed(2) + 'G'
      } // G
      return (size / Math.pow(num, 4)).toFixed(2) + 'T' // T
    },
    // 删除文件
    handleDelete(row, index) {
      const ids = []
      ids.push(row.id)
      const params = {
        ids: ids
      }
      this.$confirm(this.$i18n.t('table.programDeteleTip'), this.$i18n.t('table.tips'), {
        confirmButtonText: this.$i18n.t('table.confirm'),
        cancelButtonText: this.$i18n.t('table.cancel'),
        center: true
      }).then(() => {
        programDelete(params).then(res => {
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: this.$i18n.t('table.delete') + this.$i18n.t('table.success')
            })
            this.getList()
          } else if (res.code === 625) {
            this.$message({
              type: 'error',
              message: res.message
            })
          }
        })
      }).catch(() => {

      })
    },
    // 网页试听
    handleAudit(row) {
      this.showPlayer = false
      this.$nextTick(() => {
        this.videoPlay.src = row.path
        this.videoPlay.title = row.name
        this.videoPlay.artist = ' '
        this.showPlayer = true
      })
    },
    // 播放(设备)
    handlePlay(row) {
      if (row.playStatus === '0') {
        programStart({ id: row.id }).then(res => {
          if (res.code === 630) {
            this.$message({
              type: 'error',
              message: res.message
            })
          } else {
            this.getList()
            this.timeFun(row)
          }
        }).catch(res => {
          this.getList()
        })
      } else {
        programStop({ id: row.id }).then(res => {
          if (res.code === 631) {
            this.$message({
              type: 'error',
              message: res.message
            })
          } else {
            this.time = null
            clearInterval(this.timer)
            this.getList()
          }
        }).catch(res => {
          this.getList()
        })
      }
    },
    timeFun(row) {
      this.time = null
      clearInterval(this.timer)
      this.timer = setInterval(() => {
        this.getPlaystatus(row)
      }, 2500)
    },
    // 播放状态查询
    getPlaystatus(row) {
      playstatus({ id: row.id }).then(res => {
        if (res.code === 200 && (res.playStatus === '0' || !res.playStatus)) {
          this.time = null
          clearInterval(this.timer)
          this.getList()
        }
      }).catch(() => {})
    },
    // 播放(设备)
    // handlePlay(row) {
    //   if (row.playStatus === '0') {
    //     programStart({ id: row.id }).then(res => {
    //       if (res.code === 200) {
    //         for (var i = 0; i < this.listData.length; i++) {
    //           if (this.listData[i].id !== row.id) {
    //             this.listData[i].playStatus = '0'
    //           } else {
    //             this.listData[i].playStatus = '1'
    //           }
    //         }
    //         this.listData = JSON.parse(JSON.stringify(this.listData))
    //       }
    //     })
    //   } else {
    //     programStop({ id: row.id }).then(res => {
    //       if (res.code === 200) {
    //         row.playStatus = '0'
    //       }
    //     })
    //   }
    // },
    // 设备信息获取
    getDeviceInfo() {
      deviceInfo({}).then((res) => {
        if (res.code === 200) {
          this.formData.aiVol = parseInt(res.data.aiVol) || 0
          this.formData.aoVol = parseInt(res.data.aoVol) || 0
        } else {
          this.$message.error(res.message)
        }
      })
    },
    // 音量编辑
    submitForm() {
      const param = {
        ...this.formData
      }
      deviceEdit(param).then(res => {
        if (res.code === 200) {
          this.$message({
            type: 'success',
            message: this.$i18n.t('table.save') + this.$i18n.t('table.success')
          })
          if (res.aiVol) {
            this.formData.aiVol = parseInt(res.aiVol) || 0
          }
          if (res.aoVol) {
            this.formData.aoVol = parseInt(res.aoVol) || 0
          }
        } else {
          this.$message({
            type: 'error',
            message: this.$i18n.t('table.save') + this.$i18n.t('table.failed')
          })
          this.getDeviceInfo()
        }
      })
    },
    aiVolChange(e) {
      this.formData.aiVol = e
      this.submitForm()
    },
    aoVolChange(e) {
      this.formData.aoVol = e
      this.submitForm()
    }
  }
}
</script>
<style lang="scss" scoped>
.operatebox {
  width: 80%;
  position: relative;
  .program-form {
    display: flex;
    position: absolute;
    right: 0;
    bottom: -36px;
    ::v-deep .el-slider {
      width: 120px;
      margin-left: 16px;
    }
  }
}
</style>
