<template>
  <CommonPage>
    <template #action>
      <NButton type="primary" @click="router.push('article/add')">
        <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="50">
        <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>
  </CommonPage>
</template>

<script setup>
import { MeCrud, MeQueryItem } from '@/components'
import { useCrud } from '@/composables'
import { formatDateTime } from '@/utils'
import { NButton, NSwitch } from 'naive-ui'
import api from './api'

defineOptions({ name: 'RoleMgt' })

const router = useRouter()

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

onMounted(() => {
  $table.value?.handleSearch()
})

const { handleDelete }
  = useCrud({
    name: '文章',
    doCreate: api.create,
    doDelete: api.delete,
    doUpdate: api.update,
    initForm: { enable: true },
    refresh: (_, keepCurrentPage) => $table.value?.handleSearch(keepCurrentPage),
  })

const columns = [
  { title: 'ID', key: 'id', width: '80' },
  { title: '标题', key: 'title', width: '200' },
  { title: '分类', key: 'category.title' },
  {
    title: '内容',
    key: 'content',
    width: '400',
    render: row => h('div', htmlspecialchars(row.translations?.length ? row.translations.find(i => i.locale === 'zh').content : row.content)),
  },
  { 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: () => handleEdit(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 {
    console.log('row', row)
    await api.update({ ...row, id: row.id, enable: !row.enable })
    row.enableLoading = false
    $message.success('操作成功')
    $table.value?.handleSearch()
  }
  catch (error) {
    console.error(error)
    row.enableLoading = false
  }
}

function htmlspecialchars(str) {
  const div = document.createElement('div')
  div.innerHTML = str
  const text = div.textContent || ''
  return text.length > 150 ? `${text.substring(0, 150)}...` : text
}

function handleEdit(row) {
  router.push(`/article/edit/${row.id}`)
}
</script>
