<template>
  <CommonPage>
    <template #action>
      <NButton type="primary" @click="handleModalAdd">
        <i class="i-material-symbols:add mr-4 text-18" />
        新增
      </NButton>
    </template>

    <MeCrud ref="$table" v-model:query-items="queryItems" :scroll-x="1200" :columns="columns" :get-data="api.read">
      <MeQueryItem label="分类名称" :label-width="80">
        <n-input v-model:value="queryItems.title" type="text" placeholder="请输入分类名称" clearable>
          <template #password-visible-icon />
        </n-input>
      </MeQueryItem>
      <MeQueryItem label="状态" :label-width="50">
        <n-select
          v-model:value="queryItems.enable" clearable :options="[
            { label: '启用', value: 1 },
            { label: '停用', value: 0 },
          ]"
        />
      </MeQueryItem>
    </MeCrud>

    <MeModal ref="modalRef" width="520px">
      <n-form ref="modalFormRef" label-placement="left" label-align="left" :label-width="80" :model="modalForm">
        <n-form-item
          label="分类名" path="title" :rule="{
            required: true,
            message: '请输入分类名',
            trigger: ['input', 'blur'],
          }"
        >
          <n-input v-model:value="modalForm.title" :maxlength="200" show-count />
        </n-form-item>
        <n-form-item label="上层分类" path="parentId">
          <!-- <n-select v-model:value="modalForm.parentId" :options="allCategory" clearable filterable tag /> -->
          <n-tree-select
            v-model:value="modalForm.parentId" :options="allCategory" label-field="title" key-field="id"
            placeholder="根分类" clearable
          />
        </n-form-item>
        <n-form-item label="备注" path="remark">
          <n-input v-model:value="modalForm.remark" />
        </n-form-item>
        <!-- {{ modalForm.translations }} -->
        <n-tabs v-if="modalForm.translations.length > 0" type="line" animated>
          <template v-for="(lang, index) in langs" :key="lang">
            <n-tab-pane :name="lang" :tab="langLabel[lang]" :index="index">
              <n-form-item
                label="名称" :path="`translations[${index}].title`" :rule="{
                  required: true,
                  message: '请输入名称',
                  trigger: ['input', 'blur'],
                }"
              >
                <n-input
                  v-model:value="modalForm.translations.find(i => i.locale === lang).title" :maxlength="200"
                  show-count
                />
              </n-form-item>

              <n-form-item
                label="备注" path="remark" :rule="{
                  required: false,
                  message: '请输入备注',
                  trigger: ['input', 'blur'],
                }"
              >
                <n-input
                  v-model:value="modalForm.translations.find(i => i.locale === lang).remark" :maxlength="200"
                  show-count type="textarea"
                />
              </n-form-item>
            </n-tab-pane>
          </template>
        </n-tabs>

        <n-form-item label="状态" path="enable">
          <NSwitch v-model:value="modalForm.enable">
            <template #checked>
              启用
            </template>
            <template #unchecked>
              停用
            </template>
          </NSwitch>
        </n-form-item>
      </n-form>
    </MeModal>
  </CommonPage>
</template>

<script setup>
import { MeCrud, MeModal, MeQueryItem } from '@/components'
import { useCrud } from '@/composables'
import { useUserStore } from '@/store/index.js'
import { formatDateTime } from '@/utils'
import { initTranslations, langLabel, langs } from '@/utils/translations'
import { NButton, NSwitch } from 'naive-ui'
import { onMounted, watchEffect } from 'vue'
import api from './api'

defineOptions({ name: 'Category' })

const router = useRouter()
const { userId } = useUserStore()
const $table = ref(null)
/** QueryBar筛选参数（可选） */
const queryItems = ref({})

const { modalRef, modalFormRef, modalAction, modalForm, handleAdd, handleDelete, handleEdit }
  = useCrud({
    name: '分类',
    doCreate: api.create,
    doDelete: api.delete,
    doUpdate: api.update,
    initForm: {
      enable: true,
      translations: initTranslations({}, ['title', 'remark']).translations,
    },
    refresh: (_, keepCurrentPage) => $table.value?.handleSearch(keepCurrentPage),
  })
onMounted(() => {
  $table.value?.handleSearch()
})
watchEffect(() => {
  if (userId) {
    modalForm.value.userId = userId
  }
})
const columns = [
  { title: '分类名称', key: 'title', width: '400' },
  { title: '上级分类', key: 'parent.title' },
  { title: '备注', key: 'remark' },
  { title: '创建人', key: 'user.username' },
  {
    title: '创建时间',
    key: 'createTime',
    render: row => h('span', formatDateTime(row.createTime)),
  },
  {
    title: '状态',
    key: 'enable',
    render: row =>
      h(
        NSwitch,
        {
          size: 'small',
          rubberBand: false,
          value: row.enable,
          loading: !!row.enableLoading,
          disabled: row.code === 'SUPER_ADMIN',
          onUpdateValue: () => handleEnable(row),
        },
        {
          checked: () => '启用',
          unchecked: () => '停用',
        },
      ),
  },
  {
    title: '操作',
    key: 'actions',
    width: 200,
    align: 'center',
    fixed: 'right',
    render(row) {
      return [
        h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            style: 'margin-left: 12px;',
            disabled: row.code === 'SUPER_ADMIN',
            onClick: () => handleFormEdit(row),
          },
          {
            default: () => '编辑',
            icon: () => h('i', { class: 'i-material-symbols:edit-outline text-14' }),
          },
        ),

        h(
          NButton,
          {
            size: 'small',
            type: 'error',
            style: 'margin-left: 12px;',
            disabled: row.code === 'SUPER_ADMIN',
            onClick: () => handleDelete(row.id),
          },
          {
            default: () => '删除',
            icon: () => h('i', { class: 'i-material-symbols:delete-outline text-14' }),
          },
        ),
      ]
    },
  },
]

async function handleEnable(row) {
  row.enableLoading = true
  try {
    await api.update({ id: row.id, enable: !row.enable })
    row.enableLoading = false
    $message.success('操作成功')
    $table.value?.handleSearch()
  }
  catch (error) {
    console.error(error)
    row.enableLoading = false
  }
}

async function handleFormEdit(data = {}) {
  if (data.translations.length === 0) {
    initTranslations(data, ['title', 'remark'])
  }

  handleEdit(data)
}

function handleModalAdd() {
  modalForm.value.translations = []
  setTimeout(() => {
    modalForm.value.translations = initTranslations({}, ['title', 'remark']).translations
  }, 200)
  handleAdd()
  getALLCate()
}

const allCategory = ref([])

function getALLCate() {
  // api.getAll().then(({ data = [] }) => (allCategory.value = data.map(item => ({ label: item.title, value: item.id }))))
  api.getAll().then(({ data = [] }) => (allCategory.value = data))
}
getALLCate()
</script>
