<template>
  <el-dialog
    v-model="visible"
    title="选择资产"
    width="1000px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <!-- 筛选条件 -->
    <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>
    </div>

    <!-- 资产表格 -->
    <el-table
      ref="tableRef"
      :data="tableData"
      v-loading="loading"
      border
      stripe
      max-height="400"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" :selectable="checkSelectable" />
      <el-table-column prop="assetCode" label="资产编码" width="180" />
      <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="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>

    <!-- 分页 -->
    <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]"
        layout="total, sizes, prev, pager, next"
        @size-change="handlePageChange"
        @current-change="handlePageChange"
      />
    </div>

    <template #footer>
      <div class="dialog-footer">
        <span class="selected-info">已选择 {{ selectedAssets.length }} 项</span>
        <el-button @click="handleClose">取消</el-button>
        <el-button
          type="primary"
          :disabled="selectedAssets.length === 0"
          @click="handleConfirm"
        >
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { getAssetList, getDeviceTypes, getOrganizationTree } from '@/api'
import { usePagination } from '@/composables/usePagination'
import { ASSET_STATUS } from '@/utils/constants'

interface Props {
  modelValue: boolean
  excludeIds?: number[]
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'confirm', assets: any[]): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const tableRef = ref()
const loading = ref(false)
const tableData = ref<any[]>([])
const deviceTypes = ref<any[]>([])
const organizations = ref<any[]>([])
const selectedAssets = ref<any[]>([])

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

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

// 检查是否可选
const checkSelectable = (row: any) => {
  return !props.excludeIds?.includes(row.id)
}

// 获取资产列表
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) {
    console.error('获取资产列表失败', 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 handlePageChange = () => {
  fetchAssetList()
}

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

// 获取状态标签类型
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
}

// 确认选择
const handleConfirm = () => {
  emit('confirm', selectedAssets.value)
  handleClose()
}

// 关闭对话框
const handleClose = () => {
  visible.value = false
  // 重置选择
  setTimeout(() => {
    tableRef.value?.clearSelection()
    selectedAssets.value = []
  }, 300)
}

// 监听对话框打开
watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      fetchAssetList()
    }
  }
)

// 初始化
fetchDeviceTypes()
fetchOrganizations()
</script>

<script lang="ts">
import { computed } from 'vue'
export default {
  name: 'AssetSelectorDialog'
}
</script>

<style scoped lang="scss">
.filter-section {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  margin-bottom: 16px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .selected-info {
    font-size: 14px;
    color: #606266;
  }
}
</style>
