<template>
  <div class="bank-report-table" style="height:80vh">
    <vxe-toolbar>
      <template #buttons>
        <div class="toolbar-info">
          <span class="info-label">填报任务：{{ queryParam?.taskName }}</span>
          <span class="info-label">表格：{{ queryParam?.tplCode }} {{ queryParam?.tplName }}</span>
        </div>
      </template>
      <template #tools>
        <vxe-button status="primary" icon="vxe-icon-save" @click="saveBatch">保存</vxe-button>
      </template>
    </vxe-toolbar>
    <vxe-table
      border
      ref="tableRef"
      show-header-overflow
      :data="tableFormData"
      :column-config="{ resizable: true }"
      :row-config="{ resizable: true }"
      class="custom-table"
      height="auto"
      :merge-cells="mergeCells"
    >
      <vxe-column field="serialNumber" title="序号" width="80"></vxe-column>
      <vxe-column field="project" title="项目" width="50">
        <template #default="{ row }">
          <span class="project-title">{{ row.project }}</span>
        </template>
      </vxe-column>
      <vxe-column field="project2" title="" width="50">
        <template #default="{ row }">
          <span class="project-title">{{ row.project2 }}</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"
                :columnsPerRow="6"
                :records="[]"
                :fields="row.content"
                :ref="(el) => setMultiColumnTableRef(el, row.code)"
                class="embedded-table"
              />
            </template>
            <template v-else-if="row.type === 'AttachTable'">
              <AttachTable
                :title="row.project"
                :records="row.datas"
                :fields="row.content"
                :pcode="row.code"
                :ref="(el) => setAttachTableRef(el, row.code)"
                class="embedded-table"
              />
            </template>
            <template v-else>
              <template v-for="(item, index) in row.content" :key="index">
                <strong v-if="item.type === 'text'" v-html="item.value"></strong>
                <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>

                <template v-else-if="item.type === 'AttachTable'">
                  <AttachTable
                    :title="item.project"
                    :records="item.datas"
                    :fields="item.content"
                    :pcode="item.code"
                    :ref="(el) => setAttachTableRef(el, item.code)"
                    class="embedded-table"
                  />
                </template>

                <template v-else-if="item.type === 'MultiColumnTable'">
                  <MultiColumnTable
                    :title="item.project"
                    :records="[]"
                    :fields="item.content"
                    :ref="(el) => setMultiColumnTableRef(el, item.code)"
                    class="embedded-table"
                  />
                </template>
                
                <template v-else-if="item.type === 'yesno'">
                  <vxe-radio-group v-model="formData[getFieldKey(row.code, item.field)]">
                    <vxe-radio label="是" content="是"></vxe-radio>
                    <vxe-radio label="否" content="否"></vxe-radio>
                  </vxe-radio-group>
                  <template v-if="item.extraField || item.extraFields">
                    <div v-if="formData[getFieldKey(row.code, item.field)] === '是'" class="extra-fields-container">
                      如是，
                      <template v-if="item.extraField">
                        {{ item.extraLabel }}：
                        <vxe-input v-model="formData[getFieldKey(row.code, item.extraField)]" class="extra-input"></vxe-input>
                        <span class="unit">{{ item.unit }}</span>
                      </template>
                      <template v-else-if="item.extraFields">
                        <template v-for="(ccopt, ccind) in item.extraFields" :key="ccind">
                          <span>{{ ccopt.label }}: </span>
                          <template v-if="ccopt.formType === 'input'">
                            <vxe-input v-model="formData[getFieldKey(row.code, ccopt.field)]" class="extra-input"></vxe-input>
                          </template>
                          <template v-else-if="ccopt.formType === 'number'">
                            <vxe-input v-model="formData[getFieldKey(row.code, ccopt.field)]" type="number" class="extra-input"></vxe-input>
                            <span class="unit">{{ ccopt.unit }}</span>
                          </template>
                          <template v-else-if="ccopt.formType === 'checkbox'">
                            <vxe-checkbox-group v-model="formData[getFieldKey(row.code, ccopt.field)]">
                              <vxe-checkbox v-for="(opt, optIndex) in ccopt.options" :key="optIndex" :label="opt" :content="opt"></vxe-checkbox>
                            </vxe-checkbox-group>
                          </template>
                          <template v-else-if="ccopt.formType === 'radio'">
                            <vxe-radio-group v-model="formData[getFieldKey(row.code, ccopt.field)]" :options="ccopt.options">
                              <vxe-radio v-for="(opt, optIndex) in ccopt.options" :key="optIndex" :label="opt" :content="opt"></vxe-radio>
                            </vxe-radio-group>
                          </template>
                          <template v-else>
                            <vxe-input v-model="formData[getFieldKey(row.code, ccopt.field)]" :type="ccopt.formType" class="extra-input"></vxe-input>
                          </template>
                          <br>
                          <template v-if="ccopt.otherOption">
                            其他：<vxe-input v-model="formData[getFieldKey(row.code, ccopt.otherField)]" class="extra-input"></vxe-input>
                          </template>
                          <br>
                        </template>
                      </template>
                    </div>
                  </template>
                </template>
                <span v-else-if="item.type === 'radio-group'" class="radio-group">
                    <vxe-radio-group v-model="formData[getFieldKey(row.code, item.field)]" style="margin-left: 20px;">
                      <vxe-radio v-for="(opt, optIndex) in item.options" :key="optIndex" :label="opt" style="width:100%">{{ opt }}</vxe-radio>
                    </vxe-radio-group>
                </span>
                <span v-else-if="item.type === 'radio-group-extraFields'" class="radio-group">
                    <vxe-radio-group v-model="formData[getFieldKey(row.code, item.field)]">
                      <vxe-radio v-for="(opt, optIndex) in item.options" :key="optIndex" :label="opt.label">
                        {{ opt.label }}
                        <template v-if="opt.extraField && formData[getFieldKey(row.code, item.field)] === opt.label">
                          <span>{{ opt.extraLabel }}</span>
                          <vxe-input v-model="formData[getFieldKey(row.code, opt.extraField)]" class="extra-input"></vxe-input>
                        </template>
                        <template v-if="opt.extraFields && formData[getFieldKey(row.code, item.field)] === opt.label">
                          <template v-for="(ccopt, ccind) in opt.extraFields" :key="ccind">
                            <span>{{ ccopt.label }}: </span>
                            <vxe-input v-model="formData[getFieldKey(row.code, ccopt.field)]" class="extra-input"></vxe-input>
                          </template>
                        </template>
                      </vxe-radio>
                    </vxe-radio-group>
                </span>
                <div v-else-if="item.type === 'checkbox-group'">
                  <div style="width:400px;margin-left:30px">
                    <vxe-checkbox-group v-model="formData[getFieldKey(row.code, item.field)]">
                      <vxe-checkbox v-for="(opt, optIndex) in item.options" :key="optIndex" :label="opt">
                        {{ opt }}
                      </vxe-checkbox>
                      <template v-if="item.otherOption" >
                        <vxe-checkbox  label="其他">
                          其他：
                          <vxe-input v-model="formData[getFieldKey(row.code, item.otherField)]" class="extra-input"
                           :disabled="!(formData[row.code+'_'+item.field]?.indexOf('其他')>-1)"
                          ></vxe-input>
                        </vxe-checkbox>
                      </template>
                    </vxe-checkbox-group>
                  </div>
                </div>
                <template v-else-if="item.type === 'textarea'">
                  <vxe-textarea v-model="formData[getFieldKey(row.code, item.field)]" :rows="item.rows" :style="{ width: item.width }"></vxe-textarea>
                </template>
                <template v-else>
                  <vxe-input
                    :type="item.type"
                    v-model="formData[getFieldKey(row.code, item.field)]"
                    size="mini"
                    class="table-input"
                  ></vxe-input>
                </template>
                <span v-if="item.unit" class="unit">{{ item.unit }}</span>
              </template>
            </template>
          </div>
        </template>
      </vxe-column>
      <vxe-column field="remarks" title="备注" width="100">
        <template #default="{ row }"> 
            <vxe-textarea :rows="row.remarks.rows" v-model="formData[row.code+'_'+row.remarks.field]"  style="height:100%;">
            </vxe-textarea>
        </template>
      </vxe-column>
    </vxe-table>
  </div>
