<template>
  <div class="layer">
    <el-button type="primary" plain @click="previewData = getNew()">添加图标</el-button>

    <div class="card">
      <h2>商标</h2>
      <div class="icons">
        <div v-for="icon in icons" :key="icon.id" class="ms-item">
          <img :src="icon.cover" alt="">
          <p>{{icon.text}}</p>
          <a @click="previewData = icon">修改</a>
          <a @click="del(icon)">删除</a>
        </div>
      </div>
    </div>

    <div class="card">
      <h2>活动图集</h2>
      <div class="icons">
        <div v-for="icon in huods" :key="icon.id" class="ms-item">
          <img :src="icon.cover" alt="">
          <p>{{icon.text}}</p>
          <a @click="previewData = icon">修改</a>
          <a @click="del(icon)">删除</a>
        </div>
      </div>
    </div>

    <div class="card">
      <h2>办公环境</h2>
      <div class="icons">
        <div v-for="icon in hjins" :key="icon.id" class="ms-item">
          <img :src="icon.cover" alt="">
          <p>{{icon.text}}</p>
          <a @click="previewData = icon">修改</a>
          <a @click="del(icon)">删除</a>
        </div>
      </div>
    </div>

    <div class="preview" v-if="previewData">
      <div class="preview-layer">
        <Edit :datap="previewData" class="layer" @quit="previewData = null" @submit="insert"/>
      </div>
    </div>

  </div>
</template>

<script>
import edit from './edit'

export default {
  data () {
    return {
      icons: [],
      huods: [],
      hjins: [],
      previewData: null
    }
  },
  methods: {
    getNew () {
      return {
        cover: null,
        zip: null,
        language: '',
        text: '',
        type: ''
      }
    },
    async referData () {
      try {
        let {content} = await this.$http.get('/media')
        this.icons = content.filter(item => item.type === 1)
        this.huods = content.filter(item => item.type === 2)
        this.hjins = content.filter(item => item.type === 3)
      } catch (e) {
        this.$error('服务端发生错误！')
      }
    },
    async insert (data) {
      try {
        if (data.id) {
          await this.$http.put('/media', data)
        } else {
          await this.$http.post('/media', data)
        }
        this.previewData = null
        this.referData()
      } catch (e) {
        this.$error('服务端发生错误！')
      }
    },
    async del (data) {
      if (!confirm('删除后无法恢复，你确定要删除这个图标集吗？')) return

      try {
        await this.$http.delete('/media/' + data.id)
        this.referData()
      } catch (e) {
        this.$error('服务端发生错误！')
      }
    }
  },
  mounted () {
    this.referData()
  },
  components: { Edit: edit }
}
</script>

<style scoped>
@import url('./style.css');
</style>
