<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue'
import { Page } from '@vben/common-ui';
import { ElSplitter,ElSplitterPanel,ElCard,ElInput,ElButton,ElDialog,ElUpload,ElImage,ElTable,ElTableColumn,ElDatePicker,
  ElMessage,ElForm,ElFormItem,ElRow,ElCol,ElTreeV2 } from 'element-plus';
import { useElementSize } from '@vueuse/core'
import { DbTree } from '#/components/db-tree';
import { DbHst } from '#/components/db-hst';
import { IconifyIcon } from '@vben/icons';
import type { UploadProps } from 'element-plus'
import { computed } from 'vue'

const containerRef = ref<HTMLElement | null>(null)
const { height: containerHeight } = useElementSize(containerRef)
type Tree = { id: string; label: string; children?: Tree[] }
const categoryTreeData = ref<Tree[]>([
  {
    id: '1',
    label: '信息价目录',
    children: [
      {
        id: '2',
        label: '广东',
        children: [
          { id: '3', label: '信息价1' },
          { id: '4', label: '信息价2' },
          { id: '5', label: '信息价3' }
        ]
      }
    ]
  },
  {
    id: '11',
    label: '信息价目录2',
    children: [
      {
        id: '12',
        label: '广西',
        children: [
          { id: '13', label: '信息价5' },
          { id: '14', label: '信息价6' },
          { id: '15', label: '信息价7' }
        ]
      }
    ]
  }
])

// 上传对话框相关
const uploadDialogVisible = ref(false)
const currentUploadRow = ref<number>(0)
const currentUploadCol = ref<number>(0)
const uploadImageUrl = ref<string>('')

// 图片预览相关
const previewImageUrl = ref<string>('')
const previewVisible = ref(false)

// 附件管理相关
const attachmentDialogVisible = ref(false)
const attachmentDateRange = ref<[Date, Date] | null>(null)
const attachmentTableData = ref<any[]>([
  {
    id: 1,
    name: '广东省信息价',
    priceDate: '2024-01',
    attachment: '广东省信息价_2024-01.pdf',
    attachmentUrl: ''
  },
  {
    id: 2,
    name: '广东省信息价',
    priceDate: '2024-02',
    attachment: '广东省信息价_2024-02.pdf',
    attachmentUrl: ''
  },
  {
    id: 3,
    name: '广西省信息价',
    priceDate: '2024-01',
    attachment: '广西省信息价_2024-01.pdf',
    attachmentUrl: ''
  }
])

const filteredAttachmentData = computed(() => {
  if (!attachmentDateRange.value || attachmentDateRange.value.length !== 2) {
    return attachmentTableData.value
  }
  
  const [startDate, endDate] = attachmentDateRange.value
  return attachmentTableData.value.filter(item => {
    const itemDate = new Date(item.priceDate)
    return itemDate >= startDate && itemDate <= endDate
  })
})

// 新增对话框相关
const addDialogVisible = ref(false)
const addFormRef = ref()
const addForm = ref({
  name: '',
  priceDate: ''
})

const addFormRules = {
  name: [
    { required: true, message: '请输入信息价名称', trigger: 'blur' }
  ],
  priceDate: [
    { required: true, message: '请选择价格时间', trigger: 'change' }
  ]
}

// 复制（软件商）对话框相关
const copyDialogVisible = ref(false)
const copyTableData = ref<any[]>([
  {
    id: 1,
    serialNumber: '001',
    tenantName: '租户A',
    specialty: '建筑工程',
    region: '广东省',
    priceDate: '2024-01',
    priceName: '广东省信息价',
    priceCount: 150,
    attachment: '附件1.pdf',
    published: true
  },
  {
    id: 2,
    serialNumber: '002',
    tenantName: '租户B',
    specialty: '市政工程',
    region: '广西省',
    priceDate: '2024-02',
    priceName: '广西省信息价',
    priceCount: 200,
    attachment: '附件2.pdf',
    published: false
  },
  {
    id: 3,
    serialNumber: '003',
    tenantName: '租户C',
    specialty: '装饰装修',
    region: '广东省',
    priceDate: '2024-03',
    priceName: '广东省装修信息价',
    priceCount: 180,
    attachment: '',
    published: true
  }
])

