<template>
  <TableLayout
    :authorized="$hasPermissions([`cms:category:query`])"
    :fullscreen="fullscreen"
  >
    <!-- 表格和分页 -->
    <template #table-wrap>
      <SearchTable
        v-loading="isWorking.search"
        row-key="id"
        :default-expand-all="true"
        :data="tableData.list"
        v-model:fullscreen="fullscreen"
        buttons-width="255px"
        @selection-change="handleSelectionChange"
        @refresh="refresh"
      >
        <template
          v-if="$hasAnyPermissions([
            'cms:category:create',
            'cms:category:delete'
          ])"
          #toolbar
        >
          <el-button
            v-permissions="['cms:category:create']"
            type="primary"
            icon="Plus"
            @click="$refs.operaCategoryWindow.open('新建栏目')"
          >新建</el-button>
          <el-button
            v-permissions="['cms:category:delete']"
            type="danger"
            icon="Delete"
            @click="deleteByIdInBatch"
          >删除</el-button>
        </template>
        <el-table-column type="selection" fixed="left" width="55"/>
        <el-table-column prop="title" label="栏目标题" min-width="120px">
          <template #default="{ row }">
            <CategoryIcon :value="row.icon" size="13px" :with-holder="false"/>
            <label>{{ row.title }}</label>
          </template>
        </el-table-column>
        <el-table-column prop="uid" label="唯一标识" min-width="100px"/>
        <el-table-column prop="type" label="栏目类型" min-width="100px">
          <template #default="{ row }">
            {{ $d(`CATEGORY_TYPES.${row.type}`) }}
          </template>
        </el-table-column>
        <el-table-column prop="uri" label="链接地址" min-width="150px">
          <template #default="{ row }">
            <PopoverCellValue :content="row.uri"/>
          </template>
        </el-table-column>
        <el-table-column prop="permission" label="权限码" min-width="150px"/>
        <el-table-column prop="hidden" label="状态" min-width="100px">
          <template #default="{ row }">
            <el-switch
              v-model="row.hidden"
              :active-value="false"
              :inactive-value="true"
              @change="switchHidden(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" min-width="100px"/>
        <el-table-column prop="config" label="栏目配置" min-width="200px">
          <template #default="{ row }">
            <PopoverCellValue :content="row.config"/>
          </template>
        </el-table-column>
        <el-table-column prop="creatorRealName" label="创建人姓名" min-width="100px"/>
        <el-table-column prop="createdAt" label="创建时间" min-width="185px"/>
        <el-table-column prop="updaterRealName" label="更新人姓名" min-width="100px"/>
        <el-table-column prop="updatedAt" label="更新时间" min-width="185px"/>
        <template
          v-if="$hasAnyPermissions([
            'cms:category:update',
            'cms:category:delete'
          ])"
          #buttons="{ row }"
        >
          <el-button
            v-if="row.type === $const.CATEGORY_TYPE.DEFAULT && $hasPermissions(['cms:category:create'])"
            type="primary"
            icon="Plus"
            link
            @click="$refs.operaCategoryWindow.open('新建子栏目', null, row)"
          >新建子栏目</el-button>
          <el-button
            type="primary"
            icon="EditPen"
            v-permissions="['cms:category:update']"
            link
            @click="$refs.operaCategoryWindow.open(`编辑${row.title}`, row)"
          >编辑</el-button>
          <el-button
            type="danger"
            icon="Delete"
            v-permissions="['cms:category:delete']"
            link
            @click="deleteById(row)"
          >删除</el-button>
        </template>
      </SearchTable>
    </template>
    <!-- 新建编辑窗口 -->
    <OperaCategoryWindow
      ref="operaCategoryWindow"
      @success="refresh"
    />
  </TableLayout>
</template>

<script>
import BaseTable from '@/components/base/BaseTable'
import OperaCategoryWindow from '@/components/cms/category/OperaCategoryWindow'
import CategoryIcon from '@/components/cms/category/CategoryIcon'
import { deleteById, deleteByIdInBatch, updateStatus } from '@/api/cms/category'

export default {
  extends: BaseTable,
  components: { OperaCategoryWindow, CategoryIcon },
  data () {
    return {
    }
  },
  methods: {
    /**
     * 隐藏/显示
     *
     * @param row 行对象
     */
    switchHidden (row) {
      const newValue = row.hidden
      row.hidden = !row.hidden
      // 显示
      if (!newValue) {
        this.__updateStatus(row, newValue)
        return
      }
      // 隐藏
      this.$dialog.disableConfirm(`确认隐藏 ${row.title} 栏目吗？`, {
        title: '隐藏提醒',
        confirmButtonText: '确认隐藏'
      })
        .then(() => {
          this.__updateStatus(row, newValue)
        })
        .catch(() => {
        })
    },
    /**
     * 删除（点击行操作/删除时触发）
     *
     * @param row 行对象
     */
    deleteById (row) {
      this.$dialog.deleteConfirm(`确认删除 ${row.title} 栏目及栏目下的所有文章吗?`)
        .then(() => {
          this.isWorking.delete = true
          return deleteById(row[this.configData['field.id']])
        })
        .then(() => {
          this.__afterDelete()
        })
        .catch(e => {
          this.$tip.apiFailed(e)
        })
        .finally(() => {
          this.isWorking.delete = false
        })
    },
    /**
     * 批量删除（点击批量删除时触发）
     */
    deleteByIdInBatch () {
      if (this.tableData.selectedRows.length === 0) {
        this.$tip.warning('请至少选择一条栏目')
        return
      }
      this.$dialog.deleteConfirm(`确认删除已选中的 ${this.tableData.selectedRows.length} 条栏目及栏目下的所有文章吗?`)
        .then(() => {
          this.isWorking.delete = true
          return deleteByIdInBatch(this.tableData.selectedRows.map(row => row.id).join(','))
        })
        .then(() => {
          this.__afterDelete(this.tableData.selectedRows.length)
        })
        .catch(e => {
          this.$tip.apiFailed(e)
        })
        .finally(() => {
          this.isWorking.delete = false
        })
    },
    /**
     * 修改状态
     *
     * @param row 行对象
     * @param newValue 新值
     * @private
     */
    __updateStatus (row, newValue) {
      updateStatus({
        id: row.id,
        hidden: newValue
      })
        .then(() => {
          row.hidden = newValue
          this.$tip.apiSuccess('修改成功')
        })
        .catch(e => {
          this.$tip.apiFailed(e)
        })
    }
  },
  async created () {
    this.config({
      module: '栏目',
      api: await import('@/api/cms/category')
    })
    this.search()
  }
}
</script>
<style scoped lang="scss">
:deep(.el-table__cell) {
  .category-icon {
    margin-right: 3px;
  }
}
</style>
