<template>
  <div class="synergr" :id="videoId" v-if="isInit">
    <canvas
      id="synergr-canvas"
      :style="{height: '28px'}"
      v-if="canvasWidth"
      @click="onClick"
      @mousemove.stop="onMousemove"
      @mouseup="onMouseUp"
      @mouseleave="isHide = true"
      :width="canvasWidth"
      height="28">
    </canvas>
    <div class="time" v-show="!isHide" :style="{left: left + 'px'}">{{ time }}</div>
    <img
      @mousedown="onDragDown"
      class="drag-img"
      :style="{left: x + 'px'}"
      src="https://cdn.cunwuyun.cn/slw2.0/images/drag.png" />
    <div class="slw-bottom">
      <div class="action-bar">
        <div class="left">
          <!-- <div
            class="volume"
            @mouseleave.stop="isShowVolume = false">
            <img 
              @mouseenter.stop="isShowVolume = true"
              src="https://cdn.cunwuyun.cn/slw2.0/images/sound.png">
            <div class="volume-slider" :class="[isShowVolume ? 'active' : '']">
              <el-slider
                input-size="mini"
                v-model="volume"
                vertical
                @change="onVolume"
                height="80px">
              </el-slider>
            </div>
          </div> -->
          <div class="play-status">
            <div class="live" v-if="isLiveing">
              <span class="label"></span>
              <i>直播中</i>
              <em>{{ date }}</em>
            </div>
            <div v-else class="back-btn" @click="backLiveing">回到直播</div>
          </div>
        </div>
        <div class="right">
          <el-tooltip effect="dark" content="选择日期" placement="top">
            <img src="https://cdn.cunwuyun.cn/slw2.0/images/date.png" @click="isShowDate = true">
          </el-tooltip>
        </div>
      </div>
    </div>
    <div class="playback">
      <div class="synergr-more" @click="isShowTimeline = !isShowTimeline" :class="[isShowTimeline ? 'active' : '']">
        <img title="展开" src="https://cdn.cunwuyun.cn/slw2.0/images/arrow.png" />
      </div>
      <div class="playback-list" v-if="isShowTimeline">
        <div class="playback-item" v-for="(item, index) in times" :key="index">
          <el-checkbox></el-checkbox>
          <span>通道{{ index }}</span>
          <PlaybackTime class="playback-item__timeline" :key="'PlaybackTime' + index" :times="item"></PlaybackTime>
        </div>
      </div>
    </div>
    <ai-dialog
      title="选择日期"
      :visible.sync="isShowDate"
      width="520px"
      @onConfirm="onConfirm">
      <el-form class="ai-form" ref="form" :model="form" label-width="80px" size="small">
        <el-form-item label="选择日期" prop="date" :rules="[{ required: true, message: '请选择日期', trigger: 'change' }]">
          <el-date-picker
            value-format="yyyy-MM-dd"
            v-model="form.date"
            type="date"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
      </el-form>
    </ai-dialog>
  </div>
</template>

