<!--
 * @Author: xiejiang
 * @Date: 2024-11-11 09:38:40
 * @LastEditors: xiejiang
 * @LastEditTime: 2024-12-11 23:12:57
 * @Description: 版本管理
 * Copyright（c）2024 by 好老师教育科技有限公司 All right Reserved.
-->
<template>
  <div class="h-full overflow-auto">
    <t-tabs class="!px-[16px]" v-model="tabValue" :on-change="onTabChange">
      <t-tab-panel :value="1" label="平台端" :destroy-on-hide="false" />
    </t-tabs>

    <PageContainer
      row-key="menuId"
      :filter-conditions="filterConditions"
      :table-data="tableData"
      :columns="columns"
      :loading="loading"
      :pagination="pagination"
      :show-tree="true"
      @on-search="onSearch"
      @search-change="handleSearch"
      @page-change="handlePage"
      @clear="handleSearch({})"
      table-maxheight="550px"
      class="max-h-[calc(100%-50px)]"
    >
      <template #header-left>
        <p class="text-[12px] text-[var(--td-font-gray-1)] m-[0]">累计更新：{{ publishedNum }} 次</p>
      </template>
      <template #header-right>
        <div class="flex items-center justify-end gap-2">
          <t-button theme="primary" @click="handleEdit(null)">
            <template #icon><AddIcon /></template>
            添加版本</t-button
          >
        </div>
      </template>

      <!-- 表格操作列插槽，#colKey必须对应operation -->
      <template #menuStatus="{ row }">
        <div class="flex items-center gap-2">
          <div class="w-[6px] h-[6px] rounded-full" :class="row.menuStatus == 1 ? 'bg-success' : 'bg-danger'" />
          {{ row.menuStatus == 1 ? '启用' : '停用' }}
        </div>
      </template>
      <template #operation="{ row }">
        <div class="flex items-center">
          <operate-btn v-if="row.status != 2" content="编辑" @click="handleEdit(row)"> </operate-btn>
          <operate-btn v-if="row.status != 1" content="详情" @click="handleDetail(row)"> </operate-btn>
          <operate-btn v-if="row.status == 2" content="下线" @click="handleStatus(row, 6)"></operate-btn>
          <operate-btn v-if="row.status == 1" content="发布" @click="handleStatus(row, 7)"> </operate-btn>
          <operate-btn v-if="row.status == 3" content="重新发布" @click="handleStatus(row, 8)"> </operate-btn>
          <operate-btn v-if="row.status != 2" content="删除" @click="handleDel(row)"></operate-btn>
        </div>
      </template>
    </PageContainer>

    <!-- 新增编辑版本 -->
    <VersionEdit :tab-type="tabValue" ref="versionEditRef" @success="handleSearch(searchParams)" />

    <!-- 版本详情 -->
    <VersionDetail :tab-type="tabValue" ref="versionDetailRef" />
  </div>
</template>

<script setup lang="tsx" name="version">
import dayjs from 'dayjs'
import { PrimaryTableCol, MessagePlugin } from 'tdesign-vue-next'
import type { filterItemProp } from '@/components/PageFilters/interface/index'
import type { Pagination } from '@/components/PageContainer/interface/index'
import { useBasic } from '@/hooks/useBasic'
import MessageBox from '@/utils/messageBox'
import { ResVersion } from '@/api/interface/version/index'
import { getVersionPage, postVersionRemove, postVersionEditStatus } from '@/api/modules/version/index'
import { statusVersionTxt } from '@/utils/status'
import VersionEdit from './page/version-edit.vue'
import VersionDetail from './page/version-detail.vue'

defineOptions({
  name: 'version'
})

const { setBreadcrumb } = useBasic()
// 标签页
const tabValue = ref(1)

// 切换标签页
const onTabChange = () => {
  getData()
}

// 初始加载
onMounted(() => {
  setBreadcrumb([
    {
      title: '系统配置'
    },
    {
      title: '版本管理'
    }
  ])
})

