<template>
  <div>
    <el-row style="padding: 5px">
      <el-col :md="16" style="padding: 5px">
        <el-card v-if="camDetail !== null" class="box-card">
          <div slot="header" class="clearfix">
            <span>{{ camDetail.camName }}</span>
          </div>
          <div class="text item">
            <span v-if="camDetail.onLive">
              <video
                :src="camDetail.pullUrl"
                controls
                autoplay
                class="video"
                width="100%"
                height="480px"
              />
            </span>
            <span v-else>
              <video
                v-if="camRecordDetail !== null"
                :src="camRecordDetail.url"
                controls
                autoplay
                class="video"
                width="100%"
                height="480px"
              />
              <span v-else>
                无实时监控(选择日期查看历史监控录像)
              </span>
            </span>
          </div>
        </el-card>
        <el-card v-else class="box-card">
          <div slot="header" class="clearfix">
            <span>选择摄像头查看监控</span>
          </div>
        </el-card>
      </el-col>
      <el-col :md="8" style="padding: 5px">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <el-select
              v-model="selectedOption"
              style="margin: 5px;"
              clearable
              placeholder="选择摄像头"
              @change="onSelectChange"
            >
              <el-option v-for="item in selectOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
            <el-button type="plain" icon="el-icon-date" style="margin: 5px" @click="onSelectDate">选择日期</el-button>
            <el-button type="plain" icon="el-icon-magic-stick" style="margin: 5px" @click="onButtonSubmit">提交</el-button>
          </div>
          <div class="text item">
            <span style="color: red">
              {{ getYearMonthDay(calendarDate) }} 的监控录像
            </span>
            <el-divider />
            <el-table
              :data="dataList"
              :show-header="true"
              style="width: 100%"
            >
              <el-table-column
                prop="startTime"
                label="开始时间"
              />
              <el-table-column
                prop="duration"
                label="时长(秒)"
              />
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    icon="el-icon-video-play"
                    @click="handlePlay(scope.row.recordId)"
                  >播放</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-dialog
      title="日历"
      append-to-body
      :visible.sync="showCalenderDialog"
      width="50%"
      center
    >
      <div style="padding: 5px; text-align: center">
        <span>
          <span style="color: red">红色 ✔</span>标记的日期表示当天有监控录像
        </span>
        <el-calendar v-model="calendarDate">
          <div
            slot="dateCell"
            slot-scope="{ date, data }"
            @click="handleCellClick(date, data)"
          >
            <p v-if="dealMyDate(data.day)" style="color: red">
              {{ data.day.split("-").slice(2).join() }} {{ '✔' }}
            </p>
            <p v-else>{{ data.day.split("-").slice(2).join() }}</p>
          </div>
        </el-calendar>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getCamDetail, getCamKeyValue, getRecordByMonth, getRecordUrl, submitActivity } from '@/api/disk'

export default {
  name: 'DiskCam',
  data() {
    return {
      selectOptions: [],
      selectedOption: '',
      calendarDate: new Date(),
      dateMap: new Map(),
      query: {
        camId: '',
        yearMonth: '',
        yearMonthDay: ''
      },
      dataList: [],
      showCalenderDialog: false,
      camDetail: null,
      camRecordDetail: null
    }
  },
  watch: {
    $route() {
      this.$router.go()
    },
    calendarDate: {
      handler(newValue, oldValue) {
        const oldMonth = this.getYearMonth(oldValue)
        const newMonth = this.getYearMonth(newValue)
        if (oldMonth !== newMonth) {
          this.query.yearMonth = this.getYearMonth(newValue)
          getRecordByMonth(this.query).then(resp => {
            if (resp.code === 0) {
              this.dateMap.clear()
              for (const item of resp.data) {
                const date1 = new Date(item)
                const dayStr = this.getYearMonthDay(date1)
                this.dateMap.set(dayStr, date1)
              }
              // 对 calendarDate 赋值重新渲染日历, 目的是调用 dealMyDate 处理当月的日期
              this.calendarDate = new Date(newMonth)
            }
          }).catch(error => {
            this.$message.error(error.message)
          })
        }
      }
    }
  },
  created() {
    document.title = '监控'
    getCamKeyValue().then(resp => {
      if (resp.code === 0) {
        this.selectOptions = resp.data
      }
    })
  },
  methods: {
    getData() {
      getCamDetail(this.query).then(resp => {
        if (resp.code === 0) {
          this.camDetail = resp.data
        }
      })
    },
    onSelectChange() {
      if (this.selectedOption === '') {
        this.query.camId = ''
        this.query.yearMonth = ''
        this.query.yearMonthDay = ''
        this.camDetail = null
        this.camRecordDetail = null
        return
      }

      this.query.camId = this.selectedOption
      this.query.yearMonth = ''
      this.query.yearMonthDay = ''
      this.getData()
    },
    handleCellClick(date, data) {
      this.showCalenderDialog = false
      this.query.yearMonthDay = this.getYearMonthDay(date)
      getCamDetail(this.query).then(resp => {
        if (resp.code === 0) {
          const respData = resp.data
          this.camDetail = respData
          this.dataList = respData.dayRecords
        }
      })
    },
    // 渲染日历时会处理每个日期
    dealMyDate(val) {
      return this.dateMap.get(val) !== undefined
    },
    getYearMonth(date) {
      const year = date.getFullYear().toString().padStart(4, '0')
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      // const day = date.getDate().toString().padStart(2, '0')
      // const hour = date.getHours().toString().padStart(2, '0')
      // const minute = date.getMinutes().toString().padStart(2, '0')
      // const second = date.getSeconds().toString().padStart(2, '0')
      // 2023-02-16 08:25:05
      // console.log(`${year}-${month}-${day} ${hour}:${minute}:${second}`)
      return year + '-' + month
    },
    getYearMonthDay(date) {
      const year = date.getFullYear().toString().padStart(4, '0')
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      return year + '-' + month + '-' + day
    },
    handlePlay(recordId) {
      getRecordUrl(recordId).then(resp => {
        if (resp.code === 0) {
          this.camRecordDetail = resp.data
        } else {
          this.$message.error(resp.msg)
        }
      })
    },
    onSelectDate() {
      if (this.selectedOption === '') {
        this.$message.info('请先选择摄像头')
      } else {
        this.showCalenderDialog = true
      }
    },
    onButtonSubmit() {
      this.$confirm('确认提交？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        submitActivity().then(resp => {
          this.$message.info(resp.msg)
        }).catch(error => {
          this.$message.error(error.message)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    }
  }
}
</script>

<style>
</style>
