<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>
        <vxe-button status="primary"  icon="vxe-icon-save" @click="checkData()">校验</vxe-button>
      </template>
    </vxe-toolbar>
    <vxe-table
      border
      ref="tableRef"
      height="auto"
      show-header-overflow
      :data="tableFormData"
      :column-config="{ resizable: true }"
      :row-config="{ resizable: true }"
      class="custom-table"
    >
      <vxe-column field="serialNumber" title="序号" width="50"></vxe-column>
      <vxe-column field="project" title="项目" width="100">
        <template #default="{ row }">
          <span style="font-weight: bold;size:20px">{{ row.project }}</span>
        </template>
      </vxe-column>
      <vxe-column field="content" title="内容" row-resize>
        <template #default="{ row }"> 
          
          <div class="content-cell">
            <template v-if="row.type === 'MultiColumnTable'">
              <MultiColumnTable
                :title="row.project"
                :records="[]"
                :fields="row.content"
                :ref="(el) => setMultiColumnTableRef(el, row.code)"
                style="margin:0px;padding:0px"
              />
            </template>
            <template v-else-if="row.type === 'AttachTable'">
              <AttachTable
                :title="row.project"
                :records="row.datas"
                :fields="row.content"
                :pcode="row.code"
                :calcSum="row.calcSum"
                :showFooter="row.showFooter"
                :ref="(el) => setAttachTableRef(el, row.code)"
                style="margin:0px;padding:0px"
              />
            </template>
            <template v-else-if="row.type === 'VxeTable'">
              <MyVxeTable1
                :title="row.project"
                :data="row.data"
                :columns="row.columns"
                :pcode="row.code"
                :footerData="row.footerData"
                :showFooter="row.showFooter"
                :ref="(el) => setMyVxeTableRef(el, row.code)"
                style="margin:0px;padding:0px"
              />
            </template>
            <template v-else>
              <template v-for="(item, index) in row.content" :key="index">
                <span v-if="item.type === 'text'" v-html="item.value"></span>
                <span v-else-if="item.type === 'br'"><br></span>
                <span v-else-if="item.type === 'brspace'">
                  <br>
                  <template v-for="i in item.value||1" :key="i">
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                  </template>
                </span>
                
                <span v-else-if="item.type === 'radio-group'" class="radio-group">
                  <vxe-radio-group v-model="formData[row.code +'_'+ item.field]"
                    :disabled="item.relatedFiled&&formData[row.code +'_'+ item.relatedFiled]!='是'"
                  >
                    <vxe-radio
                      v-for="(opt, optIndex) in item.options"
                      :key="optIndex"
                      :label="opt"
                      >{{ opt }}</vxe-radio
                    >
                  </vxe-radio-group>
                </span>
                <div v-else-if="item.type === 'checkbox-group'">
                  <span class="checkbox-group" >
                      <vxe-checkbox-group v-model="formData[row.code+'_'+item.field]">
                        <vxe-checkbox v-for="(opt, optIndex) in item.options" :key="optIndex" :label="opt">
                          {{ opt }}
                          </vxe-checkbox>
                          <template  v-if="item.otherField">
                            <div style="width:100%">
                              <vxe-checkbox label="其他">
                                其他：
                              </vxe-checkbox>
                              <vxe-input v-model="formData[row.code + '_'+ item.otherField]"  
                                :disabled="!(formData[row.code+'_'+item.field]?.indexOf('其他')>-1)"
                                style="width: 50%"
                              >
                              </vxe-input>
                            </div>
                            </template>
                      </vxe-checkbox-group>
                    </span> 
                </div>

                <div v-else-if="item.type === 'checkboxAndInput'">
                  <span style="margin-left:20px">
                      <vxe-checkbox-group v-model="formData[row.code+'_'+item.field]">
                        <vxe-checkbox v-for="(opt, optIndex) in item.options" :key="optIndex" :label="opt" style="margin-left: 0px;display: block;">
                          {{ opt }}
                          <vxe-input type="number" v-model="formData[row.code + '_'+ item.optionItemField[optIndex]]"  style="width: 100px;margin: 0px;">
                          </vxe-input>
                          <span class="unit"> {{ item.optionItemUint }}</span>
                        </vxe-checkbox>
                      </vxe-checkbox-group>
                    </span> 
                </div>
                <template v-else>
                  <vxe-input
                    :disabled="item.relatedFiled&&formData[row.code +'_'+ item.relatedFiled]!='是'"
                    :type="item.type"
                    v-model="formData[row.code +'_'+ item.field]"
                    size="mini"
                    class="table-input"
                    :style="item.style"
                  >
                  </vxe-input>
                  <span class="unit"> {{ item.unit }}</span>

                  
                </template>
              </template>
            </template>
          </div>
        </template>
      </vxe-column>
      <vxe-column field="remarks" title="备注" width="60">
        <template #default="{ row }"> 
            <vxe-textarea :rows="row.remarks.rows" v-model="formData[row.code+'_'+row.remarks.field]">
            </vxe-textarea>
        </template>
      </vxe-column>
    </vxe-table>
    <CheckTbData ref="refCheckTbData"></CheckTbData>
  </div>
