<template>
  <div style="height:100%;">
    <vxe-toolbar ref="toolbarRef"  custom :refresh="{ queryMethod }">
      <template #buttons>
        <vxe-button mode="text" status="primary"  @click="handlLeftWidth">
          <menuUnfoldOutlined v-if="collapsed" class="trigger" />
          <MenuFoldOutlined v-else class="trigger" />
        </vxe-button>
        <span style="margin-left:20px">{{ curTpl?.code }} {{ curTpl?.nm }}</span>

      </template>
      <template #tools>
        <vxe-button mode="text" status="primary" @click="saveBatch()" :loading="loading"  icon="vxe-icon-save" style="margin-right:40px">保存</vxe-button>
      </template>
    </vxe-toolbar>
    
    <vxe-table
      border
      :loading="loading"
      keep-source
      height="auto"
      auto-resize
      ref="tableRef"
      :column-config="{ resizable: true }"
      :custom-config="customConfig"
      :row-config="{ keyField: 'id', isCurrent: true, isHover: true, useKey: true, resizable: true }"
      :tree-config="{ transform: true, rowField: 'id', parentField: 'pid',showIcon: false}"
      @toggle-tree-expand="handleExpandChange"
      :data="tableData">
      <vxe-column type="seq" width="60" fixed="left"></vxe-column>
      <vxe-column field="title" title="模板项目" type="html" tree-node fixed="left" width="150" row-resize :visible="true">
      </vxe-column>
      <vxe-column field="content" title="内容" fixed="left" :visible="true" :edit-render="{}" row-resize>
        <template #default="{ row }">
          <template v-if="row.formTp && row.formTp === 'table'">
            <SubTable
              :key="row.id"
              :title="row.title"
              :columnsPerRow="6"
              :records="subTablesData[row.id] || []"
              :fields="getTableFields(row)"
              :ref="(el) => setSubTableRef(el, row.id)"
              @update:records="handleRecordsUpdate(row.id, $event)"
              @change="handleSubTableChange(row.id)"
            />
          </template>
          <template v-else-if="row.formTp && row.formTp === 'table2'">
            <SubTable2
              :title="row.title"
              :columnsPerRow="6"
              :records="subTablesData[row.id] || []"
              :fields="getTableFields(row)"
              @update:records="handleRecordsUpdate(row.id, $event)"
              @change="handleSubTableChange(row.id)"
            />
          </template>
          <template v-else>
            <a-card style="min-height:200px">
              <template v-if="row.children && row.children.length > 0">
                <template v-for="(item, ind) in row.children" :key="ind">
                  <div style="margin: 10px;">
                    <span style="color:blue">{{ item.title }}：</span>
                    <template v-if="item.formTp === 'yesno'">
                      <vxe-radio-group v-model="formData[item.code]" @change="handleFormChange">
                        <vxe-radio label="是">是</vxe-radio>
                        <vxe-radio label="否">否</vxe-radio>
                      </vxe-radio-group>
                    </template>
                    <template v-else-if="item.formTp === 'radio'">
                      <div style="margin:10px">
                        <vxe-radio-group v-model="formData[item.code]" @change="handleFormChange">
                          <vxe-radio v-for="(opt, ind) in item.options.split('\n')" :key="ind" :label="opt" style="margin: 10px;">{{ opt }}</vxe-radio>
                        </vxe-radio-group>
                      </div>
                    </template>
                    <template v-else-if="item.formTp === 'checkbox'">
                      <div style="margin:10px">
                        <vxe-checkbox-group v-model="formData[item.code]" @change="handleFormChange">
                        <vxe-checkbox v-for="(opt, ind) in item.options.split('\n')" :key="ind" :label="opt" style="margin: 10px;">{{ opt }}</vxe-checkbox>
                        </vxe-checkbox-group>
                      </div>
                    </template>
                    <template v-else-if="item.formTp === 'input'">
                      <vxe-input 
                        v-model="formData[item.code]" 
                        :type="item.tp" 
                        placeholder="请输入"
                        @change="handleFormChange"
                      ></vxe-input>
                      <template v-if="item.tp === 'number'">
                        {{ item.unit }}
                      </template>
                    </template>
                    <template v-else-if="item.formTp === 'date'">
                      <vxe-input 
                        v-model="formData[item.code]" 
                        :type="item.tp" 
                        placeholder="请输入"
                        @change="handleFormChange"
                      ></vxe-input>
                    </template>
                    <template v-else-if="item.formTp === 'textarea'">
                      <vxe-input 
                        v-model="formData[item.code]" 
                        placeholder="请输入" 
                        :autosize="{minRows: 2, maxRows: 2}" 
                        clearable 
                        style="width:60%"
                        @change="handleFormChange"
                      ></vxe-input>
                    </template>
                  </div>
                </template>
              </template>
              <template v-else>
                <div style="margin: 10px;">
                  <template v-if="row.formTp === 'yesno'">
                    <vxe-radio-group v-model="formData[row.code]" @change="handleFormChange">
                      <vxe-radio label="是">是</vxe-radio>
                      <vxe-radio label="否">否</vxe-radio>
                    </vxe-radio-group>
                  </template>
                  <template v-else-if="row.formTp === 'radio'">
                    <div style="margin:10px">
                      <vxe-radio-group v-model="formData[row.code]" @change="handleFormChange">
                        <vxe-radio v-for="(opt, ind) in row.options.split('\n')" :key="ind" :label="opt" style="margin: 10px;">{{ opt }}</vxe-radio>
                      </vxe-radio-group>
                    </div>
                  </template>
                  <template v-else-if="row.formTp === 'checkbox'">
                    <div style="margin:10px">
                      <vxe-checkbox-group 
                        v-model="formData[row.code]" 
                        :options="row.options.split('\n').map(opt => ({ label: opt, value: opt }))" 
                        @change="handleFormChange"
                      />
                    </div>
                  </template>
                  <template v-else-if="row.formTp === 'input'">
                    <vxe-input 
                      v-model="formData[row.code]" 
                      :type="row.tp" 
                      placeholder="请输入"
                      @change="handleFormChange"
                    ></vxe-input>
                    <template v-if="row.tp === 'number'">
                      {{ row.unit }}
                    </template>
                  </template>
                  <template v-else-if="row.formTp === 'date'">
                    <vxe-input 
                      v-model="formData[row.code]" 
                      :type="row.tp" 
                      placeholder="请输入"
                      @change="handleFormChange"
                    ></vxe-input>
                  </template>
                  <template v-else-if="row.formTp === 'textarea'">
                    <vxe-input 
                      v-model="formData[row.code]" 
                      placeholder="请输入" 
                      clearable 
                      style="width:60%"
                      @change="handleFormChange"
                    ></vxe-input>
                  </template>
                </div>
              </template>
            </a-card>
          </template>
        </template>
      </vxe-column>
    </vxe-table>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { VxeUI, VxeTableInstance,VxeTablePropTypes } from 'vxe-table'
