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

    <n-flex class="flex" justify="justify-center" size="large">
      <template v-for="(item) of topMenu" :key="item.id">
        <n-card class="min-h-220 min-w-200 w-32%" :title="item.title">
          <div class="ml-20 flex-col">
            <!-- {{ item.children.length }} -->
            <template v-if="item.children.length > 0">
              <n-grid x-gap="12" :cols="item.grid || 3">
                <n-gi v-for="(child) of item.children" :key="child.id">
                  <n-card :bordered="false" size="small">
                    <template #cover>
                      <!-- <div style="width: 100%;height: 50px;overflow: hidden;"> -->
                      <n-image
                        preview-disabled :src="child.cover" object-fit="scale-down"
                        style="width: 100%;height: 50px;overflow: hidden;"
                      />
                      <!-- </div> -->
                    </template>
                    <div class="text-center text-12">
                      {{ child.title }}
                    </div>
                  </n-card>
                </n-gi>
              </n-grid>
            </template>
            <template v-else>
              <div class="mt-20 min-h-150 flex items-center justify-center text-center">
                暂没子菜单
              </div>
            </template>
          </div>
          <template #header-extra>
            <n-dropdown
              class="menu_dropdown" trigger="click" :options="options" :show-arrow="true"
              @select="(key) => handleSelect(key, item)"
            >
              <n-button text>
                <i class="i-material-symbols:more-horiz text-24" />
              </n-button>
            </n-dropdown>
          </template>
        </n-card>
      </template>
    </n-flex>

    <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="description" :rule="{
            required: false,
            message: '请输入描述',
            trigger: ['input', 'blur'],
          }"
        >
          <n-input v-model:value="modalForm.description" :maxlength="200" show-count type="textarea" />
        </n-form-item>
        <n-form-item
          label="样式类型" path="styleType" :rule="{
            required: true,
            type: 'number',
            message: '请输入样式类型',
            trigger: ['input', 'blur'],
          }"
        >
          <n-select v-model:value="modalForm.styleType" :options="styleEnum" clearable filterable tag />
        </n-form-item>
        <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="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="description" :rule="{
                  required: false,
                  message: '请输入描述',
                  trigger: ['input', 'blur'],
                }"
              >
                <n-input
                  v-model:value="modalForm.translations.find(i => i.locale === lang).description" :maxlength="200" show-count
                  type="textarea"
                />
              </n-form-item>
            </n-tab-pane>
          </template>
        </n-tabs>
        <n-form-item label="备注" path="remark">
          <n-input v-model:value="modalForm.remark" />
        </n-form-item>
        <!-- <n-form-item label="是否显示" path="isPublish">
          <NSwitch v-model:value="modalForm.isPublish">
            <template #checked>
              启用
            </template>
            <template #unchecked>
              停用
            </template>
          </NSwitch>
        </n-form-item> -->
        <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 { MeModal } from '@/components'
import { useCrud } from '@/composables'
import { useUserStore } from '@/store/index.js'
import { styleEnum } from '@/utils/enum.js'
import { initTranslations, langLabel, langs } from '@/utils/translations'
import { onMounted } from 'vue'
import { useRouter } from 'vue-router'
import MenuApi from './api.js'

const router = useRouter()
const topMenu = ref([])
const { userId } = useUserStore()
const $table = ref(null)

console.log('styleEnum', styleEnum)
/** QueryBar筛选参数（可选） */
const queryItems = ref({})

const { modalRef, modalFormRef, modalAction, modalForm, handleAdd, handleDelete, handleEdit }
  = useCrud({
    name: '菜单',
    doCreate: MenuApi.create,
    doDelete: MenuApi.delete,
    doUpdate: MenuApi.update,
    initForm: {
      enable: true,
      isPublish: true,
      translations: initTranslations({}, ['title', 'remark']).translations,
    },
    refresh: (_, keepCurrentPage) => $table.value?.handleSearch(keepCurrentPage),
  })
onMounted(() => {
  $table.value?.handleSearch()
  getTopMenuList()
})

watchEffect(() => {
  if (userId) {
    modalForm.value.userId = userId
    modalForm.value.level = 0
  }
})
const options = [
  {
    label: '编辑',
    key: 'edit',
  },
  {
    label: '删除',
    key: 'delete',
  },
]

function handleSelect(key, item) {
  const { id } = item
  switch (key) {
    case 'edit':
      handleTopMenuEdit(id)
      break
    case 'delete':
      handleTopMenuDelete(id)
      break
  }
}

async function handleTopMenuDelete(id) {
  $dialog.confirm({
    content: '确认删除？',
    async confirm() {
      const res = await MenuApi.delete(id)
      if (res.code === 0) {
        $message.success('操作成功！')
        getTopMenuList()
      }
    },
    cancel() {
      $message.warning('已取消')
    },
  })
}

async function handleTopMenuEdit(id) {
  console.log('id', id)
  router.push(`/menu/list/${id}`)
}

function getTopMenuList() {
  MenuApi.getLevel(0).then(({ data = [] }) => (topMenu.value = data))
}

function handleAddMenu() {
  handleAdd(null, null, () => {
    getTopMenuList()
  })
}
</script>

<style>
.menu_dropdown .n-dropdown-option:nth-child(2) .n-dropdown-option-body__label {
  color: red;
  /* display: none; */
}
</style>
