<template>
  <el-dialog
    :visible.sync="isPreviewing"
    custom-class="c-dialog--preview program"
    :before-close="onCloseDialog"
    :close-on-click-modal="false"
    append-to-body
    v-on="$attrs"
    @closed="onClosed"
  >
    <program
      v-if="program"
      :program="program"
    />
    <i
      class="l-flex__none c-dialog--preview__close has-active el-icon-close u-bold u-pointer"
      @click="onCloseDialog"
    />
  </el-dialog>
</template>

<script>
import { getProgram } from '@/api/program'
import Program from '@/views/bigscreen/ast/Previewer'

export default {
  name: 'ProgramDialog',
  components: {
    Program
  },
  inheritAttrs: false,
  data () {
    return {
      program: null,
      isPreviewing: false
    }
  },
  methods: {
    show (id) {
      const loading = this.$showLoading()
      getProgram(id).then(({ data }) => {
        try {
          const { id, status, name, resolutionRatio, itemJsonStr } = data
          const [width, height] = resolutionRatio.split('x')
          if (!width || !height) {
            this.showMessage('error', '布局分辨率异常，请联系管理员')
            return
          }

          this.program = {
            id, status, name, resolutionRatio,
            detail: {
              width: Number(width),
              height: Number(height),
              ...JSON.parse(itemJsonStr)
            }
          }
          this.isPreviewing = true
        } catch (e) {
          this.showMessage('error', '布局解析失败')
        }
      }).finally(() => {
        this.$closeLoading(loading)
      })
    },
    onCloseDialog () {
      this.isPreviewing = false
    },
    showMessage (type, message) {
      this.$message({ type, message })
    },
    onClosed () {
      this.program = null
    }
  }
}
</script>
