<template>
  <wrapper
    fill
    margin
    padding
    background
  >
    <el-tabs
      :value="active"
      class="c-tabs has-bottom-padding"
      @tab-click="onTabClick"
    >
      <el-tab-pane name="0">
        <template #label>
          <div class="o-tab">
            <i
              class="o-tab__icon el-icon-circle-plus-outline"
              @click.stop="onAdd"
            />
            待提交
          </div>
        </template>
      </el-tab-pane>
      <el-tab-pane
        label="已审核"
        name="2"
      />
      <el-tab-pane
        label="待审核"
        name="1"
      />
    </el-tabs>
    <grid-table
      ref="table"
      :schema="schema"
    >
      <grid-table-item v-slot="item">
        <program
          :key="item.id"
          :program="item"
        >
          <div
            v-if="item.status === 0"
            @click="onSubmit(item)"
          >
            提交
          </div>
          <div
            v-else
            @click="onCopy(item)"
          >
            复制
          </div>
          <div
            v-if="item.del"
            @click="onDel(item)"
          >
            删除
          </div>
        </program>
      </grid-table-item>
    </grid-table>
    <confirm-dialog
      ref="addDialog"
      title="新增节目"
      @confirm="onConfirmAdd"
    >
      <div class="c-grid-form u-align-self--center">
        <span class="c-grid-form__label required">名称：</span>
        <el-input
          v-model.trim="program.name"
          placeholder="最多50个字符"
          maxlength="50"
          clearable
        />
        <span class="c-grid-form__label required">分辨率：</span>
        <schema-select
          v-model="program.resolutionRatio"
          placeholder="请选择分辨率"
          :schema="resolutionRatioSelectSchema"
        />
      </div>
    </confirm-dialog>
    <confirm-dialog
      ref="copyDialog"
      title="复制节目"
      @confirm="onConfirmCopy"
    >
      <div class="c-grid-form u-align-self--center">
        <span class="c-grid-form__label required">名称：</span>
        <el-input
          v-model.trim="copyProgram.name"
          placeholder="最多50个字符"
          maxlength="50"
          clearable
        />
      </div>
    </confirm-dialog>
  </wrapper>
</template>

<script>
import { getRatiosWithUser } from '@/api/device'
import {
  addProgram,
  getProgram,
  submitProgram,
  copyProgram
} from '@/api/program'
import { State } from '@/constant'
import { validate } from './ast/core/utils'
import mixin from './mixin'

export default {
  name: 'ProgramDesigner',
  mixins: [mixin],
  data () {
    return {
      active: `${this.status}`,
      resolutionRatioSelectSchema: { remote: getRatiosWithUser },
      program: {},
      copyProgram: {
        id: null,
        name: ''
      }
    }
  },
  created () {
    window.addEventListener('message', this.onMessage)
  },
  beforeDestroy () {
    window.removeEventListener('message', this.onMessage)
  },
  methods: {
    onTabClick ({ name: active }) {
      if (this.active !== active) {
        this.active = active
        this.$refs.table.mergeCondition({ status: Number(active) })
      }
    },
    onMessage (event) {
      if (!this.loading) {
        const id = event.data?.id
        if (id) {
          const program = this.$refs.table.getData().find(program => program.id === id)
          if (program) {
            program.img = event.data.base64
          }
        }
      }
    },
    onAdd () {
      this.program = {
        name: '',
        resolutionRatio: ''
      }
      this.$refs.addDialog.show()
    },
    onConfirmAdd (done) {
      if (!this.program.name) {
        this.$message({
          type: 'warning',
          message: '名称不能为空'
        })
        return
      }
      if (!this.program.resolutionRatio) {
        this.$message({
          type: 'warning',
          message: '请选择分辨率'
        })
        return
      }
      addProgram(this.program).then(({ data: id }) => {
        done()
        this.active = `${State.READY}`
        this.$refs.table.resetCondition({ status: State.READY, name: this.program.name })
        setTimeout(() => {
          window.open(this.$router.resolve({
            name: 'program',
            params: { id }
          }).href, '_blank')
        }, 500)
      })
    },
    onSubmit (item) {
      const loading = this.$showLoading()
      getProgram(item.id).then(({ data }) => {
        const { itemJsonStr } = data
        if (!itemJsonStr) {
          this.$message({
            type: 'warning',
            message: `请先编辑节目`
          })
          return
        }
        try {
          const error = validate(JSON.parse(itemJsonStr))
          if (error) {
            this.$message({
              type: 'warning',
              message: error
            })
            return
          }
        } catch (e) {
          this.$message({
            type: 'warning',
            message: `节目数据异常`
          })
          return
        }
        submitProgram(item).then(() => {
          this.$refs.table.decrease(1)
        })
      }).finally(() => {
        this.$closeLoading(loading)
      })
    },
    onCopy ({ id, name }) {
      this.copyProgram = { id, name }
      this.$refs.copyDialog.show()
    },
    onConfirmCopy (done) {
      const { id, name } = this.copyProgram
      copyProgram({ id }, name).then(() => {
        done()
        this.active = `${State.READY}`
        this.$refs.table.resetCondition({ status: State.READY, name })
      })
    }
  }
}
</script>
