<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { ElDialog, ElTable, ElTableColumn, ElButton, ElTabs, ElTabPane, ElInput, ElSegmented } from 'element-plus'
import { DbHst } from '#/components/db-hst'
import { handleRowOperation, codeRenderer } from '#/components/db-hst/tree'

const props = defineProps<{
  height?: number
}>()

const hstRef = ref<any>(null)
const dialogVisible = ref(false)
const activeTab = ref('global')
const currentRowData = ref<any>(null)
const formulaInput = ref('')

// 各个 Tab 的表格数据
const tabTableData = ref({
  global: [
    { seq: '1', code: 'GF001', name: '全局费用1', value: '100' },
    { seq: '2', code: 'GF002', name: '全局费用2', value: '200' },
  ],
  division: [
    { seq: '1', code: 'FB001', name: '分部分项1', value: '150' },
    { seq: '2', code: 'FB002', name: '分部分项2', value: '250' },
  ],
  measure: [
    { seq: '1', code: 'CS001', name: '措施项目1', value: '180' },
    { seq: '2', code: 'CS002', name: '措施项目2', value: '280' },
  ],
  other: [
    { seq: '1', code: 'QT001', name: '其他项目1', value: '120' },
    { seq: '2', code: 'QT002', name: '其他项目2', value: '220' },
  ],
  supplement: [
    { seq: '1', code: 'BC001', name: '补充费用1', value: '160' },
    { seq: '2', code: 'BC002', name: '补充费用2', value: '260' },
  ],
})

const dialogRenderer = (instance: any, td: HTMLElement, row: number, col: number, prop: string, value: any, cellProperties: any) => {
  td.innerHTML = ''
  td.style.position = 'relative'
  td.style.padding = '0 8px'
  
  // 创建文本容器
  const textSpan = document.createElement('span')
  textSpan.textContent = value || ''
  textSpan.style.display = 'inline-block'
  textSpan.style.verticalAlign = 'middle'
  textSpan.style.maxWidth = 'calc(100% - 24px)'
  textSpan.style.overflow = 'hidden'
  textSpan.style.textOverflow = 'ellipsis'
  textSpan.style.whiteSpace = 'nowrap'
  
  // 创建图标按钮
  const iconBtn = document.createElement('span')
  iconBtn.innerHTML = '⚙️'
  iconBtn.style.cursor = 'pointer'
  iconBtn.style.marginLeft = '4px'
  iconBtn.style.fontSize = '14px'
  iconBtn.style.verticalAlign = 'middle'
  iconBtn.style.float = 'right'
  
  iconBtn.addEventListener('click', (e) => {
    e.stopPropagation()
    const rowData = instance.getSourceDataAtRow(instance.toPhysicalRow(row))
    currentRowData.value = rowData
    dialogVisible.value = true
  })
  
  td.appendChild(textSpan)
  td.appendChild(iconBtn)
  
  return td
}
  
const columns = ref<any[]>([
  { type: 'text', data: 'seq', title: '序', width: 40 },
  { type: 'text', data: 'name', title: '费用名称', renderer: codeRenderer },
  { type: 'text', data: 'spec', title: '费用代码', width: 300,renderer: dialogRenderer },
  { type: 'text', data: 'cardinal', title: '计算基数（用户端不显示）', width: 200 },
])
let rowSchema: any = {}
// 根据 columns 的 data 字段生成对象结构
columns.value.forEach((col: any) => {
  if (col.data ) {
    rowSchema[col.data] = null
  }
})

const mockData = (() => {
  const data: any[] = []
  
  // 生成5个父级数据
  for (let i = 1; i <= 5; i++) {
    const parent: any = {
      seq: `${i}`,
      name: `费用名称${i}`,
      spec: `SPEC${String(i).padStart(3, '0')}`,
      cardinal: `基数${i}`,
      __children: [] as any[]
    }
    
    // 为每个父级生成3-5个子级
    const childCount = Math.floor(Math.random() * 3) + 3
    for (let j = 1; j <= childCount; j++) {
      const child: any = {
        seq: `${i}.${j}`,
        name: `子费用${i}-${j}`,
        spec: `SPEC${String(i).padStart(3, '0')}-${String(j).padStart(2, '0')}`,
        cardinal: `子基数${i}-${j}`,
        __children: []
      }
      parent.__children.push(child)
    }
    
    data.push(parent)
  }
  
  return data
})()