<script>
  import PlaybackTime from './PlaybackTime'

  export default {
    props: ['ids', 'instance'],

    name: 'Synergy',

    components: {
      PlaybackTime
    },

    data () {
      return {
        canvasWidth: 0,
        currIndex: 0,
        isShowDate: false,
        isShow: true,
        isShowVolume: false,
        isLiveing: true,
        form: {
          date: ''
        },
        times: [],
        isShowTimeline: false,
        checkList: [],
        isInit: false,
        left: 0,
        date: '',
        scale: 4,
        width: '',
        isHide: false,
        x: 0,
        time: '',
        videoId: `synergr-${new Date().getTime()}`,
        isFullscreen: false,
        timer: null
      }
    },

    watch: {
      src: {
        handler (val) {
          if (val) {
            this.isShow = false

            this.$nextTick(() => {
              this.isShow = true
            })
          }
        },
        immediate: true,
        deep: true
      }
    },

    mounted () {
      this.form.date = this.$moment(new Date()).format('YYYY-MM-DD')
      this.date = this.$moment(new Date()).format('YYYY-MM-DD')
      this.getSlwPlaybackTime()
      this.$nextTick(() => {
        this.init()
      })
    },

    methods: {
      onMousemove (e) {
        const canvasInfo = document.querySelector(`#synergr-canvas`).getBoundingClientRect()
        const seconds = 24 * 60 * 60
        const x = e.clientX - canvasInfo.left
        const unit = seconds / this.canvasWidth * x
        this.left = x
        this.time = this.secTotime(unit)
        this.isHide = false

        if (!this.isChoose) return
        this.x = e.clientX - canvasInfo.left - 4
        this.ratioW = this.x / this.canvasWidth
      },

      onDragDown () {
        this.isChoose = true
      },

      backLiveing () {
        this.$emit('backLiveing')
        this.isLiveing = true
        this.initNowTime()
      },

      onMouseUp () {
        if (!this.isChoose) return

        clearInterval(this.timer)
        this.timer = null
        this.isChoose = false
        const time = this.secTotime((24 * 60 * 60) / this.canvasWidth * this.x)
        this.$emit('replay', {
          startTime: `${this.form.date} ${time}`,
          endTime: this.form.date + ` ${Number(time.substr(0, 2)) + 6 > 9 ? Number(time.substr(0, 2)) + 6 : '0' + (Number(time.substr(0, 2)) + 6)}:59:59`
        })

        this.isLiveing = false
      },

      init () {
        this.$nextTick(() => {
          this.isInit = true
          this.$nextTick(() => {
            this.canvasWidth = document.querySelector(`#${this.videoId}`).offsetWidth
            this.canvasHeight = document.querySelector(`#${this.videoId}`).offsetHeight

            this.$nextTick(() => {
              const el = document.querySelector(`#synergr-canvas`)
              this.ctx = el.getContext('2d')
              this.ctx.width  = document.querySelector(`#${this.videoId}`).offsetWidth
              this.ctx.height  = document.querySelector(`#${this.videoId}`).offsetHeight

              if (this.x > 0) {
                this.x = this.canvasWidth * this.ratioW
              } else {
                this.initNowTime()
              }

              this.renderTimeLine()
              this.countdown()
            })
          })
        })
      },

      countdown () {
        this.timer = setInterval(() => {
          this.initNowTime()
        }, 1000)
      },

      drawLine(ctx, options) {
        const { beginX, beginY, endX, endY, lineColor, lineWidth } = options
        ctx.beginPath()
        ctx.lineWidth = lineWidth
        ctx.moveTo(beginX, beginY)
        ctx.lineTo(endX, endY)
        ctx.strokeStyle = lineColor
        ctx.stroke()
      },

      onClick (e) {
        const canvasInfo = document.querySelector(`#synergr-canvas`).getBoundingClientRect()
        this.x = e.clientX - canvasInfo.left - 4
        clearInterval(this.timer)
        this.timer = null
        const time = this.secTotime((24 * 60 * 60) / this.canvasWidth * this.x)
        this.$emit('replay', {
          startTime: `${this.form.date} ${time}`,
          endTime: this.form.date + ` ${Number(time.substr(0, 2)) + 6 > 9 ? Number(time.substr(0, 2)) + 6 : '0' + (Number(time.substr(0, 2)) + 6)}:00:00`
        })
        this.isLiveing = false
      },

      renderTimeLine () {
        const ctx = this.ctx
        ctx.fillStyle = 'rgba(40, 43, 58, 1)'
        ctx.fillRect(0, 0, this.canvasWidth, 28)
        
        ctx.fillStyle = '#fff'
        ctx.font = '12px Arial'
        const w = this.canvasWidth / 24 

        for (let i = 1; i < 25; i ++) {
          this.drawLine(ctx, {
            beginX: i * w,
            beginY: 28,
            endX: i * w,
            endY: i % this.scale === 0 ? 22 : 24,
            lineColor: i % this.scale === 0 ? '#000' : '#000',
            lineWidth: i % this.scale === 0 ? 1 : 1
          })

          if (i % this.scale === 0) {
            const text = (i < 10 ? '0' + i : i) + ': 00'
            const textWidth = ctx.measureText(text).width
            if (i === 24) {
              ctx.fillText(text, i * w - textWidth, 21)
            } else {
              ctx.fillText(text, i * w - textWidth / 2, 21)
            }
          }
        }
      },

      initNowTime () {
        const date = new Date()
        const seconds = date.getHours() * 3600 + date.getMinutes() * 60 + date.getSeconds()

        this.x = seconds / (24 * 60 * 60) * this.canvasWidth
      },

      secTotime (s) {
        let second = parseInt(s)
        let minute = 0
        let hour = 0
        if (second > 60) {
          minute = parseInt(second / 60)
          second = parseInt(second % 60)
          if (minute > 60) {
            hour = parseInt(minute / 60)
            minute = parseInt(minute % 60)
          }
        }

        hour = `${parseInt(hour) > 9 ? parseInt(hour) : '0' + parseInt(hour)}`
        minute = `${parseInt(minute) > 9 ? parseInt(minute) : '0' + parseInt(minute)}`
        second = `${parseInt(second) > 9 ? parseInt(second) : '0' + parseInt(second)}`
        return `${hour}:${minute}:${second}`
      },

      onConfirm () {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.isShowDate = false
            this.date = this.form.date
            this.getSlwPlaybackTime()
          }
        })
      },

      getSlwPlaybackTime () {
        this.isLoading = true
        this.instance.post(`/app/appzyvideoequipment/getSlwPlaybackTime`, null, {
          params: {
            ids: this.ids,
            startTime: this.date + ' 00:00:00',
            endTime: this.date + ' 23:59:59',
          }
        }).then(res => {
          if (res.code == 0) {
            if (res.data && res.data.length) {
              this.times = res.data.map(v => {
                return v.times.map(item => {
                  const startTime = (item.startTime - new Date(this.date + ' 00:00:00').getTime()) / 1000
                  const endTime = (item.endTime - new Date(this.date + ' 00:00:00').getTime()) / 1000

                  return {
                    startTime: Number(startTime.toFixed(0)),
                    endTime: Number(endTime.toFixed(0))
                  }
                }).sort((a, b) => {
                  return a.startTime - b.startTime
                })
              })
            }

            this.isLoading = false
          }
        }).catch(() => {
          this.isLoading = false
        })
      },

      onVolume (e) {
        const v = (e / 100).toFixed(1)
        const subPage = document.querySelector(`#${this.id}`).contentWindow
        subPage.postMessage({
          type: 'volume',
          value: Number(v)
        }, '*')
      },

      reset () {
        setTimeout(() => {
          this.init()
        }, 60)
      }
    }
  }