</template>

<script lang="ts" setup>
import MultiColumnTable from '../tableComponents/MultiColumnTable.vue'
import AttachTable from '../tableComponents/AttachTable.vue'
import MyVxeTable1 from '../tableComponents/MyVxeTable.vue'
import CheckTbData from './CheckTbData.vue'
import { tableFormData } from '../../data/tb1.data';
import { ref, reactive,nextTick,onMounted,toRaw } from 'vue'
import { VxeUI,VxeToolbarInstance,VxeToolbarPropTypes } from 'vxe-table'
import { batchSaveOrUpdate, queryRecord,batchSaveOrUpdateBeforeDelete } from '../../record/BaosongTaskRecord.api'
import { queryAllTplItemForUser } from '../../alloc/BaosongTaskAlloc.api'
import { allTplItems } from '../../tpl/BaosongTplItem.api'

import { useRoute } from 'vue-router';

const refCheckTbData = ref();

const route = useRoute();
const tableRef = 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 getFillDatas()
    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 getFillDatas = async() => {

  try {
    formValues.value = []

    for (const strKey in formData) {
      const valData = formData[strKey]
      if (valData!==undefined&&valData!=="") {
        let tmpAry = strKey.split("_")
        await setFormValues(tmpAry[0],tmpAry[1],valData,1)    
      }
    }
    await getAttachTableFormData();
    await getAllMultiTableFormData()
    await getVxeTableFormData()

  } catch (error) {
    console.log(error)
  } finally {
 
  }
}


const childMultiTableRefs = ref({})
const setMultiColumnTableRef = (el: any, index: string) => {
  if (el) {
    childMultiTableRefs.value[index] = el;
  }
};


const getAllMultiTableFormData = async () => {
  for (const pcode in childMultiTableRefs.value) {
      const child = childMultiTableRefs.value[pcode];
      if (child) {
          const datas = await child.getFormData()
          let rind = 0
          for(const obj of datas) {
            rind++
            Object.keys(obj).forEach(code => {  
              setFormValues(pcode,code,obj[code],rind)
            });
          }
      }
  }
};


const childAttachTableRefs = ref({})
const setAttachTableRef = (el: any, index: string) => {
  if (el) {
    childAttachTableRefs.value[index] = el; // 保存子组件实例
  }
};

const childMyVexTableRefs = ref({})
const setMyVxeTableRef = (el: any, index: string) => {
  if (el) {
    childMyVexTableRefs.value[index] = el; // 保存子组件实例
  }
};

const getAttachTableFormData  = async () => {
  for (const pcode in childAttachTableRefs.value) {
      const child = childAttachTableRefs.value[pcode];
      if (child) {
          const datas = await child.getFormData()
          for(const code in datas) {
            await setFormValues(pcode,code,datas[code],1)
          }
      }
  }
};

