<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true">
      <el-form-item label="键盘皮肤名称" prop="themeName">
        <el-input v-model="queryParams.themeName" placeholder="请输入键盘皮肤名称" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="键盘价格" prop="themePrice">
        <el-input v-model="queryParams.themePrice" placeholder="请输入键盘价格" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="主题标签" prop="themeTag">
        <el-input v-model="queryParams.themeTag" placeholder="请输入主题标签" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="主题下载次数" prop="themeDownload">
        <el-input v-model="queryParams.themeDownload" placeholder="请输入主题下载次数" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="主题风格" prop="themeStyle">
        <el-select v-model="queryParams.themeStyle" placeholder="请选择主题风格" clearable class="!w-240px">
          <el-option v-for="item in themeStyleOptions" :key="item.id" :label="item.styleName" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="上架状态" prop="themeStatus">
        <el-select v-model="queryParams.themeStatus" placeholder="请选择上架状态" clearable class="!w-240px">
          <el-option v-for="item in themeStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="主题购买次数" prop="themePurchasesNumber">
        <el-input v-model="queryParams.themePurchasesNumber" placeholder="请输入主题购买次数" clearable
          @keyup.enter="handleQuery" class="!w-240px" />
      </el-form-item>
      <el-form-item label="创建时间" prop="createdAt">
        <el-date-picker v-model="queryParams.createdAt" value-format="YYYY-MM-DD" type="date" placeholder="选择创建时间"
          clearable class="!w-240px" />
      </el-form-item>
      <el-form-item label="更新时间" prop="updatedAt">
        <el-date-picker v-model="queryParams.updatedAt" value-format="YYYY-MM-DD" type="date" placeholder="选择更新时间"
          clearable class="!w-240px" />
      </el-form-item>
      <el-form-item label="预览图" prop="themePreviewImageUrl">
        <el-input v-model="queryParams.themePreviewImageUrl" placeholder="请输入预览图" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="是否免费" prop="isFree">
        <el-select v-model="queryParams.isFree" placeholder="请选择是否免费" clearable class="!w-240px">
          <el-option v-for="item in freeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="下载地址" prop="themeDownloadUrl">
        <el-input v-model="queryParams.themeDownloadUrl" placeholder="请输入下载地址" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="所属国家" prop="local">
        <el-input v-model="queryParams.local" placeholder="请输入所属国家" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>

      <el-form-item label="排序" prop="sort">
        <el-input v-model="queryParams.sort" placeholder="请输入排序" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="真实下载数量" prop="realDownloadCount">
        <el-input v-model="queryParams.realDownloadCount" placeholder="请输入真实下载数量" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" /> 搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" /> 重置
        </el-button>
        <el-button type="primary" plain @click="openForm('create')" v-hasPermi="['keyboard:themes:create']">
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button type="success" plain @click="handleExport" :loading="exportLoading"
          v-hasPermi="['keyboard:themes:export']">
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button type="danger" plain :disabled="isEmpty(checkedIds)" @click="handleDeleteBatch"
          v-hasPermi="['keyboard:themes:delete']">
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table row-key="id" v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="主键 Id" align="center" prop="id" />
      <el-table-column label="键盘皮肤名称" align="center" prop="themeName" />
      <el-table-column label="键盘价格" align="center" prop="themePrice" />
      <el-table-column label="主题标签" align="center" prop="themeTag" min-width="140px">
        <template #default="{ row }">
          <el-tooltip v-if="getThemeTags(row).length" placement="top" effect="dark">
            <template #content>
              <div class="flex flex-wrap">
                <el-tag v-for="(tag, index) in getThemeTags(row)" :key="index" class="mr-5px mb-5px"
                  :style="getTagStyle(tag)">
                  {{ getTagText(tag) }}
                </el-tag>
              </div>
            </template>
            <el-button link type="primary">查看({{ getThemeTags(row).length }})</el-button>
          </el-tooltip>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="主题下载次数" align="center" prop="themeDownload" />
      <el-table-column label="主题风格" align="center" prop="themeStyle">
        <template #default="{ row }">
          <span>{{ getThemeStyleName(row.themeStyle) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上架状态" align="center" prop="themeStatus" width="110px">
        <template #default="{ row }">
          <el-tag :type="getThemeStatusTagType(row.themeStatus)">
            {{ getThemeStatusLabel(row.themeStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="主题购买次数" align="center" prop="themePurchasesNumber" />
      <el-table-column label="所属国家" align="center" prop="local" />
      <el-table-column label="创建时间" align="center" prop="createdAt" :formatter="dateFormatter" width="180px" />
      <el-table-column label="更新时间" align="center" prop="updatedAt" :formatter="dateFormatter" width="180px" />
      <el-table-column label="预览图" align="center" prop="themePreviewImageUrl" width="120px">
        <template #default="{ row }">
          <el-image v-if="row.themePreviewImageUrl" :src="row.themePreviewImageUrl" fit="cover" class="cursor-pointer"
            style="width: 60px; height: 60px" @click="imagePreview(row.themePreviewImageUrl)" />
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="是否免费" align="center" prop="isFree" width="110px">
        <template #default="{ row }">
          <el-tag :type="getFreeTagType(row.isFree)">
            {{ getFreeLabel(row.isFree) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="下载地址" align="center" prop="themeDownloadUrl" />
      <el-table-column label="排序" align="center" prop="sort" />
      <el-table-column label="真实下载数量" align="center" prop="realDownloadCount" />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button link type="primary" @click="openForm('update', scope.row.id)"
            v-hasPermi="['keyboard:themes:update']">
            编辑
          </el-button>
          <el-button link type="danger" @click="handleDelete(scope.row.id)" v-hasPermi="['keyboard:themes:delete']">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
      @pagination="getList" />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <ThemesForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { ThemesApi, Themes } from '@/api/keyboard/themes'
import { KeyboardThemeStylesApi, KeyboardThemeStyles } from '@/api/keyboard-server/themestyles'
import ThemesForm from './ThemesForm.vue'
import { createImageViewer } from '@/components/ImageViewer'

/** 键盘皮肤 列表 */
defineOptions({ name: 'KeyboardThemes' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<Themes[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  themeName: undefined,
  themePrice: undefined,
  themeTag: undefined,
  themeDownload: undefined,
  themeStyle: undefined,
  themeStatus: undefined,
  themePurchasesNumber: undefined,
  createdAt: undefined,
  createdAt: [],
  updatedAt: undefined,
  updatedAt: [],
  themePreviewImageUrl: undefined,
  isFree: undefined,
  themeDownloadUrl: undefined,
  local: undefined,
  sort: undefined,
  realDownloadCount: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const themeStyleOptions = ref<KeyboardThemeStyles[]>([])
const themeStyleMap = computed(() => {
  return new Map(themeStyleOptions.value.map((item) => [String(item.id), item.styleName]))
})
const themeStatusOptions = [
  { label: '已上架', value: true, tagType: 'success' },
  { label: '未上架', value: false, tagType: 'info' }
]
const freeOptions = [
  { label: '免费', value: true, tagType: 'success' },
  { label: '付费', value: false, tagType: 'warning' }
]

const getThemeStatusOption = (status: unknown) => {
  return themeStatusOptions.find((item) => String(item.value) === String(status))
}

const getThemeStatusLabel = (status: unknown) => {
  return getThemeStatusOption(status)?.label ?? '-'
}

const getThemeStatusTagType = (status: unknown) => {
  return getThemeStatusOption(status)?.tagType ?? 'info'
}
const getFreeOption = (value: unknown) => {
  return freeOptions.find((item) => String(item.value) === String(value))
}

const getFreeLabel = (value: unknown) => {
  return getFreeOption(value)?.label ?? '-'
}

const getFreeTagType = (value: unknown) => {
  return getFreeOption(value)?.tagType ?? 'info'
}
const getTagText = (tag: Record<string, any>) => {
  return tag?.label ?? tag?.text ?? tag?.name ?? '-'
}

const getTagStyle = (tag: Record<string, any>) => {
  if (!tag?.color) return {}
  return {
    backgroundColor: tag.color,
    borderColor: tag.color,
    color: '#ffffff'
  }
}

const normalizeThemeTags = (raw: unknown) => {
  if (!raw) return []
  if (Array.isArray(raw)) return raw
  if (typeof raw === 'string') {
    try {
      const parsed = JSON.parse(raw)
      if (Array.isArray(parsed)) return parsed
      if (parsed && typeof parsed === 'object') return [parsed]
    } catch {
      return raw ? [{ text: raw }] : []
    }
  }
  if (typeof raw === 'object') return [raw]
  return []
}

const getThemeTags = (row: Themes) => {
  return normalizeThemeTags(row.themeTag)
}

const getThemeStyleName = (styleId: unknown) => {
  if (styleId === null || styleId === undefined || styleId === '') return '-'
  return themeStyleMap.value.get(String(styleId)) ?? String(styleId)
}

const fetchThemeStyles = async () => {
  const data = await KeyboardThemeStylesApi.getKeyboardThemeStylesPage({ pageNo: 1, pageSize: 100 })
  themeStyleOptions.value = data.list ?? []
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ThemesApi.getThemesPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ThemesApi.deleteThemes(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch { }
}

/** 批量删除键盘皮肤 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await ThemesApi.deleteThemesList(checkedIds.value);
    checkedIds.value = [];
    message.success(t('common.delSuccess'))
    await getList();
  } catch { }
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: Themes[]) => {
  checkedIds.value = records.map((item) => item.id!);
}

/** 预览图片 */
const imagePreview = (imgUrl: string) => {
  createImageViewer({
    urlList: [imgUrl]
  })
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ThemesApi.exportThemes(queryParams)
    download.excel(data, '键盘皮肤.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  fetchThemeStyles()
  getList()
})
</script>