import { queryAllTplItemForUser } from '../../alloc/BaosongTaskAlloc.api'
import { batchSaveOrUpdate, queryRecord } from '../BaosongTaskRecord.api'
import { MenuUnfoldOutlined, MenuFoldOutlined } from '@ant-design/icons-vue'
import SubTable from './SubTable.vue'
import SubTable2 from './SubTable2.vue'

const emit = defineEmits(['callback', 'hideTplList'])

interface RowVO {
  id: number
  pid?: number
  title: string
  tp?: string
  pcode?: string
  code: string
  formTp: string
  childNum?: number
  hasChild?: boolean
  content?: any
  children?: RowVO[]
  options?: string
  rid?: number,
  xmlcode?:string
}

interface FormData {
  id: number | null
  taskid: number
  tplid: number
  itemid: number
  itempid:number
  content: string
  tplcode:string
  rind:number
}

interface SubTableRecord {
  [key: string]: any
}

interface SubTableData {
  [tableId: string]: SubTableRecord[]
}

const toolbarRef = ref()
const curTask = ref<any>()
const curTpl = ref<any>()
const loading = ref(false)
const tableRef = ref<VxeTableInstance<RowVO>>()
const tableData = ref<RowVO[]>([])
const formValues = ref<FormData[]>([])
const collapsed = ref(false)
const subTablesData = reactive<SubTableData>({})
const formData = reactive<Record<string, any>>({})


