<template>
  <table-template :soul="this">
    <template #switch="{ record, index }">
      <a-switch
        :checked="dataSource[index].enabled"
        checked-children="启用"
        un-checked-children="禁用"
        :loading="loadingKeys.includes(record.id)"
        @click="enableChange(record, index)"
        v-if="hasPerm('SYS02102.ENABLE')"
      />
    </template>
    <template #action="{ record }">
      <a-space>
        <a @click="edit(record.id)">编辑</a>
        <a style="color: red" v-if="hasPerm('SYS02102.DELETE')" @click="deleteRow(record.id)">删除</a>
      </a-space>
    </template>
    <template #free>
      <BannerEdit ref="BannerEdit" :success="reset" />
    </template>
  </table-template>
</template>
<script>
import { TableTemplate, TableScript } from '@/components/table'
import { getList, enable, deleteOne } from '@/api/banner'
import dayjs from 'dayjs'
import BannerEdit from './BannerEdit.vue'

const columns = [
  { title: '描述', dataIndex: 'description' },
  { title: '排序号', dataIndex: 'showOrder', width: 120 },
  {
    title: '启用/禁用',
    width: 120,
    scopedSlots: { customRender: 'switch' },
    align: 'center'
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 150,
    customRender: (text) => dayjs(text).format('YYYY-MM-DD HH:mm:ss')
  },
  {
    title: '启用/禁用',
    width: 120,
    scopedSlots: { customRender: 'action' },
    align: 'center'
  }
]

export default {
  name: 'BannerList',
  mixins: [TableScript],
  components: { TableTemplate, BannerEdit },
  data() {
    return {
      columns,
      useYScroll: true,
      pagination: false,
      title: '首页轮播图',
      loadingKeys: [],
      toolbar: [
        {
          text: '新增',
          handler: 'add'
        }
      ]
    }
  },
  methods: {
    queryData: getList,
    add() {
      this.$refs.BannerEdit.show(null)
    },
    edit(id) {
      this.$refs.BannerEdit.show(id)
    },
    deleteRow(id) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '是否删除',
        onOk() {
          deleteOne(id).then(({ code }) => {
            if (code == 200) {
              _this.$message.success('删除成功')
              _this.reset()
            }
          })
        }
      })
    },
    enableChange(record, index) {
      if (this.loadingKeys.includes(record.id)) {
        return
      }
      this.loadingKeys.push(record.id)
      enable({ id: record.id, enabled: !record.enabled })
        .then(({ code }) => {
          if (code == 200) {
            this.$message.success('保存成功')
            this.dataSource[index].enabled = !record.enabled
          }
        })
        .finally(() => {
          this.loadingKeys.splice(this.loadingKeys.indexOf(record.id), 1)
        })
    }
  }
}
</script>