// 更多价格对话框相关
const morePriceDialogVisible = ref(false)
const currentPriceRow = ref<number>(0)
const morePriceTableData = ref<any[]>([
  {
    id: 1,
    priceDate: '2024-01',
    priceExcludeTax: '1250.00',
    taxRate: '13',
    priceIncludeTax: '1412.50'
  },
  {
    id: 2,
    priceDate: '2024-02',
    priceExcludeTax: '1280.00',
    taxRate: '13',
    priceIncludeTax: '1446.40'
  },
  {
    id: 3,
    priceDate: '2024-03',
    priceExcludeTax: '1300.00',
    taxRate: '13',
    priceIncludeTax: '1469.00'
  }
])

// 历史信息对话框相关
const historyDialogVisible = ref(false)
const historyTreeData = ref<any[]>([
  {
    id: '1',
    label: '2024年',
    children: [
      {
        id: '1-1',
        label: '2024-01',
        children: [
          { id: '1-1-1', label: '广东省信息价' },
          { id: '1-1-2', label: '广西省信息价' }
        ]
      },
      {
        id: '1-2',
        label: '2024-02',
        children: [
          { id: '1-2-1', label: '广东省信息价' },
          { id: '1-2-2', label: '广西省信息价' }
        ]
      }
    ]
  },
  {
    id: '2',
    label: '2023年',
    children: [
      {
        id: '2-1',
        label: '2023-12',
        children: [
          { id: '2-1-1', label: '广东省信息价' },
          { id: '2-1-2', label: '广西省信息价' }
        ]
      }
    ]
  }
])

const historyTableData = ref<any[]>([
  {
    id: 1,
    name: '水泥',
    model: 'P.O 42.5',
    unit: '吨',
    drawing: '',
    category: '材料'
  },
  {
    id: 2,
    name: '钢筋',
    model: 'HRB400E Φ12',
    unit: '吨',
    drawing: '',
    category: '材料'
  },
  {
    id: 3,
    name: '混凝土',
    model: 'C30',
    unit: '立方米',
    drawing: '',
    category: '材料'
  },
  {
    id: 4,
    name: '砖',
    model: 'MU10',
    unit: '千块',
    drawing: '',
    category: '材料'
  },
  {
    id: 5,
    name: '挖掘机',
    model: '1m³',
    unit: '台班',
    drawing: '',
    category: '机械'
  }
])

const selectedHistoryNode = ref<any>(null)

const uploadPhotoRender = (instance: any, td: HTMLElement, row: number, col: number, prop: string, value: any, cellProperties: any) => {
  td.innerHTML = '';
  td.style.padding = '2px';
  td.style.display = 'flex';
  td.style.alignItems = 'center';
  td.style.justifyContent = 'space-between';
  td.style.gap = '4px';

  // 左侧图片容器
  const imgContainer = document.createElement('div');
  imgContainer.style.flex = '1';
  imgContainer.style.display = 'flex';
  imgContainer.style.alignItems = 'center';
  imgContainer.style.overflow = 'hidden';

  if (value) {
    const img = document.createElement('img');
    img.src = value
    img.style.maxWidth = '40px';
    img.style.maxHeight = '40px';
    img.style.objectFit = 'contain';
    img.style.cursor = 'pointer';
    
    // 点击图片预览
    img.addEventListener('click', (event) => {
      event.stopPropagation();
      previewImageUrl.value = value;
      previewVisible.value = true;
    });
    
    img.addEventListener('mousedown', (event) => {
      event.preventDefault();
    });
    imgContainer.appendChild(img);
  }

  // 右侧上传图标
  const uploadIcon = document.createElement('span');
  uploadIcon.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24"><path fill="currentColor" d="M11 16V7.85l-2.6 2.6L7 9l5-5l5 5l-1.4 1.45l-2.6-2.6V16zm-5 4q-.825 0-1.412-.587T4 18v-3h2v3h12v-3h2v3q0 .825-.587 1.413T18 20z"/></svg>';
  uploadIcon.style.cursor = 'pointer';
  uploadIcon.style.color = '#979797';
  uploadIcon.style.display = 'flex';
  uploadIcon.style.alignItems = 'center';
  uploadIcon.style.flexShrink = '0';
  
  uploadIcon.addEventListener('click', (event) => {
    event.stopPropagation();
    currentUploadRow.value = row;
    currentUploadCol.value = col;
    uploadImageUrl.value = value || '';
    uploadDialogVisible.value = true;
  });

  uploadIcon.addEventListener('mousedown', (event) => {
    event.preventDefault();
  });

  td.appendChild(imgContainer);
  td.appendChild(uploadIcon);

  return td;
}