const getTableFields = (row: RowVO) => {
  if (!row.children) return []
  return row.children.map(child => ({
    code: child.id +"_"+child.code,
    title: child.title,
    formTp: child.formTp,
    options: child.options,
    tp:child.tp,
    itemid:child.id
  }))
}

const handleRecordsUpdate = (tableId: number, records: SubTableRecord[]) => {
  subTablesData[tableId] = records
}

const handleSubTableChange = (tableId: number) => {
  // 可以在这里添加子表格变化时的处理逻辑
}


const handleFormChange = () => {
  // 可以在这里添加表单变化时的处理逻辑
}


const subTableRefs = ref<Record<number, any>>({})

const setSubTableRef = (el: any, tableId: number) => {
  if (el) {
    subTableRefs.value[tableId] = el
  } else {
    delete subTableRefs.value[tableId]
  }
}

const getSubTableData = (tableId: number) => {
  const subTable = subTableRefs.value[tableId]
  if (subTable) {
    return subTable.getFormData() // 调用子组件暴露的方法
  }
  return null
}
const getAllSubTableData = () => {
  return Object.entries(subTableRefs.value).map(([tableId, subTable]) => {
    return {
      tableId: Number(tableId),
      data: subTable.getFormData()
    }
  })
}

const findRowById = (id: number): RowVO | undefined => {
  const findInTree = (nodes: RowVO[]): RowVO | undefined => {
    for (const node of nodes) {
      if (node.id === id) return node
      if (node.children) {
        const found = findInTree(node.children)
        if (found) return found
      }
    }
    return undefined
  }
  return findInTree(tableData.value || [])
}

async function setData(taskData, tplData) {
  try {
    loading.value = true
    curTpl.value = tplData
    curTask.value = taskData
    collapsed.value = false
    Object.keys(formData).forEach(key => delete formData[key])
    Object.keys(subTablesData).forEach(key => delete subTablesData[key])
    const retData = await queryAllTplItemForUser({
      tplid: curTpl.value.id,
      taskid: curTask.value.id
    })
    tableData.value = retData
    const recordData = await queryRecord({taskid: curTask.value.id, tplid: curTpl.value.id})
    const groupedData = await groupDataByCompositeKey(recordData)
    if (tableData.value) {
      const initData = (nodes: RowVO[]) => {
        nodes.forEach(node => {
          if (node.formTp === 'table') {
           let compositeKey = `${curTask.value.id }_${curTpl.value.id}_${node.id}`; 
           subTablesData[node.id] = groupedData[compositeKey];

          } else {
            node.children?.forEach(child => {
              const record = recordData.find(r => r.itemid === child.id)
              let content =  record?.content
              if(content) {
                if(child.formTp==='checkbox') {
                  formData[child.code] = content.split(",")
                } else {
                  formData[child.code] =  content
                }
              } else {
                formData[child.code] =  ""
              }
            })
          }
          if (node.children) {
            initData(node.children)
          }
        })
      }
      
      initData(tableData.value)
    }
  } catch (error) {
    VxeUI.modal.message({ content: `加载数据失败: ${error.message}`, status: 'error' })
  } finally {
    loading.value = false
  }
}