</template>

<script lang="ts" setup>
import MultiColumnTable from '../tableComponents/MultiColumnTable.vue'
import AttachTable from '../tableComponents/AttachTable.vue'
import { tableFormData } from '../../data/tb10.data'
import { ref, reactive, nextTick, onMounted } from 'vue'
import { VxeUI,VxeTablePropTypes } from 'vxe-table'
import { batchSaveOrUpdateBeforeDelete, queryRecord } from '../../record/BaosongTaskRecord.api'
import { queryAllTplItemForUser } from '../../alloc/BaosongTaskAlloc.api'
import { allTplItems } from '../../tpl/BaosongTplItem.api'
import { useRoute } from 'vue-router'


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

const route = useRoute()
const tableRef = ref()
const tplItemMap = ref<Record<string, any>>({})
const loading = ref(false)
const formData = reactive<Record<string, any>>({})
const formValues = ref<FormData[]>([])
const childMultiTableRefs = ref<Record<string, any>>({})
const childAttachTableRefs = ref<Record<string, any>>({})

const queryParam = ref({
  taskId: -1,
  taskName: '',
  tplId: -1,
  tplName: '',
  tplCode: ''
})

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 getFieldKey = (pcode: string | undefined, field: string): string => {
  return pcode ? `${pcode}_${field}` : field
}

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

    // Process main form data
    for (const strKey in formData) {
      const valData = formData[strKey]
      if (valData) {
        const [pcode, code] = strKey.split('_')
        await setFormValues(pcode, code, valData, 1)
      }
    }


    await getAttachTableFormData()
    await getAllMultiTableFormData()

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

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

