<template>
  <div class="container">
    <search-table
      :form-model="formModel"
      :form-items="formItems"
      :data="tableData"
      :columns="columns"
      :loading="loading"
      :pagination="pagination"
      title="设备资产管理"
      search-button-text="查询"
      reset-button-text="重置"
      @update:form-model="handleFormModelUpdate"
      @search="handleSearch"
      @reset="handleReset"
      @page-change="handlePageChange"
      @refresh="handleRefresh"
    >
      <template #toolbar-left>
        <a-button type="primary" @click="handleCreate">
          新增设备
        </a-button>
      </template>

      <!-- 序号 -->
      <template #index="{ rowIndex }">
        {{ rowIndex + 1 + (pagination.current - 1) * pagination.pageSize }}
      </template>

      <!-- 资产状态 -->
      <template #status="{ record }">
        <a-tag :color="getAssetStatusColor(record.status)">
          {{ getAssetStatusText(record.status) }}
        </a-tag>
      </template>

      <!-- 原值 -->
      <template #original_value="{ record }">
        {{ formatMoney(record.original_value) }}
      </template>

      <!-- 采购日期 -->
      <template #purchase_date="{ record }">
        {{ formatDate(record.purchase_date) }}
      </template>

      <!-- 质保到期日期 -->
      <template #warranty_expiry="{ record }">
        {{ formatDate(record.warranty_expiry) }}
      </template>

      <!-- 操作 -->
      <template #actions="{ record }">
        <a-button type="text" size="small" @click="handleDetail(record)">
          详情
        </a-button>
        <a-button type="text" size="small" @click="handleEdit(record)">
          编辑
        </a-button>
        <a-button type="text" size="small" status="danger" @click="handleDelete(record)">
          删除
        </a-button>
      </template>
    </search-table>

    <!-- 设备详情对话框 -->
    <device-detail-dialog
      v-model:visible="detailVisible"
      :device="currentDevice"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Message, Modal } from '@arco-design/web-vue'
import type { FormItem } from '@/components/search-form/types'
import SearchTable from '@/components/search-table/index.vue'
import {
  fetchAssetList,
  deleteAsset,
  fetchAssetDetail,
  getAssetStatusText,
  getAssetStatusColor,
  assetStatusOptions,
} from '@/api/ops/asset'
import DeviceDetailDialog from '../components/DeviceDetailDialog.vue'

const router = useRouter()

// 状态管理
const loading = ref(false)
const tableData = ref<any[]>([])
const formModel = ref({
  keyword: '',
  status: '',
})

const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
})

// 表单项配置
const formItems = computed<FormItem[]>(() => [
  {
    field: 'keyword',
    label: '关键词',
    type: 'input',
    placeholder: '请输入资产名称/编号/部门',
  },
  {
    field: 'status',
    label: '资产状态',
    type: 'select',
    placeholder: '请选择状态',
    options: assetStatusOptions,
    allowClear: true,
  },
])

// 表格列配置
const columns = computed(() => [
  {
    title: '序号',
    dataIndex: 'index',
    slotName: 'index',
    width: 70,
    align: 'center' as const,
  },
  {
    title: '资产编号',
    dataIndex: 'asset_code',
    ellipsis: true,
    tooltip: true,
    width: 130,
  },
  {
    title: '资产名称',
    dataIndex: 'asset_name',
    ellipsis: true,
    tooltip: true,
    width: 180,
  },
  {
    title: '资产分类',
    dataIndex: 'category.name',
    ellipsis: true,
    tooltip: true,
    width: 120,
  },
  {
    title: '规格型号',
    dataIndex: 'model',
    ellipsis: true,
    tooltip: true,
    width: 150,
  },
  {
    title: '使用部门',
    dataIndex: 'department',
    ellipsis: true,
    tooltip: true,
    width: 120,
  },
  {
    title: '使用人',
    dataIndex: 'user',
    ellipsis: true,
    tooltip: true,
    width: 100,
  },
  {
    title: '原值（元）',
    dataIndex: 'original_value',
    slotName: 'original_value',
    width: 120,
    align: 'right' as const,
  },
  {
    title: '资产状态',
    dataIndex: 'status',
    slotName: 'status',
    width: 100,
    align: 'center' as const,
  },
  {
    title: '采购日期',
    dataIndex: 'purchase_date',
    slotName: 'purchase_date',
    width: 110,
    align: 'center' as const,
  },
  {
    title: '操作',
    slotName: 'actions',
    width: 220,
    fixed: 'right' as const,
  },
])

