<script setup lang="ts">

defineOptions({
  name: 'Voice Management',
})
import { Plus } from '@element-plus/icons-vue'
import { ElButton, ElDialog, ElEmpty, ElInput, ElOption, ElPagination, ElSelect, ElTable, ElTableColumn, ElTag } from 'element-plus'
import SearchForm from './components/SearchForm.vue'
import type { TSearchParams } from './components/SearchForm.vue'
import EditForm from './components/EditForm.vue'
import EditClone from './components/EditClone.vue'

import type { TVoice } from '@/types/voice'
import { toast } from 'vue-sonner'
import { voiceList, activeVoice } from '@/api/modules/voice'
import { formatDateGeneral } from '@/utils'

const tableRef = ref()
const loading = ref(false)
const cloneLoading = ref(false)
const router = useRouter()
const route = useRoute()

// 搜索参数
const searchParams = ref<TSearchParams>({
  name: '',
  type: 1,
  gender: null
})
const dataList = ref<TVoice[]>([]);
const editFormVisible = ref(false)
const editCloneVisible = ref(false)
const editMode = ref<'create' | 'edit'>('create')
const currentData = ref<{
    "id": string|undefined,
    "name": string,
    "photoUrl": string,
    "feature": string
    "gender": number,
}|null>(null)

const currentAudio = ref<{
    src: string;
    srcName: string;
    duration: number;
}|undefined>()

// 从URL获取初始分页参数
const getInitialPagination = () => {
  const page = Number(route.query.page) || 1
  const size = Number(route.query.size) || 20
  return {
    total: 0,
    page: page > 0 ? page : 1,
    size: [10, 20, 50, 100].includes(size) ? size : 20,
  }
}

// 分页信息
const pagination = ref(getInitialPagination())

// 更新URL中的分页参数
const updateUrlParams = (page: number, size: number) => {
  const query = {
    ...route.query,
    page: page.toString(),
    size: size.toString(),
  }

  // 使用replace模式更新URL，避免产生历史记录
  router.replace({
    path: route.path,
    query
  })
}

async function fetchData() {
  loading.value = true
  const gender = searchParams.value.gender === -1 ? null : searchParams.value.gender
  const res = await voiceList({
    gender,
    name: searchParams.value.name,
    type: searchParams.value.type,
    page: pagination.value.page,
    size: pagination.value.size,
  })
  console.log('res', res)
  if(res.code === 0){
    dataList.value = res.data.content
    pagination.value.total = res.data.total
  }
  loading.value = false
}
function handlePageChange(page: number) {
  pagination.value.page = page
  updateUrlParams(page, pagination.value.size)
  fetchData()
}

function handleSizeChange(size: number) {
  pagination.value.size = size
  pagination.value.page = 1
  updateUrlParams(1, size)
  fetchData()
}

function handleSearch () {
  pagination.value.page = 1 // 搜索时重置到第一页
  updateUrlParams(1, pagination.value.size)
  fetchData()
}

function handleReset () {
  searchParams.value = {
    name: '',
    type: 1,
    gender: null,
  }
  pagination.value.page = 1 // 重置时重置到第一页
  updateUrlParams(1, pagination.value.size)
  fetchData()
}


// 监听URL参数变化，用于处理浏览器后退/前进
watch(
  () => route.query,
  (newQuery) => {
    const newPage = Number(newQuery.page) || 1
    const newSize = Number(newQuery.size) || 20

    // 只有当参数真正发生变化时才更新
    if (newPage !== pagination.value.page || newSize !== pagination.value.size) {
      pagination.value.page = newPage > 0 ? newPage : 1
      pagination.value.size = [10, 20, 50, 100].includes(newSize) ? newSize : 20
      fetchData()
    }
  },
  { deep: true }
)


const handleEdit = (data: TVoice) => {
  editMode.value = 'edit'
  currentData.value = {
    id: data.id,
    name: data.name ?? '',
    photoUrl: data.photoUrl ?? '',
    feature: data.feature ?? '',
    gender: data.gender,
  }

  editFormVisible.value = true
}

const switchLoading = ref(false)
const handleActive = async (id: string) => {
  switchLoading.value = true
  try {
    const { code } = await activeVoice({ id })
    if(code === 0){
      toast.success('激活成功')
      fetchData()
    }
    switchLoading.value = false
  } catch (error) {
    switchLoading.value = false
    return
  }
}


onMounted(async () => {
  updateUrlParams(pagination.value.page, pagination.value.size)
  await fetchData()
})


</script>

<template>
  <div class="absolute-container">
    <div class="p-4 pb-0 bg-white dark-bg-black/50">
      <SearchForm v-model="searchParams" @search="handleSearch" @reset="handleReset"></SearchForm>
    </div>
    <FaPageMain class="flex-1 overflow-auto" main-class="flex-1 flex flex-col overflow-auto">
      <div class="pb-4">
        <ElSpace>
          <ElButton type="primary" :icon="Plus" @click="()=> editCloneVisible = true">克隆声音</ElButton>
        </ElSpace>
      </div>
      <ElTable
        ref="tableRef" :data="dataList" stripe highlight-current-row border height="100%"
      >
        <ElTableColumn label="ID" prop="id" width="280" />
        <ElTableColumn label="Name" prop="name" min-width="200"/>
        <ElTableColumn label="Avatar" prop="photoUrl">
          <template #default="{row}">
            <ElImage :src="row.photoUrl" fit="cover" class="w-12 h-12 rounded" />
          </template>
        </ElTableColumn>
        <ElTableColumn label="Gender" prop="gender">
          <template #default="{row}">
            {{ row.gender === 1 ? '男':"女" }}
          </template>
        </ElTableColumn>

        <ElTableColumn label="feature" prop="feature" width="280" />
        <ElTableColumn label="激活状态" prop="status" width="120">
          <template #default="{row}">
            <ElTag type="success" v-if="row.status === 5">
              已激活
            </ElTag>
            <ElButton v-else-if="row.status === 3"  @click="() => handleActive(row.voiceId)" :disabled="switchLoading">
              激活
            </ElButton>
            <div v-else>...</div>
            <!-- <ElSwitch
              v-model="row.status"
              :active-value="5"
              :inactive-value="3"
              :disabled="switchLoading"
              @click="() => handleActive(row.voiceId)"
            />
              待激活
            </div> -->
          </template>
        </ElTableColumn>
        <ElTableColumn label="create time" prop="ctime" width="280">
          <template #default="{row}">
            {{ formatDateGeneral(row.ctime) }}
          </template>
        </ElTableColumn>
        <ElTableColumn fixed="right" label="操作" min-width="240">
          <template #default="{row}">
            <ElButton link type="primary" size="small" @click="handleEdit(row)">编辑</ElButton>
          </template>
        </ElTableColumn>
      </ElTable>
      <div class="p-4">
        <ElPagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </FaPageMain>
    <EditForm v-model="currentData" v-model:visible="editFormVisible" :mode="editMode" @refresh="fetchData"></EditForm>
    <EditClone v-model:visible="editCloneVisible" @refresh="fetchData"></EditClone>
  </div>
</template>
<style scoped>
.absolute-container {
  position: absolute;
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
}
</style>