const morePriceRender = (instance: any, td: HTMLElement, row: number, col: number, prop: string, value: any, cellProperties: any) => {
  td.innerHTML = '';
  td.style.padding = '2px';
  td.style.display = 'flex';
  td.style.alignItems = 'center';
  td.style.justifyContent = 'space-between';
  td.style.gap = '4px';

  // 左侧价格文本
  const priceText = document.createElement('span');
  priceText.textContent = value || '';
  priceText.style.flex = '1';
  priceText.style.overflow = 'hidden';
  priceText.style.textOverflow = 'ellipsis';
  priceText.style.whiteSpace = 'nowrap';

  // 右侧选择图标
  const selectIcon = document.createElement('span');
  selectIcon.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24"><path fill="currentColor" d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2m0 16H5V5h14zM7 10h2v7H7zm4-3h2v10h-2zm4 6h2v4h-2z"/></svg>';
  selectIcon.style.cursor = 'pointer';
  selectIcon.style.color = '#979797';
  selectIcon.style.display = 'flex';
  selectIcon.style.alignItems = 'center';
  selectIcon.style.flexShrink = '0';
  
  selectIcon.addEventListener('click', (event) => {
    event.stopPropagation();
    currentPriceRow.value = row;
    morePriceDialogVisible.value = true;
  });

  selectIcon.addEventListener('mousedown', (event) => {
    event.preventDefault();
  });

  td.appendChild(priceText);
  td.appendChild(selectIcon);

  return td;
}
const columns = ref<any[]>([
  {type:'text',data:'code',title:'序号编码'},
  {type:'text',data:'name',title:'名称'},
  {type:'text',data:'model',title:'型号规格'},
  {type:'text',data:'unit',title:'单位',width: 50},
  {type:'text',data:'priceExcludeTax',title:'除税编制价'},
  {type:'text',data:'taxRate',title:'税率%',width: 60},
  {type:'text',data:'priceIncludeTax',title:'含税编制价'},
  {type:'text',data:'drawing',title:'图样(仅供参考)',renderer: uploadPhotoRender},
  {type:'text',data:'category',title:'分类',renderer: 'db-dropdown',
  source: ['措施类1', '措施类2', '措施类3', '措施类3'],
  readOnly: true,},
  {type:'text',data:'servicePrice',title:'劳务单价',renderer: morePriceRender},
  {type:'text',data:'remark',title:'备注'},
{type:'text',data:'',title:'操作'},
])
// const colHeaders = ref<string[]>(topColHeaders)

const hstRef = ref<any>(null)

