<script setup>
import { ElMessageBox, ElMessage } from 'element-plus'
import { getCategoryList, deleteCategory } from '../api'
import { useMapStore } from '@/stores/map'
import { getNameByValue } from '@/utils/dictionary'

const FormDialog = defineAsyncComponent(() => import('../components/FormDialog.vue'))

const statusList = useMapStore().getMapValuesByKey('system_status')

const appList = ref(null)
// 刷新
const handleRefresh = () => {
  appList.value?.refetch()
}
// 列表配置
const listOptions = {
  hasPagination: false,
  remote: {
    httpRequest: getCategoryList,
    callback(data) {
      return { list: data.trees }
    },
  },
  filters: [{ label: '商品品类名称', prop: 'name', type: 'input', placeholder: '请输入类别名称' }],
  columns: [
    { label: '商品品类名称', prop: 'name', align: 'left' },
    { label: '层级', prop: 'level' },
    {
      label: '状态',
      prop: 'status',
      computed({ row }) {
        const color = row.status === '1' ? 'var(--main-success-color)' : 'var(--main-color)'
        return `<span style="color: ${color}">${getNameByValue(row.status, statusList)}</span>`
      },
    },
    { label: '操作', slots: 'table-x', width: 160 },
  ],
}

const formVisible = ref(false)
const currentRow = ref(null)

// 新建
const handleAdd = (row) => {
  formVisible.value = true
  currentRow.value = row || { pid: 0 }
}
// 编辑
const handleUpdate = (row) => {
  formVisible.value = true
  currentRow.value = row
}
const handleRemove = async (row) => {
  await ElMessageBox.confirm('此操作将永久删除该数据, 是否继续?', '提示')
  await deleteCategory({ id: row.id })
  ElMessage.success('删除成功')
  appList.value?.refetch()
}
</script>

<template>
  <AppCard title="商品品类管理">
    <AppList v-bind="listOptions" row-key="id" ref="appList">
      <template #header-buttons>
        <el-button type="primary" @click="handleAdd()">新增类别</el-button>
      </template>
      <template #table-x="{ row }">
        <el-button text type="primary" @click="handleAdd({ pid: row.id })" v-if="row.level != 4">新增</el-button>
        <el-button text type="primary" @click="handleUpdate(row)">编辑</el-button>
        <el-button text type="primary" @click="handleRemove(row)">删除</el-button>
      </template>
    </AppList>
  </AppCard>
  <!-- 新建/修改 -->
  <FormDialog v-model="formVisible" :data="currentRow" @update="handleRefresh" v-if="formVisible" />
</template>
