<script setup lang="ts">
import { getCategoriesList } from '#/api/database/materials/root';
import { DbHst } from '#/components/db-hst';
import { ElButton, ElDialog, ElInput } from 'element-plus';
import { computed, nextTick, ref, watch } from 'vue';

const props = defineProps<{
  modelValue: boolean
  rowData?: any
  catalogItemId?: string
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'success', value: string): void
}>()

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

const formulaInput = ref('')
const hstRef = ref<any>(null)
const tableData = ref<any[]>([])

const handleSubmit = () => {
  emit('success', formulaInput.value)
  isVisible.value = false
}

// 加载工料机总类数据
const loadCategoriesData = async () => {
  try {
    const res = await getCategoriesList()
    // 转换数据格式，映射到表格列
    tableData.value = (res || []).map((item: any, index: number) => ({
      code: String(index + 1),
      category: item.code || '',
      taxFreeBaseCode: item.taxExclBaseCode || '',
      taxIncludedBaseCode: item.taxInclBaseCode || '',
      taxFreeCompileCode: item.taxExclCompileCode || '',
      taxIncludedCompileCode: item.taxInclCompileCode || '',
    }))
  } catch (error) {
    console.error('加载工料机总类失败:', error)
    tableData.value = []
  }
}

const columns = [
  { type: 'text', data: 'code', title: '序号', width: 60, readOnly: true },
  { type: 'text', data: 'category', title: '类别', readOnly: true },
  { type: 'text', data: 'taxFreeBaseCode', title: '除税基价代码', readOnly: true },
  { type: 'text', data: 'taxIncludedBaseCode', title: '含税基价代码', readOnly: true },
  { type: 'text', data: 'taxFreeCompileCode', title: '除税编制代码', readOnly: true },
  { type: 'text', data: 'taxIncludedCompileCode', title: '含税编制代码', readOnly: true },
]

const allowedSelectionDataKeys = new Set([
  'taxFreeBaseCode',
  'taxIncludedBaseCode',
  'taxFreeCompileCode',
  'taxIncludedCompileCode',
])

let settings = {
  data: [],
  colWidths: 150,
  columns: columns,
  rowHeaders: false,
  nestedRows: false,
  bindRowsWithHeaders: true,
  selectionMode: 'single',
  className: 'htCenter',
  afterSelection(row: number, col: number, row2: number, col2: number) {
    if (row < 0 || col < 0) return
    const selectedDataKey = columns?.[col]?.data
    if (!selectedDataKey || !allowedSelectionDataKeys.has(selectedDataKey)) return
    const cellValue = this.getDataAtCell(row, col)
    if (cellValue == null) return
    formulaInput.value += String(cellValue)
  }
}
watch(
  () => props.modelValue,
  async (visible) => {
    if (!visible) {
      formulaInput.value = ''
      return
    }

    // 加载工料机总类数据
    await loadCategoriesData()

    nextTick(() => {
      setTimeout(() => {
        if(hstRef?.value?.hotInstance) {
          hstRef?.value?.hotInstance.loadData(tableData.value)
        }
      }, 200);
    })

    const currentCardinal = props.rowData?.cardinal
    formulaInput.value = currentCardinal == null ? '' : String(currentCardinal)
  },
  { immediate: true, deep: true },
)
</script>

<template>
  <ElDialog v-model="isVisible" title="工料机总类" width="60%" :close-on-click-modal="false" body-class="materials-body-height">
    <div class="h-full w-full flex flex-col">
      <div>
        <ElInput v-model="formulaInput" placeholder="请输入计算基数公式" clearable></ElInput>
      </div>

      <DbHst ref="hstRef" :settings="settings"  v-if="isVisible"></DbHst>
    </div>

    <template #footer>
      <ElButton @click="isVisible = false">取消</ElButton>
      <ElButton type="primary" @click="handleSubmit">确定</ElButton>
    </template>
  </ElDialog>
</template>
<style lang="scss">
.materials-body-height{
  height: 500px;
}
</style>