</script>

<style lang="scss">
  .synergr {
    position: relative;
    width: 100%;
    height: 100%;
    font-size: 0;
    background: rgba(40, 43, 58, 1);

    .playback {
      position: absolute;
      top: 0;
      left: 50%;
      z-index: 1;
      width: 100%;
      padding-top: 6px;
      text-align: center;
      transform: translate(-50%, -100%);
      background: #202330;

      .synergr-more {
        width: 80px;
        height: 16px;
        margin: 0 auto;
        cursor: pointer;
        background: url(https://cdn.cunwuyun.cn/slw2.0/images/more.png);
        color: #fff;

        img {
          position: relative;
          transition: all ease 0.5s;
          transform: rotate(180deg);
        }

        &.active img {
          transform: rotate(0);
        }
      }

      .playback-list {
        padding: 8px 16px;
        background: rgba(22, 24, 33, 1);
        font-size: 12px;
        color: #FFFFFF;

        .playback-item {
          display: flex;
          align-items: center;
          width: 100%;
          margin-bottom: 4px;

          &:last-child {
            margin-bottom: 0;
          }

          .playback-item__timeline {
            flex: 1;
            height: 12px;
            border-radius: 6px;
          }

          span {
            padding: 0 8px 0 0;
          }
        }
      }
    }

    .time-scale {
      display: flex;
      position: absolute;
      align-items: center;
      justify-content: center;
      left: 0;
      top: 28px;
      z-index: 1;
      user-select: none;
      width: 12px;
      height: 24px;

      span {
        width: 2px;
        height: 24px;
        background: rgba(255, 255, 255, 0.8);
      }
    }

    .drag-img {
      position: absolute;
      left: 0;
      top: 0;
      z-index: 1;
      user-select: none;
      cursor: e-resize;
      -webkit-user-drag: none;
    }

    .time {
      position: absolute;
      bottom: 40px;
      left: 0;
      z-index: 1;
      padding: 2px 4px;
      font-size: 12px;
      color: #fff;
      background: rgba(0, 0, 0, 1);
      transform: translate(-50%, 100%);
    }

    .slw-bottom {
      width: 100%;
      height: 40px;
    }

    &:hover {
      .slw-title {
        transform: translateY(0%);
      }
      .slw-bottom {
        transform: translateY(0%);
      }
    }

    .action-bar {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100%;
      height: 40px;
      padding: 0 16px;
      transition: all ease-in-out 0.5s;
      background: rgba(46, 53, 75, 1);

      .left {
        display: flex;
        align-items: center;

        .play-status {
          display: flex;
          align-items: center;

          em {
            margin-left: 12px;
            font-style: normal;
            color: #fff;
            font-size: 12px;
          }

          .back-btn {
            padding: 4px 10px;
            border-radius: 6px;
            color: #ddd;
            font-size: 12px;
            cursor: pointer;
            background: #343747;

            &:hover {
              opacity: 0.6;
            }
          }

          .live {
            display: flex;
            align-items: center;
            padding: 2px 5px;
            color: rgba(0,255,0,.8);

            i {
              font-size: 12px;
              font-style: normal;
            }

            .label {
              width: 6px;
              height: 6px;
              margin-right: 12px;
              background: rgba(0,255,0,.8);
              border-radius: 50%;
              position: relative;

              &:after {
                content: "";
                width: 12px;
                height: 12px;
                position: absolute;
                left: 50%;
                top: 50%;
                -webkit-transform: translate(-50%,-50%);
                transform: translate(-50%,-50%);
                border-radius: 50%;
                border: 4px solid rgba(0,255,0,.2);
              }
            }
          }
        }

        .volume {
          display: flex;
          align-items: center;
          position: relative;
          height: 100%;

          .volume-slider {
            display: none;
            position: absolute;
            bottom: 20px;
            left: 50%;
            z-index: -1;
            opacity: 0;
            padding: 20px 0 10px;
            background-color: rgba(0, 0,0,.8);
            transform: translate(-50%, 0);
            transition: all ease 0.3s;

            &.active {
              display: block;
              z-index: 1;
              opacity: 1;
            }
          }
        }

        img {
          cursor: pointer;
        }

        .left-btns {
          display: flex;
          align-items: center;
          margin-right: 10px;

          span {
            flex: 1;
            height: 100%;
            line-height: 24px;
            background: #222838;
            color: #c9c9c9;
            font-size: 12px;
            cursor: pointer;

            &.active {
              color: #fff;
              background: linear-gradient(180deg, #28B2EB 0%, #193D91 100%);
            }
          }
        }
      }

      .right {
        color: #c9c9c9;
        font-size: 12px;

        span {
          margin-right: 32px;
          cursor: pointer;

          &:hover {
            opacity: 0.6;
          }
        }

        img {
          margin-right: 16px;
          cursor: pointer;

          &:last-child {
            margin-right: 0;
          }

          &:hover {
            opacity: 0.6;
          }
        }
      }

      & > div {
        display: flex;
        align-items: center;
      }
    }
  }
</style>