<script setup lang="ts">
import { onMounted, onUnmounted, reactive, ref, nextTick, createVNode, render, watch,computed } from 'vue'
import { Page } from '@vben/common-ui';
import { ElSplitter,ElSplitterPanel,ElCard,ElDialog,ElTable,ElTableColumn,ElButton,ElInput,ElAlert } from 'element-plus';
import { useElementSize } from '@vueuse/core'
import { DbTree } from '#/components/db-tree';
import { DbHst } from '#/components/db-hst';

const containerRef = ref<HTMLElement | null>(null)
const { height: containerHeight } = useElementSize(containerRef)

type Tree = { id: string; label: string; children?: Tree[] }
const treeData = ref<Tree[]>([
  {
    id: '1',
    label: '定额库',
    children: [
      {
        id: '2',
        label: '广东',
        children: [
          { id: '3', label: '广东工民建工料机定额' },
          { id: '4', label: '广东公路工料机定额' },
          { id: '5', label: '广东水利工料机定额' }
        ]
      }
    ]
  },
  {
    id: '11',
    label: '定额库2',
    children: [
      {
        id: '12',
        label: '广西',
        children: [
          { id: '13', label: '工料机1费率库' },
          { id: '14', label: '工料机2费率库' },
          { id: '15', label: '工料机3费率库' }
        ]
      }
    ]
  }
])

const calcRenderer = (instance: any, td: HTMLElement, row: number, col: number, prop: string, value: any, cellProperties: any) => {
  // 清空单元格内容
  td.innerHTML = ''
  
  // 创建容器
  const container = document.createElement('div')
  container.style.cssText = 'display: flex; justify-content: space-between; align-items: center; width: 100%; height: 100%; padding: 0 5px;'
  
  // 创建文本显示
  const textSpan = document.createElement('span')
  textSpan.textContent = value || ''
  textSpan.style.cssText = 'flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;'
  
  // 创建编辑图标
  const iconSpan = document.createElement('span')
  iconSpan.innerHTML = '<svg viewBox="0 0 1024 1024" width="14" height="14" fill="currentColor"><path d="M862.709333 116.042667a32 32 0 0 1 45.248 0l0.032 0.032a32 32 0 0 1 0 45.248L455.445333 613.866667a32 32 0 1 1-45.258666-45.258667L862.709333 116.042667z m-64 64L346.165333 632.586667a32 32 0 0 0 45.258667 45.258666L844.010667 225.28a32 32 0 1 0-45.258667-45.258667zM704 512a32 32 0 0 1 64 0v352a96 96 0 0 1-96 96H160a96 96 0 0 1-96-96V352a96 96 0 0 1 96-96h352a32 32 0 0 1 0 64H160a32 32 0 0 0-32 32v512a32 32 0 0 0 32 32h512a32 32 0 0 0 32-32V512z"/></svg>'
  iconSpan.style.cssText = 'cursor: pointer; margin-left: 5px; display: inline-flex; align-items: center; color: black;'
  iconSpan.title = '计算基数设置'
  
  // 点击图标打开弹窗
  iconSpan.addEventListener('click', (e) => {
    e.stopPropagation()
    openCalcDialog(row)
  })
  
  container.appendChild(textSpan)
  container.appendChild(iconSpan)
  td.appendChild(container)
  
  return td
}

const topColumns = ref<any[]>([
{type:'text',data:'name',title:'名称'},
{type:'text',data:'calcBase',title:'计算基数', renderer: calcRenderer},
{type:'text',data:'rateCode',title:'费率代号(%)'},
{type:'text',data:'code',title:'代号'},
{type:'text',data:'costOwnership',title:'费用归属'},
{type:'text',data:'baseDesc',title:'基数说明'},
{type:'checkbox',data:'variable',title:'变量'}
])


const topHstRef = ref<any>(null)
let rowSchema: any = {}
// 根据 columns 的 data 字段生成对象结构
topColumns.value.forEach((col: any) => {
  if (col.data ) {
    rowSchema[col.data] = null
  }
})
// console.log(rowSchema)
// Dialog相关状态
const dialogVisible = ref(false)
const calcDialogVisible = ref(false)
const currentRow = ref<number>(0)