// 当前选中的设备
const currentDevice = ref<any>(null)

// 对话框可见性
const detailVisible = ref(false)

// 获取设备列表
const fetchDevices = async () => {
  loading.value = true

  try {
    const params: any = {
      page: pagination.current,
      page_size: pagination.pageSize,
      keyword: formModel.value.keyword || undefined,
      status: formModel.value.status || undefined,
    }

    const res = await fetchAssetList(params)

    tableData.value = res.details?.data || []
    pagination.total = res.details?.total || 0
  } catch (error) {
    console.error('获取设备列表失败:', error)
    Message.error('获取设备列表失败')
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchDevices()
}

// 处理表单模型更新
const handleFormModelUpdate = (value: any) => {
  formModel.value = value
}

// 重置
const handleReset = () => {
  formModel.value = {
    keyword: '',
    status: '',
  }
  pagination.current = 1
  fetchDevices()
}

// 分页变化
const handlePageChange = (current: number) => {
  pagination.current = current
  fetchDevices()
}

// 刷新
const handleRefresh = () => {
  fetchDevices()
  Message.success('数据已刷新')
}

// 新增设备 - 跳转到新增页面
const handleCreate = () => {
  router.push('/assets/device/form')
}

// 编辑设备 - 跳转到编辑页面
const handleEdit = (record: any) => {
  router.push({
    path: '/assets/device/form',
    query: { id: record.id },
  })
}

// 详情
const handleDetail = async (record: any) => {
  try {
    const res = await fetchAssetDetail(record.id)
    if (res.code === 0) {
      currentDevice.value = res.details
      detailVisible.value = true
    } else {
      Message.error(res.message || '获取详情失败')
    }
  } catch (error) {
    console.error('获取设备详情失败:', error)
    Message.error('获取详情失败')
  }
}

// 删除设备
const handleDelete = async (record: any) => {
  try {
    Modal.confirm({
      title: '确认删除',
      content: `确认删除设备 ${record.asset_name} 吗？`,
      onOk: async () => {
        const res = await deleteAsset(record.id)
        if (res.code === 0) {
          Message.success('删除成功')
          fetchDevices()
        } else {
          Message.error(res.message || '删除失败')
        }
      },
    })
  } catch (error) {
    console.error('删除设备失败:', error)
  }
}

// 导出
const handleExport = async () => {
  try {
    Message.info('正在导出...')
    const res = await fetchAssetList({
      page: 1,
      page_size: 10000,
      keyword: formModel.value.keyword || undefined,
      status: formModel.value.status || undefined,
    })

    if (res.code === 0 && res.details?.data) {
      const data = res.details.data
      const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
      const url = URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `assets_${new Date().toISOString().slice(0, 10)}.json`
      link.click()
      URL.revokeObjectURL(url)
      Message.success('导出成功')
    }
  } catch (error) {
    console.error('导出失败:', error)
    Message.error('导出失败')
  }
}

// 格式化金额
const formatMoney = (value: number | string | null | undefined) => {
  if (value === null || value === undefined || value === '') return '-'
  const num = Number(value)
  if (isNaN(num)) return '-'
  return num.toLocaleString('zh-CN', {
    style: 'currency',
    currency: 'CNY',
    minimumFractionDigits: 2,
  })
}

// 格式化日期
const formatDate = (dateStr?: string) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 初始化加载数据
onMounted(() => {
  fetchDevices()
})
</script>

<script lang="ts">
export default {
  name: 'DeviceList',
}
</script>

<style scoped lang="less">
.container {
  margin-top: 20px;
}
</style>