<template>
  <div class="pa-4 layout-editor">
    <div class="d-flex align-center justify-space-between mb-4">
      <div>
        <div class="text-h5 font-weight-medium">编辑工作台布局</div>
        <div class="text-body-2 grey--text mt-1">可调整标准组件的顺序和显示状态，配置按当前用户保存在浏览器中。</div>
      </div>
      <div>
        <v-btn text class="mr-2" @click="$router.push('/home')">取消</v-btn>
        <v-btn color="primary" @click="save">保存</v-btn>
      </div>
    </div>

    <v-card outlined>
      <v-list two-line>
        <template v-for="(item, index) in layout">
          <v-list-item :key="item.id">
            <v-list-item-avatar :color="widget(item.id).color">
              <v-icon dark>{{ widget(item.id).icon }}</v-icon>
            </v-list-item-avatar>
            <v-list-item-content>
              <v-list-item-title>{{ widget(item.id).title }}</v-list-item-title>
              <v-list-item-subtitle>{{ widget(item.id).description }}</v-list-item-subtitle>
            </v-list-item-content>
            <v-list-item-action class="d-flex flex-row align-center">
              <v-btn icon :disabled="index === 0" @click="move(index, -1)">
                <v-icon>mdi-arrow-up</v-icon>
              </v-btn>
              <v-btn icon :disabled="index === layout.length - 1" @click="move(index, 1)">
                <v-icon>mdi-arrow-down</v-icon>
              </v-btn>
              <v-switch v-model="item.enabled" class="ml-3" hide-details inset />
            </v-list-item-action>
          </v-list-item>
          <v-divider v-if="index < layout.length - 1" :key="`${item.id}-divider`" />
        </template>
      </v-list>
    </v-card>
  </div>
</template>

<script>
import { loadWorkbenchLayout, saveWorkbenchLayout, STANDARD_WIDGETS } from './workbench'

export default {
  name: 'home-edit',
  data () {
    return {
      layout: []
    }
  },
  computed: {
    username () {
      const info = this.$store.getters.userInfo || {}
      return info.username || (info.user && info.user.username) || 'anonymous'
    }
  },
  created () {
    this.layout = loadWorkbenchLayout(this.username)
  },
  methods: {
    widget (id) {
      return STANDARD_WIDGETS.find(item => item.id === id) || {}
    },
    move (index, offset) {
      const target = index + offset
      if (target < 0 || target >= this.layout.length) return
      const next = [...this.layout]
      const current = next[index]
      this.$set(next, index, next[target])
      this.$set(next, target, current)
      this.layout = next
    },
    save () {
      saveWorkbenchLayout(this.username, this.layout)
      this.$snackbar.success('工作台布局已保存')
      this.$router.push('/home')
    }
  }
}
</script>

<style lang="scss" scoped>
.layout-editor {
  min-height: 100%;
  background: #f7f9fc;
}
</style>