// 生成随机4位英文字母
const generateRandomCode = () => {
  const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  let result = ''
  for (let i = 0; i < 4; i++) {
    result += letters.charAt(Math.floor(Math.random() * letters.length))
  }
  return result
}

// 计算基数弹窗数据
const calcTableData = ref<any[]>([
  { category: '直接费', priceExTax: generateRandomCode(), priceInTax: generateRandomCode(), compileExTax: generateRandomCode(), compileInTax: generateRandomCode() },
  { category: '间接费', priceExTax: generateRandomCode(), priceInTax: generateRandomCode(), compileExTax: generateRandomCode(), compileInTax: generateRandomCode() },
  { category: '利润', priceExTax: generateRandomCode(), priceInTax: generateRandomCode(), compileExTax: generateRandomCode(), compileInTax: generateRandomCode() },
  { category: '税金', priceExTax: generateRandomCode(), priceInTax: generateRandomCode(), compileExTax: generateRandomCode(), compileInTax: generateRandomCode() }
])

// 运算符号按钮
const operators = ['+', '-', '*', '/', '(', ')']

const openDialog = (row: number) => {
  currentRow.value = row
  dialogVisible.value = true
}

const openCalcDialog = (row: number) => {
  currentRow.value = row
  calcDialogVisible.value = true
  // 清空之前的编辑值
  currentEditValue.value = ''
  currentEditCell.value = null
  
  // 获取当前行的计算基数值，如果有的话显示在输入框中
  if (topHstRef.value?.hotInstance) {
    const currentValue = topHstRef.value.hotInstance.getDataAtRowProp(row, 'calcBase')
    if (currentValue) {
      currentEditValue.value = currentValue
    }
  }
}

// 插入运算符到指定行列
const insertOperator = (rowIndex: number, field: string, operator: string) => {
  if (!calcTableData.value[rowIndex][field]) {
    calcTableData.value[rowIndex][field] = []
  }
  calcTableData.value[rowIndex][field].push(operator)
}

// 当前编辑的值 - 改为字符串
const currentEditValue = ref<string>('')
const currentEditCell = ref<{ rowIndex: number; field: string } | null>(null)

// 处理单元格点击 - 累计添加到 currentEditValue
const handleCellClick = (row: any, column: any, cell: HTMLElement, event: Event) => {
  const field = column.property
  if (field && field !== 'category') {
    const rowIndex = calcTableData.value.findIndex(r => r === row)
    currentEditCell.value = { rowIndex, field }
    
    // 获取单元格的值
    const value = row[field]
    console.log(value)
    const cellValue = Array.isArray(value) ? value.join('') : value
    
    // 累计添加到 currentEditValue，而不是替换
    currentEditValue.value += cellValue
  }
}

// 添加运算符
const addOperator = (op: string) => {
  currentEditValue.value += op
}

// 保存计算数据
const saveCalcData = () => {
  // 更新 Handsontable 中对应行的计算基数值
  if (topHstRef.value?.hotInstance && currentEditValue.value) {
    topHstRef.value.hotInstance.setDataAtRowProp(currentRow.value, 'calcBase', currentEditValue.value)
    topHstRef.value.hotInstance.render()
  }
  
  console.log('保存计算数据:', calcTableData.value)
  console.log('更新计算基数:', currentEditValue.value, '到行:', currentRow.value)
  
  calcDialogVisible.value = false
  currentEditValue.value = ''
  currentEditCell.value = null
}

