<template>
  <div class="bank-report-table" style="height: 80vh;">
    <vxe-toolbar>
      <template #buttons>
        <div style="margin:10px">
          <span style="font-weight: bold"> 填报任务：{{ queryParam?.taskName }} </span>
          <span style="font-weight: bold;margin-left:20px"> 表格：{{ queryParam?.tplCode }} {{ queryParam?.tplName }}</span>
        </div>
      </template>
      <template #tools>
        <vxe-button status="primary" icon="vxe-icon-save" @click="saveBatch()">保存</vxe-button>
      </template>
    </vxe-toolbar>
    <MyVxeTable
      :title="tableFormData.project"
      :data="tableFormData.data"
      :columns="tableFormData.columns"
      :pcode="tableFormData.code"
      :showFooter="tableFormData.showFooter"
      style="margin:0px;padding:0px;height:100%"
      ref="refMyVxeTable"
    />
         
  </div>
</template>

<script lang="ts" setup>
import MyVxeTable from '../tableComponents/MyVxeTable.vue'
import { tableFormData } from '../../data/tb4.data';
import { ref, reactive, onMounted } from 'vue'
import { VxeUI } from 'vxe-table'
import { batchSaveOrUpdateBeforeDelete, queryRecord } from '../../record/BaosongTaskRecord.api'
import { allTplItems } from '../../tpl/BaosongTplItem.api'
import { useRoute } from 'vue-router';

const route = useRoute();
const refMyVxeTable = ref();
const tplItemMap = ref({});
const queryParam = ref({
  taskId:-1,
  taskName:'',
  tplId:-1,
  tplName:'',
  tplCode:''
})

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

onMounted(async ()=>{
  if (route.query.taskId) {  
    queryParam.value.taskId = Number(route.query.taskId); 
  }  
  if (route.query.taskName) {  
    queryParam.value.taskName = String(route.query.taskName);
  } 
  if (route.query.tplId) {  
    queryParam.value.tplId = Number(route.query.tplId);  
  }  
  if (route.query.tplName) {  
    queryParam.value.tplName = String(route.query.tplName); 
  } 
  if (route.query.tplCode) {  
    queryParam.value.tplCode = String(route.query.tplCode); 
  } 

  await setTplItemMap()
  await setData();
})

const loading = ref(false)
const formData = reactive({});
const formValues = ref<FormData[]>([])

const saveBatch = async () => {
  try {
    formValues.value = []

    await getVxeTableFormData();

    if (formValues.value.length > 0) {
      await batchSaveOrUpdateBeforeDelete(formValues.value)
      VxeUI.modal.message({ content: '保存成功', status: 'success' })
    } else {
      VxeUI.modal.message({ content: '没有需要保存的数据', status: 'warning' })
    }
  } catch (error) {
    VxeUI.modal.message({ content: `保存失败: ${error.message}`, status: 'error' })
  } finally {
    loading.value = false
  }
}

const getVxeTableFormData  = async () => {
  const formData = await refMyVxeTable.value.getFormData()
  let rind = 0
  let pcode = tableFormData.code;
  for(const obj of formData.datas) {
    rind++
    Object.keys(obj).forEach(code => {  
      setFormValues(pcode,code,obj[code],rind)
    });
  }
  
}


const setFormValues = async (pcode, code, valData, rind) => {
  if(!valData) return;
  let vals = Array.isArray(valData) ? valData.join(',') : valData 
  let strKey = pcode+"_"+code
  const item = tplItemMap.value[strKey];  
  const { pid, itemid } = item ?? {}; 
  
  let tempForm: FormData = {
    id: null,
    rind: rind,
    taskid: queryParam.value.taskId,
    tplid: queryParam.value.tplId,
    tplcode: code,
    itemid: itemid,
    itempid: pid,
    content: vals
  };
  formValues.value.push(tempForm)
}
  
async function setData() {
  try {

    loading.value = true
    const taskId = queryParam.value.taskId
    const tplid = queryParam.value.tplId
    Object.keys(formData).forEach(key => delete formData[key])
    await setTplItemMap();
    const recordData = await queryRecord({taskid: taskId, tplid: tplid})
    let valueObj = {}
    
    for(let data of recordData) {
      valueObj[data.itempid+"_" + data.itemid+"_"+ data.rind] = data["content"]
    }

    const rowsMap = {};
    for (const strKey of Object.keys(tplItemMap.value)) {
      const tmpData = tplItemMap.value[strKey];
      if (!tmpData) continue;
      
      const { pid, itemid, code } = tmpData;
      const valKeys = Object.keys(valueObj).filter(k => 
        k.startsWith(`${pid}_${itemid}_`)
      );
      
      for (const valKey of valKeys) {
        const parts = valKey.split('_');
        const rind = parts[2];
        
        if (!rowsMap[rind]) {
          rowsMap[rind] = {};
        }
        
        rowsMap[rind][code] = valueObj[valKey];
      }
    }

    const tableDatas = Object.values(rowsMap);
    refMyVxeTable.value.setFormData(tableDatas);
    
    } catch (error) {
      VxeUI.modal.message({ 
        content: `加载数据失败: ${error.message}`, 
        status: 'error' 
      });
    } finally {
      loading.value = false;
    }

}

async function setTplItemMap() {
  try {
    const tplid = queryParam.value.tplId
    const tplItem = await allTplItems({
      tplid: tplid,
    })

    tplItem.forEach(item => {
      let strKey = item.pcode + "_" + item.xmlcode;
      tplItemMap.value[strKey] = {pid:item.pid, itemid:item.id, formTp:item.formTp, code:item.xmlcode};
    })
  } catch (error) {
    VxeUI.modal.message({ content: `加载数据失败: ${error.message}`, status: 'error' })
  }
}
</script>

<style lang="less" scoped>
.bank-report-table {
  font-family: "SimSun", "宋体", serif;
  font-size: 12px;
  color: #000;
  margin: 5px auto;
  width: 99%;
}

.custom-table {
  width: 100%;
  border: 1px solid #000;
}

.custom-table .vxe-header--column,
.custom-table .vxe-body--column {
  border-right: 1px solid #000;
  border-bottom: 1px solid #000;
  padding: 5px;
}

.content-cell {
  line-height: 1.8;
}

.table-input {
  width: 80px;
  margin: 0 2px;
}

.vxe-input {
  border-bottom: 1px solid #333;
  text-align: center;
  margin: 5px 3px;
  padding: 0;
  border-top: none;
  border-left: none;
  border-right: none;
  background: transparent;
  line-height: 50px;
}
</style>