<template>
  <n-card :bordered="false" class="valuation-card">
    <div class="section-header">
      <div class="title-block">
        <div class="title-bar"></div>
        <div class="title-text">估值记录</div>
      </div>
      <!-- <n-button quaternary type="primary" size="small" @click="fetchHistory">
        刷新
      </n-button> -->
    </div>

    <n-data-table
      :loading="loading"
      :columns="columns"
      :data="tableData"
      :row-key="rowKey"
      :pagination="pagination"
      remote
      striped
      size="medium"
    />
  </n-card>
</template>

<script setup>
import { h, onMounted, ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { NButton, NSpace } from 'naive-ui'
import api from '@/api'

const props = defineProps({
  assetList: {
    type: Array,
    default: () => [],
  },
})

const router = useRouter()

const loading = ref(false)
const tableData = ref([...props.assetList])

function getDownloadLink(urls) {
  if (Array.isArray(urls) && urls.length > 0) {
    return urls[0]
  }
  if (typeof urls === 'string' && urls) {
    return urls
  }
  return null
}

function handleDownloadAction(item, urlKey, errorMessage) {
  const downloadLink = getDownloadLink(item[urlKey])
  if (downloadLink) {
    window.open(downloadLink, '_blank')
  } else {
    window.$message?.error(errorMessage)
  }
}

function handleDownloadReport(item) {
  handleDownloadAction(item, 'certificate_download_urls', '报告下载链接不存在')
}

function handleDownloadCertificate(item) {
  handleDownloadAction(item, 'report_download_urls', '证书下载链接不存在')
}

function formatDate(dateStr) {
  if (!dateStr) return ''
  return `${dateStr.slice(0, 10)} ${dateStr.slice(11, 16)}`
}

const pagination = reactive({
  page: 1,
  pageSize: 10,
  itemCount: 0,
  showSizePicker: true,
  pageSizes: [10, 20, 50],
  prefix: ({ itemCount }) => `共 ${itemCount} 条`,
  onChange: (page) => {
    pagination.page = page
    fetchHistory()
  },
  onUpdatePageSize: (pageSize) => {
    pagination.pageSize = pageSize
    pagination.page = 1
    fetchHistory()
  },
})

const columns = [
  {
    title: '序号',
    key: 'index',
    width: 80,
    align: 'center',
    titleAlign: 'center',
    render: (_, index) => (pagination.page - 1) * pagination.pageSize + index + 1,
  },
  {
    title: '资产名称',
    key: 'asset_name',
    minWidth: 200,
    ellipsis: true,
    align: 'center',
    titleAlign: 'center',
    render: (row) =>
      h(
        'div',
        {
          class: 'asset-name-link',
          onClick: () => {
            router.push({
              path: '/pages',
              query: { id: row.id },
            })
          },
        },
        row.asset_name || row.name || '未知资产'
      ),
  },
  {
    title: '评估时间',
    key: 'created_at',
    minWidth: 180,
    align: 'center',
    titleAlign: 'center',
    render: (row) => formatDate(row.created_at),
  },
  {
    title: '操作',
    key: 'actions',
    align: 'center',
    titleAlign: 'center',
    width: 220,
    render: (row) =>
      h(
        NSpace,
        { size: 8, justify: 'center' },
        {
          default: () => {
            let arr = []
            if (row.report_download_urls.length) {
              arr.push(
                h(
                  NButton,
                  {
                    text: true,
                    type: 'primary',
                    size: 'small',
                    onClick: (e) => {
                      e.stopPropagation()
                      handleDownloadReport(row)
                    },
                  },
                  { default: () => '下载报告' }
                )
              )
            }
            if (row.certificate_download_urls.length)
              arr.push(
                h(
                  NButton,
                  {
                    text: true,
                    type: 'primary',
                    size: 'small',
                    onClick: (e) => {
                      e.stopPropagation()
                      handleDownloadCertificate(row)
                    },
                  },
                  { default: () => '下载证书' }
                )
              )

            return arr
          },
        }
      ),
  },
]

const rowKey = (row) => row.id ?? row.asset_name ?? row.name

async function fetchHistory() {
  loading.value = true
  try {
    const res = await api.getHistoryList({
      page: pagination.page,
      page_size: pagination.pageSize,
    })
    const list = res?.data?.items ?? res?.data?.results ?? res?.results ?? []
    tableData.value = Array.isArray(list) ? list : []
    pagination.itemCount = res?.data?.total ?? res?.total ?? 0
  } catch (error) {
    console.error('加载估值记录失败:', error)
    tableData.value = props.assetList
  } finally {
    loading.value = false
  }
}

onMounted(fetchHistory)
</script>

<style scoped>
.valuation-card {
  min-height: calc(100vh - 40px);
  border-radius: 12px;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.title-block {
  display: flex;
  align-items: center;
  gap: 8px;
}

.title-bar {
  width: 6px;
  height: 24px;
  background: #a30113;
  border-radius: 4px;
}

.title-text {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.empty-block {
  padding: 24px 0;
}

:deep(.asset-name-link) {
  cursor: pointer;
  color: #a30113;
  font-weight: 500;
  transition: all 0.3s;
}

:deep(.asset-name-link:hover) {
  opacity: 0.8;
  text-decoration: underline;
}
</style>