const settings = {
  data: mockData,
  dataSchema: rowSchema,
  colWidths: 120,
  columns: columns.value,
  rowHeaders: false,
  nestedRows: true,
  bindRowsWithHeaders: true,
  contextMenu: {
    items: {
      custom_row_above: {
        name: '在上方插入行',
        callback: function() {
          handleRowOperation(this, 'above')
        }
      },
      custom_row_below: {
        name: '在下方插入行',
        callback: function() {
          handleRowOperation(this, 'below')
        }
      },
      separator1: '---------',
      custom_add_child: {
        name: '添加子行',
        callback: function() {
          handleRowOperation(this, 'child')
        }
      },
      separator2: '---------',
      remove_row: {
        name: '删除行',
        callback: function() {
          handleRowOperation(this, 'delete')
        }
      },
      // separator3: '---------',
      // undo: {},
      // redo: {}
    }
  },
}
watch(
  () => props.height,
  (newHeight) => {
    console.log('MarketMaterials newHeight', newHeight)
    if (newHeight && hstRef.value?.hotInstance) {
      hstRef.value.hotInstance.updateSettings({
        height: newHeight - 50 - 15// 减去 tabs 头部和 padding 的高度,滚动条
      })
      hstRef.value.hotInstance.render()
    }
  },
  { immediate: true }
)

const value = ref('分部分项???')

const options = ['分部分项???', '措施项目???', '其他项目???', '单位汇总???']
onMounted(() => {
  setTimeout(() => {
    // if (hstRef.value) {
    //   hstRef.value.loadData(mockData)
    // }
  }, 100)
})
</script>

<template>
  <div class="w-full h-full">
    
    <div class="flex flex-col items-start gap-4">
      <ElSegmented v-model="value" :options="options" size="large" />
    </div>

    <DbHst ref="hstRef" :settings="settings" />

    <!-- 弹窗 -->
    <ElDialog v-model="dialogVisible" title="费用代码设置" width="60%" :close-on-click-modal="false">
      <div style="margin-bottom: 16px;">
        <div style="color: #909399; font-size: 13px; margin-bottom: 8px;">
          提示: 现在书写的公式只能调用在当前项目以前的取费和系统参数
        </div>
        <ElInput 
          v-model="formulaInput" 
          placeholder="请输入公式" 
          clearable
        />
      </div>
      
      <ElTabs v-model="activeTab">
        <ElTabPane label="全局费用" name="global">
          <ElTable :data="tabTableData.global" border style="width: 100%" max-height="400">
            <ElTableColumn prop="seq" label="序号" width="80" />
            <ElTableColumn prop="code" label="费用代号" width="150" />
            <ElTableColumn prop="name" label="费用名称" min-width="200" />
            <ElTableColumn prop="value" label="值" width="120" />
          </ElTable>
        </ElTabPane>
        
        <ElTabPane label="分部分项" name="division">
          <ElTable :data="tabTableData.division" border style="width: 100%" max-height="400">
            <ElTableColumn prop="seq" label="序号" width="80" />
            <ElTableColumn prop="code" label="费用代号" width="150" />
            <ElTableColumn prop="name" label="费用名称" min-width="200" />
            <ElTableColumn prop="value" label="值" width="120" />
          </ElTable>
        </ElTabPane>
        
        <ElTabPane label="措施项目" name="measure">
          <ElTable :data="tabTableData.measure" border style="width: 100%" max-height="400">
            <ElTableColumn prop="seq" label="序号" width="80" />
            <ElTableColumn prop="code" label="费用代号" width="150" />
            <ElTableColumn prop="name" label="费用名称" min-width="200" />
            <ElTableColumn prop="value" label="值" width="120" />
          </ElTable>
        </ElTabPane>
        
        <ElTabPane label="其他项目" name="other">
          <ElTable :data="tabTableData.other" border style="width: 100%" max-height="400">
            <ElTableColumn prop="seq" label="序号" width="80" />
            <ElTableColumn prop="code" label="费用代号" width="150" />
            <ElTableColumn prop="name" label="费用名称" min-width="200" />
            <ElTableColumn prop="value" label="值" width="120" />
          </ElTable>
        </ElTabPane>
        
        <ElTabPane label="补充费用" name="supplement">
          <ElTable :data="tabTableData.supplement" border style="width: 100%" max-height="400">
            <ElTableColumn prop="seq" label="序号" width="80" />
            <ElTableColumn prop="code" label="费用代号" width="150" />
            <ElTableColumn prop="name" label="费用名称" min-width="200" />
            <ElTableColumn prop="value" label="值" width="120" />
          </ElTable>
        </ElTabPane>
      </ElTabs>
      
      <template #footer>
        <ElButton @click="dialogVisible = false">取消</ElButton>
        <ElButton type="primary" @click="dialogVisible = false">确定</ElButton>
      </template>
    </ElDialog>
  </div>
</template>
