<template>
  <el-dialog
    v-model="visible"
    title="批量导出资产"
    width="700px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form ref="formRef" :model="formData" label-width="100px">
      <!-- 字段选择 -->
      <el-form-item label="导出字段">
        <el-checkbox-group v-model="formData.selectedFields">
          <el-checkbox label="assetCode">资产编码</el-checkbox>
          <el-checkbox label="assetName">资产名称</el-checkbox>
          <el-checkbox label="deviceTypeName">设备类型</el-checkbox>
          <el-checkbox label="brandName">品牌</el-checkbox>
          <el-checkbox label="modelName">型号</el-checkbox>
          <el-checkbox label="serialNumber">序列号</el-checkbox>
          <el-checkbox label="orgName">所属网点</el-checkbox>
          <el-checkbox label="location">位置</el-checkbox>
          <el-checkbox label="status">状态</el-checkbox>
          <el-checkbox label="purchaseDate">采购日期</el-checkbox>
          <el-checkbox label="purchasePrice">采购价格</el-checkbox>
          <el-checkbox label="warrantyExpireDate">保修截止</el-checkbox>
        </el-checkbox-group>
        <div class="field-actions">
          <el-button link type="primary" @click="selectAllFields">
            全选
          </el-button>
          <el-button link type="primary" @click="clearAllFields">
            清空
          </el-button>
        </div>
      </el-form-item>

      <!-- 筛选条件 -->
      <el-divider content-position="left">筛选条件</el-divider>

      <el-form-item label="设备类型">
        <el-select
          v-model="filters.deviceTypeId"
          placeholder="全部"
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="type in deviceTypes"
            :key="type.id"
            :label="type.typeName"
            :value="type.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="所属网点">
        <el-select
          v-model="filters.organizationId"
          placeholder="全部"
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="org in organizations"
            :key="org.id"
            :label="org.orgName"
            :value="org.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="资产状态">
        <el-select
          v-model="filters.status"
          placeholder="全部"
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="(item, key) in ASSET_STATUS"
            :key="key"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="关键词">
        <el-input
          v-model="filters.keyword"
          placeholder="搜索资产编码/名称/型号"
          clearable
        />
      </el-form-item>

      <!-- 导出格式 -->
      <el-form-item label="导出格式">
        <el-radio-group v-model="formData.format">
          <el-radio label="xlsx">Excel (.xlsx)</el-radio>
          <el-radio label="csv">CSV (.csv)</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 导出统计 -->
      <el-alert
        v-if="totalCount > 0"
        :title="`预计导出 ${totalCount} 条数据`"
        type="info"
        :closable="false"
        show-icon
      />
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="exporting" @click="handleExport">
          <el-icon><Download /></el-icon>
          开始导出
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Download } from '@element-plus/icons-vue'
import { exportAssets, getDeviceTypes, getOrganizationTree } from '@/api'
import { ASSET_STATUS } from '@/utils/constants'

interface Props {
  modelValue: boolean
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
}

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

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

const formRef = ref()
const exporting = ref(false)
const deviceTypes = ref<any[]>([])
const organizations = ref<any[]>([])
const totalCount = ref(0)

const formData = reactive({
  selectedFields: [
    'assetCode',
    'assetName',
    'deviceTypeName',
    'brandName',
    'modelName',
    'serialNumber',
    'orgName',
    'location',
    'status',
    'purchaseDate',
    'purchasePrice'
  ],
  format: 'xlsx'
})

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

// 全选字段
const selectAllFields = () => {
  formData.selectedFields = [
    'assetCode',
    'assetName',
    'deviceTypeName',
    'brandName',
    'modelName',
    'serialNumber',
    'orgName',
    'location',
    'status',
    'purchaseDate',
    'purchasePrice',
    'warrantyExpireDate'
  ]
}

// 清空字段
const clearAllFields = () => {
  formData.selectedFields = []
}

// 获取设备类型列表
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)
  }
}

// 监听筛选条件变化，更新总数
watch(
  () => filters,
  async () => {
    // TODO: 调用API获取符合条件的数据总数
    totalCount.value = Math.floor(Math.random() * 1000)
  },
  { deep: true }
)

// 执行导出
const handleExport = async () => {
  if (formData.selectedFields.length === 0) {
    ElMessage.warning('请至少选择一个导出字段')
    return
  }

  exporting.value = true

  try {
    await exportAssets({
      fields: formData.selectedFields,
      format: formData.format,
      ...filters
    })

    ElMessage.success('导出成功')
    handleClose()
  } catch (error) {
    ElMessage.error('导出失败')
  } finally {
    exporting.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  visible.value = false
  // 重置表单
  setTimeout(() => {
    formData.selectedFields = [
      'assetCode',
      'assetName',
      'deviceTypeName',
      'brandName',
      'modelName',
      'serialNumber',
      'orgName',
      'location',
      'status',
      'purchaseDate',
      'purchasePrice'
    ]
    formData.format = 'xlsx'
    Object.assign(filters, {
      deviceTypeId: undefined,
      organizationId: undefined,
      status: undefined,
      keyword: ''
    })
  }, 300)
}

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

<style scoped lang="scss">
.field-actions {
  margin-top: 8px;
}
</style>