const topMock = ()=>{
    // 生成父子级模拟数据
    const mockData: any[] = []
    
    // 根据 topColumns 生成模拟数据
    for (let i = 1; i <= 10; i++) {
      const row: any = {}
      topColumns.value.forEach((col: any) => {
        if (col.data === 'name') {
          row[col.data] = `费率项${i}`
        } else if (col.data === 'calcBase') {
          row[col.data] = `基数${i}`
        } else if (col.data === 'rateCode') {
          row[col.data] = `${(Math.random() * 10).toFixed(2)}%`
        } else if (col.data === 'code') {
          row[col.data] = `CODE${i.toString().padStart(3, '0')}`
        } else if (col.data === 'costOwnership') {
          row[col.data] = ['直接费', '间接费', '利润', '税金'][i % 4]
        } else if (col.data === 'baseDesc') {
          row[col.data] = `基数说明${i}`
        } else if (col.data === 'variable') {
          row[col.data] = false
        }
      })
      mockData.push(row)
    }
    
    return mockData;
}
let topDbSettings = {
  data: topMock(),
  dataSchema: rowSchema,
  colWidths: 120,
  columns: topColumns.value,
}

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

function onTopHeight(height: number){
  if (topHstRef.value?.hotInstance) {
    topHstRef.value.hotInstance.updateSettings({
      height: height-15,
    })
    
    topHstRef.value.hotInstance.render()
    
    // console.log('onResizeEnd-onTopHeight',height, 'codeColWidth:', topHstRef.value.codeColWidth);
  }
}

// 直接使用配置对象，DbTree 会自动创建 HierarchyContextMenuHandler
const contextMenuHandler = {
  rootKey: 'add-category',
  rootText: '添加定额',
  levels: [
    {
      depth: 0,
      addKey: 'add-province',
      addText: '添加省市',
      allowDelete: true
    },
    {
      depth: 1,
      addKey: 'add-name',
      addText: '添加名称',
      allowDelete: true
    },
    {
      depth: 2,
      addKey: 'add-model',
      addText: '添加模式',
      allowDelete: true
    },
    {
      depth: 3,
      allowDelete: true
    }
  ]
}
onMounted(() => {
  setTimeout(() => {
    onTopHeight(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="treeData" @select="treeHandleSelect" :defaultExpandedKeys="3" :context-menu-handler="contextMenuHandler"  :search="false" />
        </ElCard>
      </ElSplitterPanel>
      <ElSplitterPanel collapsible :min="200">
        <ElCard class="w-full h-full" body-class="!p-0 h-full">
            <DbHst ref="topHstRef" :settings="topDbSettings"></DbHst>
        </ElCard>
      </ElSplitterPanel>
    </ElSplitter>

    <!-- 计算基数设置弹窗 -->
    <ElDialog v-model="calcDialogVisible" title="计算基数设置" width="50%" :close-on-click-modal="false">
      <div style="margin-bottom: 15px;">
        <div style="margin-bottom: 10px; color: #909399; font-size: 13px;">
          限数字:0-9及小数点。运算符号:+加、-减、*乘、/除、()英文括号，代码。
        </div>
        <ElInput 
          size="large"
          v-model="currentEditValue" 
          style="width: 100%;"
          placeholder="点击表格单元格或运算符按钮添加内容"
        />
      </div>
      
      <div style="margin-bottom: 15px;">
        <span style="margin-right: 10px;">运算符号:</span>
        <ElButton 
          v-for="op in operators" 
          :key="op" 
          size="large"
          @click="addOperator(op)"
          style="margin-right: 5px;font-size: 20px;"
        >
          {{ op }}
        </ElButton>
      </div>

      <ElTable :data="calcTableData" border style="width: 100%" @cell-click="handleCellClick">
        <ElTableColumn prop="category" label="类别" width="100" fixed />
        <ElTableColumn prop="priceExTax" label="除税基价代码" min-width="200">
        </ElTableColumn>
        <ElTableColumn prop="priceInTax" label="含税基价代码" min-width="200">
        </ElTableColumn>
        <ElTableColumn prop="compileExTax" label="除税编制代码" min-width="200">
        </ElTableColumn>
        <ElTableColumn prop="compileInTax" label="含税编制代码" min-width="200">
        </ElTableColumn>
      </ElTable>
      
      <template #footer>
        <ElButton @click="calcDialogVisible = false">取消</ElButton>
        <ElButton type="primary" @click="saveCalcData">确定</ElButton>
      </template>
    </ElDialog>
</Page>
</template>

<style lang="css">
</style>