onActivated(() => {
  getData()
})
// 搜索参数类型
const filterConditions = ref<filterItemProp[]>([
  {
    label: '上线时间',
    prop: 'onlineTime',
    type: 'date',
    $attrs: {
      'disable-date': (date: string) => {
        return dayjs(date).isBefore(dayjs().format('YYYY-MM')) || dayjs(date).isAfter(dayjs().format('YYYY-MM-DD'))
      },
      mode: 'month'
    }
  },
  {
    label: '版本状态',
    prop: 'status',
    type: 'select',
    selectData: [
      { label: '开发中', value: 1 },
      { label: '已发布', value: 2 },
      { label: '已下线', value: 3 }
    ]
  }
])
// 表格列配置
const columns: PrimaryTableCol[] = [
  {
    title: '序号',
    colKey: 'serial-number',
    width: 70
  },
  { title: '版本号', colKey: 'version' },
  {
    title: '版本状态',
    colKey: 'status',
    cell: (h, { row }) => {
      return (
        <div class='flex items-center'>
          <div class={'dot ' + statusVersionTxt(row.status)?.class}></div>
          <span class={statusVersionTxt(row.status)?.class}>{statusVersionTxt(row.status)?.title}</span>
        </div>
      )
    }
  },
  { title: '更新说明', colKey: 'description' },
  { title: '版本备注', colKey: 'remark' },
  { title: '上线时间', colKey: 'onlineTime' },
  { title: '添加时间', colKey: 'inputTime' },
  {
    title: '添加人',
    colKey: 'inputUserName',
    width: 120,
    cell: (h, { row }) => {
      return (
        <div class='flex items-center justify-between'>
          <t-tooltip content={row.inputUserName}>
            <div class={row.inputUserDelFlag ? 'w-[calc(100%-58px)] ellipsis' : ''}>
              <span>{row.inputUserName || '-'}</span>
            </div>
          </t-tooltip>
          {row.inputUserDelFlag ? <span class='inputUserName-del'>已删除</span> : ''}
        </div>
      )
    }
  },
  { title: '操作', colKey: 'operation', fixed: 'right', width: 220 }
]
// 标签页
const publishedNum = ref<string | number>('')
// 表格数据
const tableData = ref<ResVersion[]>([])
// 加载状态
const loading = ref(false)
// 分页配置
const pagination = ref<Pagination>({ page: 1, limit: 10, total: 0 })

const searchParams = ref<Record<string, any>>({}) // 搜索筛选
// 处理搜索条件
const handleSearch = (params: Record<string, any>) => {
  pagination.value.page = 1
  searchParams.value = params
  getData()
}

// 搜索
const onSearch = (params: Record<string, any>) => {
  searchParams.value = params
}

// 分页变更
const handlePage = (pageInfo: { page: number; limit: number }) => {
  pagination.value = { ...pagination.value, ...pageInfo }
  getData()
}

// // 编辑新增
const versionEditRef = ref()
const handleEdit = (row: ResVersion | null) => {
  versionEditRef.value?.open(row)
}

// 状态
const handleStatus = (row: ResVersion, status: number) => {
  const dialog = MessageBox(status, {
    onConfirm: () => {
      // 请求成功后，销毁弹框
      dialog.update({ confirmBtn: { content: '确定', loading: true } })
      postVersionEditStatus({
        versionId: row?.versionId as string,
        status: status == 6 ? 3 : 2
      })
        .then(() => {
          getData()
          MessagePlugin.success('操作成功')
          dialog.hide()
        })
        .catch(() => {
          MessagePlugin.error('操作失败')
        })
        .finally(() => {
          dialog.update({ confirmBtn: { content: '确定', loading: false } })
        })
    }
  })
}

const versionDetailRef = ref()
// 详情
const handleDetail = (row: ResVersion) => {
  versionDetailRef.value?.open(row)
}

// 删除
const handleDel = (row: ResVersion) => {
  const dialog = MessageBox(3, {
    onConfirm: () => {
      // 请求成功后，销毁弹框
      dialog.update({ confirmBtn: { content: '确定', loading: true } })
      postVersionRemove({
        ids: [String(row.versionId)]
      })
        .then(() => {
          getData()
          MessagePlugin.success('操作成功')
          dialog.hide()
        })
        .catch(() => {
          MessagePlugin.error('操作失败')
        })
        .finally(() => {
          dialog.update({ confirmBtn: { content: '确定', loading: false } })
        })
    }
  })
}

// 获取版本列表
const getData = () => {
  loading.value = true
  const postData = {
    ...pagination.value,
    versionType: tabValue.value,
    ...searchParams.value
  }
  getVersionPage(postData)
    .then(res => {
      tableData.value = res.data.pageInfo.list
      publishedNum.value = res.data?.publishedNum
      pagination.value.total = res.data?.pageInfo?.total
    })
    .catch(() => {
      tableData.value = []
      pagination.value.total = 0
    })
    .finally(() => {
      loading.value = false
    })
}
</script>