const mockData = ()=>{
    // 生成模拟数据
    const mockData = Array.from({ length: 30 }, (_, index) => ({
      code: `DTL${String(index + 1).padStart(6, '0')}`,
      name: `明细项目${index + 1}`,
      model: `型号${index + 1}-规格${index + 1}`,
      unit: ['个', '米', '吨', '套', '台'][index % 5],
      priceExcludeTax: (Math.random() * 1000 + 100).toFixed(2),
      taxRate: ['13', '9', '6', '3'][index % 4],
      priceIncludeTax: (Math.random() * 1200 + 120).toFixed(2),
      drawing: ``,
      category: ['材料', '设备', '人工', '机械'][index % 4],
      servicePrice: (Math.random() * 500 + 50).toFixed(2),
      remark: `备注${index + 1}`,
    }))
    return mockData;
}
let dbSettings = {
  data:mockData(),
  columns: columns.value,
}
const searchText = ref('')

const categoryHandleSelect = (node: Tree) => {
  console.log('categoryhandleSelect',node)
}

const handleAttachment = () => {
  attachmentDialogVisible.value = true
}

const handleAttachmentUpload = (row: any) => {
  // 创建文件选择器
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = '.pdf,.doc,.docx,.xls,.xlsx,.zip'
  
  input.onchange = (e: any) => {
    const file = e.target.files[0]
    if (file) {
      // 这里应该上传到服务器，现在只是模拟
      const fileUrl = URL.createObjectURL(file)
      row.attachment = file.name
      row.attachmentUrl = fileUrl
      ElMessage.success('上传成功')
    }
  }
  
  input.click()
}

const handleAttachmentDownload = (row: any) => {
  if (!row.attachmentUrl && !row.attachment) {
    ElMessage.warning('暂无附件可下载')
    return
  }
  
  // 这里应该从服务器下载，现在只是模拟
  if (row.attachmentUrl) {
    const link = document.createElement('a')
    link.href = row.attachmentUrl
    link.download = row.attachment
    link.click()
    ElMessage.success('下载成功')
  } else {
    ElMessage.info('模拟下载: ' + row.attachment)
  }
}

const handleAttachmentDelete = (row: any) => {
  const index = attachmentTableData.value.findIndex(item => item.id === row.id)
  if (index > -1) {
    attachmentTableData.value.splice(index, 1)
    ElMessage.success('删除成功')
  }
}

const handleAttachmentDialogClose = () => {
  attachmentDialogVisible.value = false
  attachmentDateRange.value = null
}

const handleAdd = () => {
  addDialogVisible.value = true
}

const handleAddSubmit = async () => {
  if (!addFormRef.value) return
  
  await addFormRef.value.validate((valid: boolean) => {
    if (valid) {
      // 这里应该调用后端接口保存数据
      const newId = attachmentTableData.value.length > 0 
        ? Math.max(...attachmentTableData.value.map(item => item.id)) + 1 
        : 1
      
      attachmentTableData.value.push({
        id: newId,
        name: addForm.value.name,
        priceDate: addForm.value.priceDate,
        attachment: '',
        attachmentUrl: ''
      })
      
      ElMessage.success('新增成功')
      handleAddDialogClose()
    } else {
      ElMessage.error('请填写完整信息')
      return false
    }
  })
}

const handleAddDialogClose = () => {
  addDialogVisible.value = false
  addFormRef.value?.resetFields()
  addForm.value = {
    name: '',
    priceDate: ''
  }
}

const handleCopy = () => {
  copyDialogVisible.value = true
}

const handleTogglePublish = (row: any) => {
  row.published = !row.published
  const status = row.published ? '已发布' : '未发布'
  ElMessage.success(`状态已更新为：${status}`)
}

const handleCopyDialogClose = () => {
  copyDialogVisible.value = false
}

const handleHistory = () => {
  historyDialogVisible.value = true
}

const handleHistoryTreeSelect = (node: any) => {
  selectedHistoryNode.value = node
  console.log('选中的历史节点:', node)
  // 这里可以根据选中的节点加载对应的表格数据
}