async function saveBatch() {
  try {
    const $table = tableRef.value
    if ($table) {
      loading.value = true
      formValues.value = []
      const allRows = $table.getTableData().fullData
      
      // 处理非表格数据
      allRows.forEach(row => {
        if (row.formTp !== 'table') {
          if (row.children && row.children.length>0) {
            row.children.forEach(item => { 
              let tempForm: FormData = {
                id: row.rid || null,
                rind:1,
                taskid: curTask.value.id,
                tplid: curTpl.value.id,
                itemid: item.id,
                itempid: item.pid,
                tplcode: item.xmlcode,
                content: Array.isArray(formData[item.code]) 
                  ? formData[item.code].join(',') 
                  : formData[item.code] || ''
              };
              formValues.value.push(tempForm)
            })
          }
        }
      })

      // 处理表格数据 - 确保获取所有子表数据
      const subTablePromises = Object.entries(subTableRefs.value).map(async ([tableId, subTable]) => {
        const row = findRowById(Number(tableId));
        if (row && subTable) {
          const records = await subTable.getFormData();
          let ind = 0;
          records.forEach(item => {
            ind++;
            for (const key in item) {
              if (item.hasOwnProperty(key) && key !== "_recordIndex" && key !== "id") {
                const [itemid, tplcode] = key.split('_');
                let tempFormData: FormData = {
                  tplcode: tplcode,
                  taskid: curTask.value.id,
                  tplid: curTpl.value.id,
                  content: item[key],
                  itemid: itemid*1,
                  itempid: row.id*1,
                  rind: ind
                }
                formValues.value.push(tempFormData)
              }
            }
          });
        }
      });

      // 等待所有子表数据处理完成
      await Promise.all(subTablePromises);
    
      if (formValues.value.length > 0) {
        await batchSaveOrUpdate(formValues.value)
        VxeUI.modal.message({ content: '保存成功', status: 'success' })
        await setData(curTask.value, curTpl.value)
      } else {
        VxeUI.modal.message({ content: '没有需要保存的数据', status: 'warning' })
      }
    }
  } catch (error) {
    VxeUI.modal.message({ content: `保存失败: ${error.message}`, status: 'error' })
  } finally {
    loading.value = false
  }
}


function handleExpandChange({ row }) {
  //emit("callback", row)
  return false
}

const expandAllEvent = () => {
  const $table = tableRef.value
  if ($table) {
    $table.setAllTreeExpand(true)
  }
}

const clearExpandEvent = () => {
  const $table = tableRef.value
  if ($table) {
    $table.clearTreeExpand()
  }
}

function handlLeftWidth() {
  try{
    collapsed.value = !collapsed.value
    emit('hideTplList', collapsed.value)
  } catch(e)  {
    console.log(e)
  }
 
}


async function groupDataByCompositeKey(data) {
  const result = {};
  data.forEach(item => {
    const compositeKey = `${item.taskid}_${item.tplid}_${item.itempid}`;
    if (!result[compositeKey]) {
      result[compositeKey] = [];
    }
    let existingItem = result[compositeKey].find(obj => obj.rind === item.rind);
    if (!existingItem) {
      existingItem = { rind: item.rind };
      result[compositeKey].push(existingItem);
    }
    existingItem[item.itemid+"_"+item.tplcode] = item.content;
  });
  return result;
}

const queryMethod = async () => {
  try {
    await setData(curTask.value,curTpl.value)
  } catch (error) {
    console.error("刷新数据失败:", error);
  } finally {
    loading.value = false;
  }
};

const customConfig = reactive<VxeTablePropTypes.CustomConfig>({
  mode: 'modal'
})

onMounted(() => {
  const $table = tableRef.value
  const $toolbar = toolbarRef.value
  if ($table && $toolbar) {
    $table.connect($toolbar)
  }
})


defineExpose({
  setData
})
</script>

<style scoped>
/* 操作按钮样式 */
.vxe-table .vxe-body--column.col--operate {
  text-align: center;
}

/* 表头按钮样式 */
.vxe-table .vxe-header--column .vxe-button {
  margin-left: 5px;
}

/* 按钮悬停效果 */
.vxe-button.type--text:hover {
  color: #409eff;
  background-color: transparent;
}

/* 删除按钮颜色 */
.vxe-button.type--text.icon--delete:hover {
  color: #f56c6c;
}

.info-tech-governance-form {
  font-family: "Microsoft YaHei", SimSun, sans-serif;
  margin: 20px;
  line-height: 1.6;
  color: #333;
}

h1 {
  text-align: center;
  color: #1a56a7;
  margin-bottom: 5px;
}

.form-info {
  text-align: right;
  margin-bottom: 15px;
  font-size: 14px;
}

.highlight {
  background-color: #fff8dc;
}

.vxe-input {
  border-bottom: 1px solid #333;
  text-align: center;
  margin: 0 3px;
  padding: 0;
  border-top: none;
  border-left: none;
  border-right: none;
  background: transparent;
}

.vxe-input--inner {
  text-align: center;
}

.vxe-radio,
.vxe-checkbox {
  margin-right: 15px;
}
</style>