<template>
  <div>
    <div class="gva-table-box">
      <div class="gva-btn-list">
        <el-button type="primary" icon="plus" @click="clickAdd('0')">新增根分类</el-button>
      </div>

      <!-- 由于此处分类跟左侧列表一一对应所以不需要分页 pageSize默认999 -->
      <el-table :data="tableData" row-key="ID">
        <el-table-column align="left" label="ID" min-width="80" prop="ID" />
        <el-table-column align="left" label="分类名称" min-width="200" prop="categoryName">
          <template #default="scope">
            <span>{{ scope.row.title }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="父节点" min-width="90" prop="parentId" />
        <el-table-column align="left" label="排序" min-width="100" prop="sort" />
        <el-table-column align="left" fixed="right" label="操作" width="300">
          <template #default="scope">
            <el-button type="primary" link icon="plus" @click="clickAdd(scope.row.ID)">添加子类</el-button>
            <el-button type="primary" link icon="edit" @click="clickEdit(scope.row.ID)">编辑</el-button>
            <el-button type="primary" link icon="delete" @click="clickDelete(scope.row.ID)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog v-model="dialogFormVisible" :before-close="handleClose" :title="dialogTitle" style="max-width: 400px;">
      <el-form v-if="dialogFormVisible" ref="categoryForm" :inline="true" :model="form" :rules="rules"
        label-position="top" label-width="85px">
        <el-form-item label="分类名称" prop="title" style="width:90%">
          <el-input v-model="form.title" autocomplete="off" />
        </el-form-item>
        <el-form-item label="父节点ID" style="width:90%">
          <el-cascader v-model="form.parentId" style="width:100%" :disabled="!isEdit" :options="categoryOption"
            :props="{ checkStrictly: true, label: 'title', value: 'ID', disabled: 'disabled', emitPath: false }"
            :show-all-levels="false" filterable />
        </el-form-item>
        <el-form-item label="排序" prop="sort" style="width:90%">
          <el-input v-model.number="form.sort" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="enterDialog">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

import {
  getCategoryTree,
  addCategory,
  updateCategory,
  deleteCategory,
  getCategoryById
} from '@/api/category'

import WarningBar from '@/components/warningBar/warningBar.vue'

const rules = reactive({
  title: [
    { required: true, message: '请输入分类名称', trigger: 'blur' }
  ],
})

const tableData = ref([])

// 查询
const getTableData = async () => {
  const res = await getCategoryTree()
  if (res.code === 0) {
    tableData.value = res.data.categoryTree
  }
}

getTableData()

const categoryOption = ref([
  {
    ID: '0',
    title: '根分类'
  }
])
const setOptions = () => {
  categoryOption.value = [
    {
      ID: '0',
      title: '根分类'
    }
  ]
  setCategoryOptions(tableData.value, categoryOption.value, false)
}
const setCategoryOptions = (categoryData, optionsData, disabled) => {
  categoryData &&
    categoryData.forEach(item => {
      if (item.children && item.children.length) {
        const option = {
          title: item.title,
          ID: String(item.ID),
          disabled: disabled || item.ID === form.value.ID,
          children: []
        }
        setCategoryOptions(
          item.children,
          option.children,
          disabled || item.ID === form.value.ID
        )
        optionsData.push(option)
      } else {
        const option = {
          title: item.title,
          ID: String(item.ID),
          disabled: disabled || item.ID === form.value.ID
        }
        optionsData.push(option)
      }
    })
}

const form = ref({
  ID: 0,
  parentId: '',
  title: '',
  sort: '',
})

// 添加
const enterDialog = async () => {
  categoryForm.value.validate(async valid => {
    if (valid) {
      let res
      if (isEdit.value) {
        res = await updateCategory(form.value)
      } else {
        res = await addCategory(form.value)
      }
      if (res.code === 0) {
        ElMessage({
          type: 'success',
          message: isEdit.value ? '编辑成功' : '添加成功!'
        })
        getTableData()
      }
      initForm()
      dialogFormVisible.value = false
    }
  })
}

// 初始化弹窗内表格方法
const categoryForm = ref(null)
const initForm = () => {
  categoryForm.value.resetFields()
  form.value = {
    ID: 0,
    parentId: '',
    title: '',
    sort: '',
  }
}
const handleClose = (done) => {
  initForm()
  done()
}

// 关闭弹窗
const dialogFormVisible = ref(false)
const closeDialog = () => {
  initForm()
  dialogFormVisible.value = false
}

// 删除
const clickDelete = (ID) => {
  ElMessageBox.confirm('此操作将永久删除分类, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const res = await deleteCategory({ ID })
      if (res.code === 0) {
        ElMessage({
          type: 'success',
          message: '删除成功!'
        })
        if (tableData.value.length === 1 && page.value > 1) {
          page.value--
        }
        getTableData()
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除'
      })
    })
}

// 添加方法，id为 0则为添加根
const isEdit = ref(false)
const dialogTitle = ref('新增分类')
const clickAdd = (id) => {
  dialogTitle.value = '新增分类'
  form.value.parentId = String(id)
  isEdit.value = false
  setOptions()
  dialogFormVisible.value = true
}
// 修改方法
const clickEdit = async (ID) => {
  dialogTitle.value = '编辑分类'
  const res = await getCategoryById({ ID })
  form.value = res.data.category
  isEdit.value = true
  setOptions()
  dialogFormVisible.value = true
}

</script>
@/api/category