const handleHistoryDialogClose = () => {
  historyDialogVisible.value = false
  selectedHistoryNode.value = null
}

const handleMorePriceDialogClose = () => {
  morePriceDialogVisible.value = false
}

const handleSelectPrice = (row: any) => {
  // 选择价格后更新表格数据
  if (hstRef.value?.hotInstance) {
    const colIndex = hstRef.value.hotInstance.propToCol('priceExcludeTax')
    hstRef.value.hotInstance.setDataAtCell(currentPriceRow.value, colIndex, row.priceExcludeTax)
    
    const taxRateIndex = hstRef.value.hotInstance.propToCol('taxRate')
    hstRef.value.hotInstance.setDataAtCell(currentPriceRow.value, taxRateIndex, row.taxRate)
    
    const priceIncludeTaxIndex = hstRef.value.hotInstance.propToCol('priceIncludeTax')
    hstRef.value.hotInstance.setDataAtCell(currentPriceRow.value, priceIncludeTaxIndex, row.priceIncludeTax)
  }
  
  ElMessage.success('价格已更新')
  handleMorePriceDialogClose()
}
const onSearch = () => {
  console.log('onSearch')
}

// 上传处理
const handleUploadSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  // 这里假设上传成功后返回图片URL
  // 实际项目中需要根据后端返回的数据结构调整
  const imageUrl = URL.createObjectURL(uploadFile.raw!)
  uploadImageUrl.value = imageUrl
  
  // 更新表格数据
  if (hstRef.value?.hotInstance) {
    hstRef.value.hotInstance.setDataAtCell(currentUploadRow.value, currentUploadCol.value, imageUrl)
  }
}

const handleBeforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (!rawFile.type.startsWith('image/')) {
    console.error('只能上传图片文件!')
    return false
  }
  if (rawFile.size / 1024 / 1024 > 5) {
    console.error('图片大小不能超过 5MB!')
    return false
  }
  return true
}

const handleUploadChange: UploadProps['onChange'] = (uploadFile) => {
  if (uploadFile.raw) {
    const imageUrl = URL.createObjectURL(uploadFile.raw)
    uploadImageUrl.value = imageUrl
    
    // 更新表格数据
    if (hstRef.value?.hotInstance) {
      hstRef.value.hotInstance.setDataAtCell(currentUploadRow.value, currentUploadCol.value, imageUrl)
    }
    handleDialogClose()
  }
}

const handleRemoveImage = () => {
  uploadImageUrl.value = ''
  if (hstRef.value?.hotInstance) {
    hstRef.value.hotInstance.setDataAtCell(currentUploadRow.value, currentUploadCol.value, '')
  }
}

const handleDialogClose = () => {
  uploadDialogVisible.value = false
}

const handlePreviewClose = () => {
  previewVisible.value = false
  previewImageUrl.value = ''
}
function onHstHeight(height: number){
  if (hstRef.value?.hotInstance) {
    hstRef.value.hotInstance.updateSettings({
      height: height-15-43
    })
    
    hstRef.value.hotInstance.render()
    console.log('onResizeEnd-onHstHeight',height);
  }
}


onMounted(() => {
  setTimeout(() => {
    onHstHeight(containerHeight.value)
  }, 200);
})
onUnmounted(() => {
})

</script>

