<template>
  <div class="asset-list">
    <!-- 操作栏 -->
    <el-card class="toolbar">
      <div class="toolbar-actions">
        <el-button type="primary" :icon="Plus" @click="handleCreate">
          新建资产
        </el-button>
        <el-button :icon="Upload" @click="handleImport">
          导入
        </el-button>
        <el-button :icon="Download" @click="handleExport">
          导出
        </el-button>
      </div>

      <div class="filter-section">
        <el-select
          v-model="filters.deviceTypeId"
          placeholder="设备类型"
          clearable
          style="width: 150px"
        >
          <el-option
            v-for="type in deviceTypes"
            :key="type.id"
            :label="type.typeName"
            :value="type.id"
          />
        </el-select>

        <el-select
          v-model="filters.organizationId"
          placeholder="网点"
          clearable
          style="width: 150px"
        >
          <el-option
            v-for="org in organizations"
            :key="org.id"
            :label="org.orgName"
            :value="org.id"
          />
        </el-select>

        <el-select
          v-model="filters.status"
          placeholder="状态"
          clearable
          style="width: 150px"
        >
          <el-option
            v-for="(item, key) in ASSET_STATUS"
            :key="key"
            :label="item.label"
            :value="item.value"
          />
        </el-select>

        <el-input
          v-model="filters.keyword"
          placeholder="搜索资产编码/名称"
          clearable
          style="width: 250px"
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>

        <el-button type="primary" @click="handleSearch">
          搜索
        </el-button>
        <el-button @click="handleReset">
          重置
        </el-button>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table
        :data="tableData"
        v-loading="loading"
        border
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="assetCode" label="资产编码" width="180" fixed />
        <el-table-column prop="assetName" label="资产名称" min-width="150" />
        <el-table-column prop="deviceType.typeName" label="设备类型" width="120" />
        <el-table-column prop="brand.brandName" label="品牌" width="120" />
        <el-table-column prop="model" label="型号" width="150" />
        <el-table-column prop="serialNumber" label="序列号" width="150" />
        <el-table-column prop="organization.orgName" label="所属网点" width="150" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusName(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="purchasePrice" label="采购价格" width="120">
          <template #default="{ row }">
            {{ row.purchasePrice ? `¥${row.purchasePrice.toFixed(2)}` : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleView(row)">
              查看
            </el-button>
            <el-button link type="primary" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button link type="primary" @click="handleQrcode(row)">
              二维码
            </el-button>
            <el-popconfirm
              title="确定删除该资产吗？"
              @confirm="handleDelete(row.id)"
            >
              <template #reference>
                <el-button link type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handlePageChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 资产详情对话框 -->
    <AssetDetailDialog
      v-model="detailDialogVisible"
      :asset-id="selectedAssetId"
    />

    <!-- 资产编辑对话框 -->
    <AssetEditDialog
      v-model="editDialogVisible"
      :asset-id="selectedAssetId"
      @success="handleSaveSuccess"
    />

    <!-- 二维码对话框 -->
    <QrcodeDialog
      v-model="qrcodeDialogVisible"
      :asset="selectedAsset"
    />

    <!-- 批量导入对话框 -->
    <BatchImportDialog
      v-model="importDialogVisible"
      @success="handleSaveSuccess"
    />

    <!-- 批量导出对话框 -->
    <BatchExportDialog v-model="exportDialogVisible" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Plus, Upload, Download, Search } from '@element-plus/icons-vue'
import { getAssetList, deleteAsset, getDeviceTypes, getOrganizationTree } from '@/api'
import { usePagination } from '@/composables/usePagination'
import { ASSET_STATUS } from '@/utils/constants'
import AssetDetailDialog from './components/AssetDetailDialog.vue'
import AssetEditDialog from './components/AssetEditDialog.vue'
import QrcodeDialog from './components/QrcodeDialog.vue'
import BatchImportDialog from './components/BatchImportDialog.vue'
import BatchExportDialog from './components/BatchExportDialog.vue'
import { ElMessage } from 'element-plus'

const router = useRouter()

const deviceTypes = ref<any[]>([])
const organizations = ref<any[]>([])
const selectedRows = ref<any[]>([])

const { pagination, resetPage, setTotal } = usePagination()

const filters = reactive({
  deviceTypeId: undefined,
  organizationId: undefined,
  status: undefined,
  keyword: ''
})

const loading = ref(false)
const tableData = ref<any[]>([])

const detailDialogVisible = ref(false)
const editDialogVisible = ref(false)
const qrcodeDialogVisible = ref(false)
const importDialogVisible = ref(false)
const exportDialogVisible = ref(false)
const selectedAssetId = ref<number | null>(null)
const selectedAsset = ref<any>(null)

// 获取资产列表
const fetchAssetList = async () => {
  loading.value = true
  try {
    const data = await getAssetList({
      page: pagination.page,
      page_size: pagination.pageSize,
      ...filters
    })
    tableData.value = data.items
    setTotal(data.total)
  } catch (error) {
    ElMessage.error('获取资产列表失败')
  } finally {
    loading.value = false
  }
}

// 获取设备类型列表
const fetchDeviceTypes = async () => {
  try {
    const data = await getDeviceTypes({ status: 'active' })
    deviceTypes.value = data
  } catch (error) {
    console.error('获取设备类型失败', error)
  }
}

// 获取网点树
const fetchOrganizations = async () => {
  try {
    const tree = await getOrganizationTree()
    // 扁平化树形数据
    const flatten = (nodes: any[]) => {
      const result: any[] = []
      nodes.forEach(node => {
        result.push(node)
        if (node.children) {
          result.push(...flatten(node.children))
        }
      })
      return result
    }
    organizations.value = flatten(tree)
  } catch (error) {
    console.error('获取网点失败', error)
  }
}

// 搜索
const handleSearch = () => {
  resetPage()
  fetchAssetList()
}

// 重置
const handleReset = () => {
  Object.assign(filters, {
    deviceTypeId: undefined,
    organizationId: undefined,
    status: undefined,
    keyword: ''
  })
  handleSearch()
}

// 分页变化
const handlePageChange = () => {
  fetchAssetList()
}

// 新建
const handleCreate = () => {
  router.push('/assets/create')
}

// 导入
const handleImport = () => {
  importDialogVisible.value = true
}

// 导出
const handleExport = () => {
  exportDialogVisible.value = true
}

// 查看详情
const handleView = (row: any) => {
  selectedAssetId.value = row.id
  detailDialogVisible.value = true
}

// 编辑
const handleEdit = (row: any) => {
  selectedAssetId.value = row.id
  editDialogVisible.value = true
}

// 二维码
const handleQrcode = (row: any) => {
  selectedAsset.value = row
  qrcodeDialogVisible.value = true
}

// 删除
const handleDelete = async (id: number) => {
  try {
    await deleteAsset(id)
    ElMessage.success('删除成功')
    fetchAssetList()
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

// 保存成功回调
const handleSaveSuccess = () => {
  fetchAssetList()
}

// 状态标签类型
const getStatusType = (status: string) => {
  const item = Object.values(ASSET_STATUS).find(item => item.value === status)
  return item?.type || ''
}

// 状态名称
const getStatusName = (status: string) => {
  const item = Object.values(ASSET_STATUS).find(item => item.value === status)
  return item?.label || status
}

onMounted(() => {
  fetchAssetList()
  fetchDeviceTypes()
  fetchOrganizations()
})
</script>

<style scoped lang="scss">
.asset-list {
  .toolbar {
    margin-bottom: 16px;

    .toolbar-actions {
      margin-bottom: 16px;
    }

    .filter-section {
      display: flex;
      gap: 10px;
      flex-wrap: wrap;
    }
  }

  .table-card {
    .pagination {
      display: flex;
      justify-content: flex-end;
      margin-top: 16px;
    }
  }
}
</style>
