<template>
  <CommonPage show-footer :title="$route.title">
    <n-button v-perms="['/admin/store/classify/edit']" type="primary" @click="handleAdd(1)">
      新增商户分类
    </n-button>
    <!-- {{ formValue }} -->
    <n-data-table
      :loading="loading"
      :columns="columns"
      :data="data"
      :pagination="pagination"
      :bordered="false"
      remote
      :row-key="rowKey"
      children-key="Classify"
    />
    <n-modal v-model:show="showModal">
      <n-card
        style="width: 400px"
        :title="modelTitle"
        :bordered="false"
        size="huge"
        role="dialog"
        aria-modal="true"
      >
        <n-form ref="formRef" label-placement="left" :model="formValue" :rules="rules">
          <n-form-item label="分类图标：" path="icon">
            <Upload v-model:list="formValue.icon" />
          </n-form-item>
          <n-form-item label="分类名称：" path="name">
            <n-input v-model:value="formValue.name" placeholder="请输入商户分类名称" />
          </n-form-item>
          <n-form-item label="分类状态：" path="status">
            <n-switch v-model:value="formValue.status" :checked-value="1" :unchecked-value="2" />
          </n-form-item>
          <n-form-item>
            <div class="m-auto">
              <n-button
                class="m-auto"
                type="primary"
                attr-type="button"
                @click="handleValidateClick"
              >
                提交
              </n-button>
              <n-button class="ml-10" @click="clear">取消</n-button>
            </div>
          </n-form-item>
        </n-form>
      </n-card>
    </n-modal>
  </CommonPage>
</template>

<script setup>
import { onMounted, h, withDirectives, resolveDirective } from 'vue'
import api from './api'
import { NButton } from 'naive-ui'
import Upload from '@/components/Upload.vue'

const vPerms = resolveDirective('perms')

const loading = ref(false)

const rowKey = (row) => {
  return row.Classify || []
}

const columns = ref([
  {
    title: 'ID',
    align: 'center',
    key: 'ID',
  },
  {
    title: '分类名称',
    align: 'center',
    key: 'name',
  },
  {
    title: '状态',
    align: 'center',
    slot: 'status',
    render(row) {
      return h('span', row.status === 1 ? '正常' : '禁用')
    },
  },
  {
    title: '操作',
    align: 'center',
    slot: 'action',
    render(row) {
      return [
        withDirectives(
          h(
            NButton,
            {
              type: 'primary',
              size: 'small',
              onClick: () => {
                formValue.value = {
                  ...row,
                  icon:
                    row.icon.length > 0
                      ? [
                          {
                            url: row.icon,
                            name: '图片',
                            status: 'finished',
                          },
                        ]
                      : [],
                }
                handleAdd(2)
              },
            },
            () => '编辑'
          ),
          [[vPerms, ['/admin/store/classify/edit']]]
        ),
      ]
    },
  },
])

const data = ref([])

const formRef = ref(null)

const rules = {
  name: {
    required: true,
    message: '请输入商户分类名称',
  },
  icon: {
    required: true,
    type: 'array',
    message: '请上传分类图标',
  },
}

const formValue = ref({
  ID: 0,
  name: '',
  status: 1,
  icon: [],
})

const showModal = ref(false)

const pagination = ref({
  page: 1,
  pageSize: 10,
  itemCount: 0,
  onChange: (page) => {
    pagination.value.page = page
    getList()
  },
  onUpdatePageSize: (pageSize) => {
    pagination.value.pageSize = pageSize
    pagination.value.page = 1
    getList()
  },
})

onMounted(() => {
  getList()
})

const getList = async () => {
  loading.value = true
  try {
    const res = await api.getList({
      pageNum: pagination.value.page,
      pageSize: pagination.value.pageSize,
    })
    data.value = res.data.data
    pagination.value.itemCount = res.data.total
  } catch (error) {
    $message.error(error.msg)
  }
  loading.value = false
}

const modelTitle = ref('')

const handleAdd = (e) => {
  modelTitle.value = e === 1 ? '新增商户分类' : '编辑商户分类'
  showModal.value = true
}

const clear = () => {
  formValue.value = {
    ID: 0,
    name: '',
    status: 1,
    icon: [],
  }
  showModal.value = false
}

const handleValidateClick = async (e) => {
  e.preventDefault()
  formRef.value?.validate(async (errors) => {
    if (!errors) {
      try {
        await api.addClass({
          ...formValue.value,
          icon: formValue.value.icon[0].url,
        })
        $message.success('成功')
        clear()
        getList()
      } catch (error) {
        $message.error(error.msg)
      }
    } else {
      $message.error('Invalid')
    }
  })
}
</script>

<style lang="scss" scoped></style>