<template>
<Page auto-content-height>
   <ElSplitter >
      <ElSplitterPanel collapsible size="15%" :min="200">
        <ElCard class="w-full h-full border-radius-0" body-class="!p-0 h-full" ref="containerRef">
            <DbTree :height="containerHeight" :data="categoryTreeData" @select="categoryHandleSelect" :defaultExpandedKeys="2"  :search="false" />
        </ElCard>
      </ElSplitterPanel>
      <ElSplitterPanel collapsible :min="200">
        <ElCard class="w-full h-full border-radius-0" body-class="!p-0 h-full">
            <template #header>
              <div class="flex items-center justify-between">
                <ElInput v-model="searchText" placeholder="搜索" clearable style="width: 200px" >
                     <template #append>
                         <ElButton @click="onSearch" >
                            <IconifyIcon icon="lucide:search" class="cursor-pointer"/>
                        </ElButton>
                    </template>
                </ElInput>
                <div class="flex gap-2">
                  <ElButton @click="handleAttachment" type="primary">附件</ElButton>
                  <ElButton @click="handleAdd" type="primary">新增</ElButton>
                  <ElButton @click="handleCopy" type="primary">复制（软件商按钮）</ElButton>
                  <ElButton @click="handleHistory" type="primary">调用历史信息</ElButton>
                </div>
              </div>
            </template>
            <DbHst ref="hstRef" :settings="dbSettings"></DbHst>
        </ElCard>
      </ElSplitterPanel>
    </ElSplitter>

    <!-- 上传图片对话框 -->
    <ElDialog 
      v-model="uploadDialogVisible" 
      title="上传图片" 
      width="500px"
      @close="handleDialogClose"
    >
      <div class="upload-container">
        <!-- <div v-if="uploadImageUrl" class="image-preview">
          <img :src="uploadImageUrl" alt="预览图片" />
          <ElButton type="danger" size="small" @click="handleRemoveImage" class="remove-btn">
            删除图片
          </ElButton>
        </div> -->
        
        <ElUpload
          class="upload-demo"
          drag
          :auto-upload="false"
          :show-file-list="false"
          :before-upload="handleBeforeUpload"
          :on-change="handleUploadChange"
          accept="image/*"
        >
          <div class="flex flex-col items-center justify-center py-5">
            <IconifyIcon icon="ep:upload-filled" class="mb-2.5 text-gray-400" style="font-size: 2.75rem !important;"/>
            <div class="ant-upload-text text-base text-gray-400">
                拖拽文件至此，或者
                <em class="cursor-pointer not-italic text-blue-500">
                  选择文件
                </em>
              </div>
              <div class="mt-2.5 text-sm text-gray-400">
                已支持 pg/png 每个文件不超过
                1 MB。
              </div>
          </div>
        </ElUpload>
      </div>
      
      <template #footer>
        <ElButton @click="handleDialogClose">关闭</ElButton>
      </template>
    </ElDialog>

    <!-- 图片预览对话框 -->
    <ElDialog 
      v-model="previewVisible" 
      title="图片预览" 
      width="800px"
      @close="handlePreviewClose"
    >
      <div class="preview-image-container">
        <ElImage 
          :src="previewImageUrl" 
          fit="contain"
          :preview-src-list="[previewImageUrl]"
          :initial-index="0"
          style="width: 100%; max-height: 600px;"
        />
      </div>
      
      <template #footer>
        <ElButton @click="handlePreviewClose">关闭</ElButton>
      </template>
    </ElDialog>

    <!-- 附件管理对话框 -->
    <ElDialog 
      v-model="attachmentDialogVisible" 
      title="附件管理" 
      width="900px"
      @close="handleAttachmentDialogClose"
    >
      <div class="attachment-container">
        <!-- 时间查询 -->
        <div class="mb-4 flex items-center gap-2">
          <span>价格时间段：</span>
          <ElDatePicker
            v-model="attachmentDateRange"
            type="monthrange"
            range-separator="至"
            start-placeholder="开始月份"
            end-placeholder="结束月份"
            format="YYYY-MM"
            value-format="YYYY-MM"
            style="width: 300px"
          />
        </div>

        <!-- 附件表格 -->
        <ElTable :data="filteredAttachmentData" border stripe style="width: 100%">
          <ElTableColumn prop="name" label="信息价名称" width="200" />
          <ElTableColumn prop="priceDate" label="价格时间段" width="150" />
          <ElTableColumn prop="attachment" label="附件" min-width="200">
            <template #default="{ row }">
              <span v-if="row.attachment">{{ row.attachment }}</span>
              <span v-else class="text-gray-400">暂无附件</span>
            </template>
          </ElTableColumn>
          <ElTableColumn label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <div class="flex gap-2">
                <ElButton 
                  type="primary" 
                  size="small" 
                  @click="handleAttachmentUpload(row)"
                >
                  上传
                </ElButton>
                <ElButton 
                  type="success" 
                  size="small" 
                  @click="handleAttachmentDownload(row)"
                  :disabled="!row.attachment"
                >
                  下载
                </ElButton>
                <ElButton 
                  type="danger" 
                  size="small" 
                  @click="handleAttachmentDelete(row)"
                >
                  删除
                </ElButton>
              </div>
            </template>
          </ElTableColumn>
        </ElTable>
      </div>
      
      <template #footer>
        <ElButton @click="handleAttachmentDialogClose">关闭</ElButton>
      </template>
    </ElDialog>

    <!-- 新增对话框 -->
    <ElDialog 
      v-model="addDialogVisible" 
      title="新增信息价" 
      width="500px"
      @close="handleAddDialogClose"
    >
      <ElForm 
        ref="addFormRef" 
        :model="addForm" 
        :rules="addFormRules" 
        label-width="120px"
      >
        <ElFormItem label="信息价名称" prop="name">
          <ElInput 
            v-model="addForm.name" 
            placeholder="请输入信息价名称"
            clearable
          />
        </ElFormItem>
        
        <ElFormItem label="价格时间" prop="priceDate">
          <ElDatePicker
            v-model="addForm.priceDate"
            type="month"
            placeholder="请选择价格时间"
            format="YYYY-MM"
            value-format="YYYY-MM"
            style="width: 100%"
          />
        </ElFormItem>
      </ElForm>
      
      <template #footer>
        <div class="flex justify-end gap-2">
          <ElButton @click="handleAddDialogClose">取消</ElButton>
          <ElButton type="primary" @click="handleAddSubmit">确定</ElButton>
        </div>
      </template>
    </ElDialog>

    <!-- 复制（软件商）对话框 -->
    <ElDialog 
      v-model="copyDialogVisible" 
      title="软件商信息价管理" 
      width="1200px"
      @close="handleCopyDialogClose"
    >
      <div class="copy-container">
        <!-- 软件商表格 -->
        <ElTable :data="copyTableData" border stripe style="width: 100%" max-height="600">
          <ElTableColumn prop="serialNumber" label="序号" width="80" fixed="left" />
          <ElTableColumn prop="tenantName" label="租户名称" width="120" />
          <ElTableColumn prop="specialty" label="专业" width="120" />
          <ElTableColumn prop="region" label="地区" width="120" />
          <ElTableColumn prop="priceDate" label="价格时间段" width="120" />
          <ElTableColumn prop="priceName" label="信息价名称" width="150" />
          <ElTableColumn prop="priceCount" label="信息价条数" width="120" align="center" />
          <ElTableColumn prop="attachment" label="附件" min-width="150">
            <template #default="{ row }">
              <span v-if="row.attachment">{{ row.attachment }}</span>
              <span v-else class="text-gray-400">暂无附件</span>
            </template>
          </ElTableColumn>
          <ElTableColumn label="操作" width="120" fixed="right" align="center">
            <template #default="{ row }">
              <ElButton 
                :type="row.published ? 'success' : 'info'" 
                size="small" 
                @click="handleTogglePublish(row)"
              >
                {{ row.published ? '已发布' : '未发布' }}
              </ElButton>
            </template>
          </ElTableColumn>
        </ElTable>
      </div>
      
      <template #footer>
        <ElButton @click="handleCopyDialogClose">关闭</ElButton>
      </template>
    </ElDialog>

    <!-- 历史信息对话框 -->
    <ElDialog 
      v-model="historyDialogVisible" 
      title="调用历史信息" 
      width="1200px"
      @close="handleHistoryDialogClose"
    >
      <div class="history-container">
        <ElRow :gutter="20">
          <!-- 左侧树形结构 -->
          <ElCol :span="6">
            <div class="history-tree-container">
              <ElTreeV2
                :data="historyTreeData"
                :props="{ label: 'label', children: 'children' }"
                :height="500"
                @node-click="handleHistoryTreeSelect"
                default-expand-all
              />
            </div>
          </ElCol>
          
          <!-- 右侧表格 -->
          <ElCol :span="18">
            <div class="history-table-container">
              <ElTable :data="historyTableData" border stripe style="width: 100%" max-height="500">
                <ElTableColumn prop="name" label="名称" width="150" />
                <ElTableColumn prop="model" label="型号规格" width="150" />
                <ElTableColumn prop="unit" label="单位" width="100" align="center" />
                <ElTableColumn prop="drawing" label="图样(仅供参考)" width="150">
                  <template #default="{ row }">
                    <span v-if="row.drawing">{{ row.drawing }}</span>
                    <span v-else class="text-gray-400">暂无图样</span>
                  </template>
                </ElTableColumn>
                <ElTableColumn prop="category" label="分类" min-width="120" />
              </ElTable>
            </div>
          </ElCol>
        </ElRow>
      </div>
      
      <template #footer>
        <div class="flex justify-end gap-2">
          <ElButton @click="handleHistoryDialogClose">取消</ElButton>
          <ElButton type="primary" @click="handleHistoryDialogClose">确定</ElButton>
        </div>
      </template>
    </ElDialog>

    <!-- 更多价格对话框 -->
    <ElDialog 
      v-model="morePriceDialogVisible" 
      title="历史价格信息" 
      width="700px"
      @close="handleMorePriceDialogClose"
    >
      <div class="more-price-container">
        <ElTable :data="morePriceTableData" border stripe style="width: 100%" max-height="400">
          <ElTableColumn prop="priceDate" label="价格时间段" width="150" align="center" />
          <ElTableColumn prop="priceExcludeTax" label="除税单价" width="150" align="right" />
          <ElTableColumn prop="taxRate" label="税率" width="100" align="center">
            <template #default="{ row }">
              {{ row.taxRate }}%
            </template>
          </ElTableColumn>
          <ElTableColumn prop="priceIncludeTax" label="含税单价" width="150" align="right" />
          <ElTableColumn label="操作" width="100" align="center" fixed="right">
            <template #default="{ row }">
              <ElButton 
                type="primary" 
                size="small" 
                @click="handleSelectPrice(row)"
              >
                选择
              </ElButton>
            </template>
          </ElTableColumn>
        </ElTable>
      </div>
      
      <template #footer>
        <ElButton @click="handleMorePriceDialogClose">关闭</ElButton>
      </template>
    </ElDialog>
</Page>
</template>

<style lang="css">
    .el-card__header{
        padding: 5px;
    }
    
    .upload-container {
      display: flex;
      flex-direction: column;
      gap: 20px;
    }
    
    .image-preview {
      position: relative;
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 10px;
      padding: 20px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      background-color: #f5f7fa;
    }
    
    .image-preview img {
      max-width: 100%;
      max-height: 300px;
      object-fit: contain;
    }
    
    .upload-demo {
      width: 100%;
    }
    
    .preview-image-container {
      display: flex;
      justify-content: center;
      align-items: center;
      min-height: 400px;
    }
    
    .attachment-container {
      padding: 10px 0;
    }
    
    .el-form {
      padding: 20px 20px 0;
    }
    
    .copy-container {
      padding: 10px 0;
    }
    
    .history-container {
      padding: 10px 0;
    }
    
    .history-tree-container {
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      padding: 10px;
      background-color: #f5f7fa;
    }
    
    .history-table-container {
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      padding: 10px;
    }
    
    .more-price-container {
      padding: 10px 0;
    }
</style>
