<script setup>
import { h, ref, resolveDirective, withDirectives } from 'vue'
import api from '../api'
import { NTag, NImage, NButton, NDropdown } from 'naive-ui'
import Upload from '@/components/Upload.vue'
import Editor from '@/components/Editor.vue'
import { useRouter } from 'vue-router'

const vPerms = resolveDirective('perms')

const loading = ref(false)

const showModal = ref(false)

const columns = ref([
  {
    title: '游戏封面',
    align: 'center',
    slot: 'cover',
    render: (row) => {
      return h(NImage, {
        width: '50',
        src: row.cover,
      })
    },
  },
  {
    title: '游戏名称',
    align: 'center',
    key: 'name',
  },
  {
    title: '是否开启',
    align: 'center',
    slot: 'status',
    render: (row) => {
      return h(
        NTag,
        {
          type: row.status === 1 ? 'success' : 'warning',
        },
        {
          default: () => (row.status === 1 ? '开启' : '禁用'),
        }
      )
    },
  },
  {
    title: '操作',
    align: 'center',
    slot: 'action',
    render: (row) => {
      return [
        withDirectives(
          h(
            NButton,
            {
              type: 'primary',
              text: true,
              size: 'small',
              onClick: () => {
                openModal(2, row)
              },
            },
            () => '编辑'
          ),
          [[vPerms, ['/admin/game/edit']]]
        ),
        withDirectives(
          h(
            'span',
            {
              class: 'ml-10',
            },
            {
              default: () => [
                h(
                  NDropdown,
                  {
                    trigger: 'click',
                    size: 'small',
                    options: [
                      {
                        key: 0,
                        label: '实时数据',
                      },
                      {
                        key: 1,
                        label: '数据统计',
                      },
                      {
                        key: 2,
                        label: '宙斯统计',
                      },
                    ],
                    onSelect: (e) => dropdownSelect(e),
                  },
                  {
                    default: () =>
                      h(
                        NButton,
                        {
                          class: 'ml-5',
                          type: 'primary',
                          text: true,
                          size: 'small',
                        },
                        {
                          default: () => '操作',
                        }
                      ),
                  }
                ),
              ],
            }
          ),
          [[vPerms, ['待定']]]
        ),
      ]
    },
  },
])

const data = ref([])

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

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

const getList = async () => {
  const res = await api.getGameList({
    pageSize: pagination.value.pageSize,
    pageNum: pagination.value.page,
  })
  data.value = res.data.data || []
  pagination.value.itemCount = res.data.total
}

const openModal = (type = null, row) => {
  if (type) {
    model.value = {
      ...row,
      cover: row.cover ? [{ url: row.cover, name: '图片', status: 'finished' }] : [],
    }
  }
  showModal.value = true
}

const formRef = ref(null)

const rules = {
  cover: {
    required: true,
    type: 'array',
    message: '请选择游戏封面',
    trigger: 'change',
  },
  name: {
    required: true,
    message: '请输入游戏名称',
    trigger: 'blur',
  },
  url: {
    required: true,
    message: '请输入游戏链接',
    trigger: 'blur',
  },
  introduction: {
    required: true,
    message: '请输入游戏介绍',
    trigger: 'blur',
  },
}

const model = ref({
  name: '',
  url: '',
  introduction: '',
  cover: [],
  status: 2,
})

const submit = () => {
  formRef.value?.validate(async (errors) => {
    if (!errors) {
      const data = {
        ...model.value,
        cover: model.value.cover[0].url,
      }
      const res = await api.addGame(data)
      $message.success(res.msg)
      clear()
    }
  })
}

const clear = () => {
  model.value = {
    name: '',
    url: '',
    introduction: '',
    cover: [],
    status: 2,
  }
  formRef.value?.restoreValidation()
  showModal.value = false
  getList()
}

const route = useRouter()

const paths = ['/game/game_data', '/game/game_statistics', '/game/game_zs']

const dropdownSelect = (e) => {
  route.push(paths[e])
}
</script>

<template>
  <CommonPage show-footer :title="$route.title">
    <n-button v-perms="['/admin/game/edit']" type="primary" @click="openModal()">添加游戏</n-button>
    <n-data-table
      class="mt-5"
      :loading="loading"
      :columns="columns"
      :data="data"
      :pagination="pagination"
      :bordered="false"
      remote
    />

    <!--  添加/编辑游戏  -->
    <n-modal v-model:show="showModal">
      <n-card
        style="width: 900px"
        title="添加/编辑游戏"
        :bordered="false"
        size="huge"
        role="dialog"
        aria-modal="true"
      >
        <n-form ref="formRef" :model="model" :rules="rules" label-placement="left">
          <n-grid :cols="24" :x-gap="24">
            <n-form-item-gi :span="16" label="游戏封面：" path="cover">
              <Upload v-model:list="model.cover" :max="1" />
            </n-form-item-gi>
            <n-form-item-gi :span="16" label="游戏名称：" path="name">
              <n-input v-model:value="model.name" placeholder="请输入游戏名称" />
            </n-form-item-gi>
            <n-form-item-gi :span="16" label="游戏链接：" path="url">
              <n-input v-model:value="model.url" placeholder="请输入游戏链接" />
            </n-form-item-gi>
            <n-form-item-gi :span="24" label="游戏介绍：" path="introduction">
              <Editor v-model:value-html="model.introduction" :height="350" />
            </n-form-item-gi>
            <n-form-item-gi :span="16" label="是否显示：" path="status">
              <n-switch v-model:value="model.status" :unchecked-value="2" :checked-value="1" />
            </n-form-item-gi>
            <n-form-item-gi :span="12">
              <div m-auto p-10>
                <n-button type="primary" @click="submit">提交</n-button>
                <n-button ml-10 @click="clear">取消</n-button>
              </div>
            </n-form-item-gi>
          </n-grid>
        </n-form>
      </n-card>
    </n-modal>
  </CommonPage>
</template>

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