const setAttachTableRef = (el: any, code: string) => {
  if (el) {
    childAttachTableRefs.value[code] = el
  }
}

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

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

const setFormValues = async (pcode: string, code: string, valData: any, rind: number) => {
  if (!valData) return

  if(Array.isArray(valData)&& valData.length==0) return
    
  const vals = Array.isArray(valData) ? valData.join(',') : valData
  const strKey = `${pcode}_${code}`
  const item = tplItemMap.value[strKey]
  const { pid, itemid } = item ?? {}

  const 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 });
    
    const valueObj = {};
    for (const data of recordData) {
      const key = `${data.itempid}_${data.itemid}_${data.rind}`;
      valueObj[key] = data.content;
    }
    const shouldSkip = (key) => {
      const refsToCheck = [
        childMultiTableRefs.value,
        childAttachTableRefs.value,
      ];
      
      for (const refs of refsToCheck) {
        for (const pcode of Object.keys(refs)) {
          if (key.startsWith(pcode + '_')) {
            return true;
          }
        }
      }
      return false;
    };

    for (const strKey of Object.keys(tplItemMap.value)) {
      if (shouldSkip(strKey)) {
        continue; 
      }
      
      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 || "";
      }
    }

    for (const pcode of Object.keys(childAttachTableRefs.value)) {
      const child = childAttachTableRefs.value[pcode];
      const matchingKeys = Object.keys(tplItemMap.value).filter(key => 
        key.startsWith(pcode + '_')
      );
      
      const attachTableData = {};
      for (const key of matchingKeys) {
        const tmpData = tplItemMap.value[key];
        if (!tmpData) continue;
        
        const { pid, itemid, formTp, code } = tmpData;
        const valueKey = `${pid}_${itemid}_1`;
        
        if (formTp === 'checkbox') {
          attachTableData[code] = valueObj[valueKey]?.split(",") || [];
        } else {
          attachTableData[code] = valueObj[valueKey] || "";
        }
      }
      
      child.setFormData(attachTableData);
    }

    for (const pcode of Object.keys(childMultiTableRefs.value)) {
      const child = childMultiTableRefs.value[pcode];
      const matchingKeys = Object.keys(tplItemMap.value).filter(key => 
        key.startsWith(pcode + '_')
      );
      
      const rowsMap = {};
      for (const key of matchingKeys) {
        const tmpData = tplItemMap.value[key];
        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);
      nextTick();
      child.setFormData(tableDatas);
    }

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


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

    tplItemMap.value = tplItem.reduce((acc, item) => {
      const strKey = `${item.pcode}_${item.xmlcode}`
      acc[strKey] = {
        pid: item.pid,
        itemid: item.id,
        formTp: item.formTp,
        code: item.xmlcode
      }
      return acc
    }, {} as Record<string, any>)
  } catch (error) {
    console.error('加载数据失败:', error)
    VxeUI.modal.message({ content: `加载数据失败: ${error instanceof Error ? error.message : String(error)}`, status: 'error' })
  }
}

const mergeCells = ref<VxeTablePropTypes.MergeCells>([
  { row: 0, col: 1, rowspan: 1, colspan: 2 },
  { row: 1, col: 1, rowspan: 1, colspan: 2 },
  { row: 2, col: 1, rowspan: 1, colspan: 2 },
  { row: 3, col: 1, rowspan: 6, colspan: 1 },

  { row: 9, col: 1, rowspan: 1, colspan: 2},
  { row: 10, col: 1, rowspan: 1, colspan: 2},
])
</script>

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

.toolbar-info {
  margin: 10px;
  
  .info-label {
    font-weight: bold;
    margin-left: 20px;
    
    &:first-child {
      margin-left: 0;
    }
  }
}

.custom-table {
  width: 100%;
  border: 1px solid #000;
  border-collapse: collapse;
  
  :deep(.vxe-header--column),
  :deep(.vxe-body--column) {
    border-right: 1px solid #000;
    border-bottom: 1px solid #000;
    padding: 5px;
  }
}

.content-cell {
  line-height: 1.8;
  padding: 5px;
}

.project-title {
  font-weight: bold;
  font-size: 14px;
}

.table-input,
.vxe-input {
  height: 24px;
  line-height: 24px;
  min-width: 150px;
  margin: 0 2px;
  padding: 0 5px;
  border: none;
  border-bottom: 1px solid #333;
  background: transparent;
  text-align: center;
}

.extra-input {
  width: 200px;
  margin-left: 5px;
}

.extra-fields-container {
  margin-left: 40px;
  margin-top: 5px;
}

.vxe-radio-group,
.vxe-checkbox-group {
  display: inline-block;
  margin-right: 5px;
  max-width: 99%;
}

.radio-group,
.checkbox-group {
  display: inline-block;
  max-width: 99%;
}

.vxe-radio,
.vxe-checkbox {
  margin: 10px;
  white-space: nowrap;
}

.unit {
  margin-left: 3px;
  color: #666;
}

.embedded-table {
  margin: 0;
  padding: 0;
  border: none;
}
</style>