<template>
  <div style="height:100%;" >
    <vxe-table
      border
      custom print
      show-overflow
      keep-source
      height="auto"
      auto-resize
      ref="tableRef"
      :columnConfig="{ resizable: true }"
      :row-config="{keyField: 'id',height:50,isCurrent: true, isHover: true}"
      :tree-config="{transform: true, rowField: 'id', parentField: 'pid'}" 
      @cell-click="cellClickEvent"
      @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">
      </vxe-column>
      <!-- <vxe-column field="content" title="填报值" width="13%" fixed="left" :visible="true">
      </vxe-column> -->
    </vxe-table>
  </div>
</template>

<script lang="ts" setup>
import { ref, nextTick } from 'vue'
import { VXETable, VxeTablePropTypes, VxeTableInstance } from 'vxe-table'
import { queryAllTplItemForUser } from '../../alloc/BaosongTaskAlloc.api';
import { batchSaveOrUpdate,queryRecord,saveOrUpdate } from '../BaosongTaskRecord.api';

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

interface RowVO {
  id: number
  title: string
  tp: string
  pcode: string
  code: string
  formTp:string,
  childNum: number
  hasChild?: boolean
  content?:any,
}

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

const curTask = ref()
const curTpl = ref()
const loading = ref(false)
const tableRef = ref<VxeTableInstance<RowVO>>()
const tableData = ref<RowVO>()
const formValues = ref<FormData[]>([])

const existFormData = ref<{[key: string]: string }>({});  

async function setData(taskData,tplData){

  curTpl.value = tplData
  curTask.value = taskData
  //await setAllHaveExist()
  let retData = await queryAllTplItemForUser({
    tplid:curTpl.value.id,
    taskid:curTask.value.id
  });
  
  // if(retData&&retData.length>0) {
  //   retData.forEach((item)=>{
  //     let key = item.id
  //     item.haveChild = item.childNum>0?true:false;
  //     item["content"] =  existFormData.value[key]?.content|| ""
  //     item["rid"] = existFormData.value[key]?.id
  //   })
  // }
  


  tableData.value = retData

}

async function saveBatch() {
  const $table = tableRef.value
  if ($table) {
    loading.value = true
    formValues.value= []
    const updateRecords = $table.getUpdateRecords()
    updateRecords.forEach(row => {  
      let formData: FormData = {  
        id: row.rid||null,
        taskid: curTask.value.id, 
        tplid: curTpl.id, 
        itemid: row.id, 
        content: row.content 
      }; 
       formValues.value.push(formData)
    });    
    await batchSaveOrUpdate(formValues.value)
    loading.value = false
  }
}

async function setAllHaveExist () {
  let param = {taskid:curTask.value.id,tplid:curTpl.id}
  let vals =  await queryRecord(param)
  
  vals.forEach(item => { 
    let key = item.itemid;
    existFormData.value[key] = item

  })
}

async function cellClickEvent({row}) {
  await expandCurNodeEvent(row)
  emit("callback",row)

}

const headerCellClickEvent = ({ column }) => {
  emit("hideTplList")
}

const expandCurNodeEvent = async (row) => {
  const $table = tableRef.value
  if ($table) {
    //$table.setAllTreeExpand(true)
    $table.setTreeExpand(row, true)
  }
}

function handleExpandChange({ row, rowIndex }) {  
  emit("callback",row)

}

function clearData() {
  curTpl.value = {}
  curTask.value = {}
  tableData.value = []
}

defineExpose({
  setData,
  saveBatch,
  clearData

});
</script>


<style scope>
  .layout {
    background: #fff;
    height: calc(90vh - 120px);
    margin: 0px 0px 0px 0px;
    overflow: hidden;
    min-height: 400px;
  }
  .ant-descriptions-item-label {
    width: 150px;
  }

</style>


