<template>
  <div class="list">
    <template v-if="list.length">
      <card
        v-for="item in list"
        :data="item"
        :key="item.id"
        v-bind="page.card"
        @remove="onRemove"
      ></card>
    </template>
    <div class="empty" v-else>{{ page.emptyText }}</div>
    <div class="fixed-box">
      <div class="fixed-inner">
        <div class="fixed-button" @click="toCreatePage">
          {{ page.buttonText }}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import pages from '@/pages'
import Card from '@/components/Card.vue'
import * as api from '@/api/index'

export default {
  components: { Card },
  metaInfo() {
    return {
      title: this.page.title
    }
  },
  data() {
    return {
      list: []
    }
  },
  watch: {
    $route: {
      immediate: true,
      deep: true,
      handler(route) {
        if (!route.query.channel) {
          this.$dialog
            .alert({
              message: '请选择事务'
            })
            .then(() => {
              this.$router.replace({
                name: 'channel',
                query: this.$route.query
              })
            })
        }
      }
    }
  },
  computed: {
    // 页面配置
    page() {
      const channel = this.$route.query.channel
      return pages[channel] ? pages[channel]['list'] : {}
    },
    channelId() {
      return this.$route.query.channel_id
    }
  },
  methods: {
    getList() {
      const toast = this.$toast.loading({
        message: '加载中...',
        forbidClick: true,
        duration: 0
      })
      api.getAffairList({ affair_id: this.channelId }).then(response => {
        this.list = response
        toast.clear()
      })
    },
    onLoad() {
      this.getList()
    },
    toCreatePage() {
      this.$router.push({ name: 'create', query: this.$route.query })
    },
    onRemove(data) {
      this.$dialog
        .confirm({
          confirmButtonText: '确定',
          message: '确定要删除吗？'
        })
        .then(() => {
          api.deleteAffair(data.id).then(() => {
            this.getList()
          })
        })
        .catch(() => {
          // on cancel
        })
    }
  },
  beforeMount() {
    this.getList()
  }
}
</script>

<style lang="scss">
.list {
}
</style>