const getVxeTableFormData  = async () => {
  for (const pcode in childMyVexTableRefs.value) {
      const child = childMyVexTableRefs.value[pcode];
      if (child) {
          const formData = await child.getFormData()
          console.log("formData",formData)
          let rind = 0
          for(const obj of formData.datas) {
            rind++
            Object.keys(obj).forEach(code => {  
              setFormValues(pcode,code,obj[code],rind)
            });
          }
          if(formData.footer) {
            Object.keys(formData.footer).forEach(code => {  
              setFormValues(pcode,code,formData.footer[code],1)
            });
          }
      }
  }

};

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 checkData() {
  let tplName = queryParam.value.tplName;
  await getFillDatas();
  if(formValues.value.length > 0) {
    refCheckTbData.value.setIniData(tplName,formValues.value)
  }
}


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 });
    const valueObj = {};
    for (const data of recordData) {
      const key = `${data.itempid}_${data.itemid}_${data.rind}`;
      valueObj[key] = data.content;
    }
    for (const row of tableFormData) {
      if(!row.type&&row.content) {
        for (const cdata of row.content) {
          if(cdata.field&&cdata.field.length>0) {
            
            const strKey = `${row.code}_${cdata.field}`;           
            const item = tplItemMap.value[strKey];
            if (!item) continue;
            const { pid, itemid, formTp } = item;
            const dataVal = valueObj[`${pid}_${itemid}_1`];
            if (!dataVal) continue;
            if (formTp === 'checkbox') {
              formData[strKey] = dataVal?.split(",") || [];
            } else {
              formData[strKey] = dataVal || "";
            }

            if(cdata.type&&cdata.type=="checkboxAndInput") {
              for (const itemField of cdata.optionItemField) {
                const strItemKey = `${row.code}_${itemField}`;   
                const item2 = tplItemMap.value[strItemKey];
                if (!item2) continue;
                const { pid:pid2, itemid:itemid2 } = item2;
                const dataVal2 = valueObj[`${pid2}_${itemid2}_1`];
                formData[strItemKey] = dataVal2 || "";
              }
            }
            
            if(cdata.otherField){
              const strItemKey3 = `${row.code}_${cdata.otherField}`;   
              const item3 = tplItemMap.value[strItemKey3];
              if (!item3) continue;
              const { pid:pid3, itemid:itemid3 } = item3;
              const dataVal3 = valueObj[`${pid3}_${itemid3}_1`];
              formData[strItemKey3] = dataVal3 || ""
            }

          }
        }
      } else if(row.type=="AttachTable"&& row.datas) {
        const curAttachTable = childAttachTableRefs.value[row.code];
        const attachTableData = {};
        for (const cdata of row.datas) {
          Object.keys(cdata).forEach(key => {
            if(cdata[key]["field"]){
              const strKey = `${row.code}_${cdata[key]["field"]}`;           
              const item = tplItemMap.value[strKey];
              if (item) {
                const { pid, itemid, formTp, code } = item;
                const dataVal = valueObj[`${pid}_${itemid}_1`];
                if (dataVal) {
                  if (formTp === 'checkbox') {
                    attachTableData[code] = dataVal?.split(",") || [];
                  } else {
                    attachTableData[code] = dataVal || "";
                  }
                }
              }
            }
          });
        }
        
        curAttachTable.setFormData(attachTableData);
      } else if(row.type=="MultiColumnTable"&& row.content) {
          const curMultiTable = childMultiTableRefs.value[row.code];
 
          const rowsMap = {};
          for (const cdata of row.content) {
            if(cdata.field&&cdata.field.length>0) {
              const strKey = `${row.code}_${cdata.field}`;    
              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);
          curMultiTable.setFormData(tableDatas);
        } else if(row.type=="VxeTable"&& row.columns) {
          debugger;
          const curVexTable = childMyVexTableRefs.value[row.code];
          const rowsMap = {};
          for (const cdata of row.columns) {
            if(cdata.field&&cdata.field.length>0) {
              const strKey = `${row.code}_${cdata.field}`;
              const tmpData = tplItemMap.value[strKey];
            
              if (!tmpData || Object.keys(tmpData).length === 0) continue;
              const { pid, itemid, code } = tmpData;
              
              console.log("tmpData",tmpData)

              console.log("valueObj",valueObj)
            
              const valKeys = Object.keys(valueObj).filter(k => 
                k.startsWith(`${pid}_${itemid}_`)
              );

              console.log("valKeys",valKeys)

             
              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);
          curVexTable.setFormData(tableDatas);
      }
    }
  } catch (error) {
    console.log(error)
    VxeUI.modal.message({ 
      content: `加载数据失败:`, 
      status: 'error' 
    });
  } finally {
    loading.value = false;
  }

}

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

    tplItemMap.value = {}
    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' })
  } finally {
   
  }
}

</script>

<style lang="less" scoped>
// Base table styles
.bank-report-table {
  font-family: "SimSun", "宋体", serif;
  font-size: 12px;
  color: #000;
  margin: 5px auto;
  width: 90%;
  
  // Shared table styles
  .custom-table, .attachment-table {
    width: 100%;
    border: 1px solid #000;
    
    .vxe-header--column,
    .vxe-body--column {
      border-right: 1px solid #000;
      border-bottom: 1px solid #000;
      padding: 5px;
    }
  }
}

// Cell styles
.content-cell {
  line-height: 1.8;
}

.radio-group, .checkbox-group {
  display: inline-block;
  margin-left: 10px;
  .vxe-radio, .vxe-checkbox {
    margin-left: 0px;
    white-space: nowrap;
    line-height: 30px;
    padding: 0px 10px;
    &--label {
      font-size: 12px;
      overflow: display;
    }
    &--icon {
      font-size: 12px;
    }
  }
}


.checkbox-group {

}


// VXE specific overrides
.vxe {
  &-radio-group, &-checkbox-group {
    display: inline-block;
  }
  
  &-cell {
    padding: 5px;
  }
}

.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;
}
</style>