<template>
  <div class="bank-report-table">
   
    <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>
    <vxe-table
      border
      height="auto"
      ref="tableRef"
      show-header-overflow
      :data="tableFormData"
      :column-config="{ resizable: true }"
      :row-config="{ resizable: true }"
      class="custom-table"
    >
      <vxe-column field="serialNumber" title="序号" width="80"></vxe-column>
      <vxe-column field="project" title="项目" width="200">
        <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-for="(item, index) in row.content" :key="index">
                <span v-if="item.type === 'text'" v-html="item.value" style="line-height: 35px;"></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>

                <template v-else-if="item.type === 'yesno'">
                    <!-- 是/否单选组 -->
                    <vxe-radio-group v-model="formData[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[row.code +'_'+ item.field] === '是'" class="extra-fields-container">
                       
                        
                        <!-- 单个额外字段的情况 -->
                        <template v-if="item.extraField">
                          <span class="extra-fields-prompt">如是，</span>
                          <span class="extra-label">{{ item.extraLabel }}：</span>
                          <vxe-input 
                            v-model="formData[row.code + '_'+ item.extraField]" 
                            style="width: 300px"
                          ></vxe-input>
                          <span v-if="item.unit" class="unit">{{ item.unit }}</span>
                        </template>
                        
                        <!-- 多个额外字段的情况 -->
                        <template v-else-if="item.extraFields">
                          <span class="extra-fields-prompt">如是，</span>
                          <template v-for="(fieldOpt, index) in item.extraFields" :key="index">
                            <!-- 字段标签 -->
                            <span class="extra-field-item">
                              <span class="field-label">{{ fieldOpt.label }}: </span>
                              <template v-if="fieldOpt.formType === 'input'">
                                <vxe-input 
                                  v-model="formData[row.code + '_'+ fieldOpt.field]" 
                                  style="width: 250px"
                                ></vxe-input>
                              </template>
                              
                              <template v-else-if="fieldOpt.formType === 'number'">
                                <vxe-input 
                                  v-model="formData[row.code + '_'+ fieldOpt.field]" 
                                  type="number" 
                                  style="width: 250px"
                                ></vxe-input>
                                <span v-if="fieldOpt.unit" class="unit">{{ fieldOpt.unit }}</span>
                              </template>
                              
                              <template v-else-if="fieldOpt.formType === 'checkbox'">
                                <vxe-checkbox-group v-model="formData[row.code + '_'+ fieldOpt.field]">
                                  <vxe-checkbox 
                                    v-for="(opt, optIndex) in fieldOpt.options" 
                                    :key="optIndex" 
                                    :label="opt" 
                                    :content="opt"
                                  ></vxe-checkbox>
                                </vxe-checkbox-group>
                              </template>
                              
                              <template v-else-if="fieldOpt.formType === 'radio'">
                                <vxe-radio-group v-model="formData[row.code + '_'+ fieldOpt.field]">
                                  <vxe-radio 
                                    v-for="(opt, optIndex) in fieldOpt.options" 
                                    :key="optIndex" 
                                    :label="opt" 
                                    :content="opt"
                                  ></vxe-radio>
                                </vxe-radio-group>
                              </template>
                              
                              <template v-else>
                                <vxe-input 
                                  v-model="formData[row.code + '_'+ fieldOpt.field]" 
                                  :type="fieldOpt.formType" 
                                  style="width: 100px"
                                ></vxe-input>
                              </template>
                              
                              <!-- 其他选项 -->
                              <template v-if="fieldOpt.otherOption">
                                <div class="other-option">
                                  其他：
                                  <vxe-input 
                                    v-model="formData[row.code + '_'+ fieldOpt.otherField]" 
                                    style="width: 300px"
                                  ></vxe-input>
                                </div>
                              </template>
                            </span>
                          </template>
                        </template>
                      </div>
                    </template>
                  </template>

                <span v-else-if="item.type === 'radio-group'" class="radio-group">
                  <vxe-radio-group v-model="formData[row.code +'_'+ item.field]">
                    <vxe-radio v-for="(opt, optIndex) in item.options" :key="optIndex" :label="opt">{{ opt }}</vxe-radio>
                  </vxe-radio-group>
                </span>
                <span v-else-if="item.type === 'radio-group-extraFields'" class="radio-group" style="width:100%">
                  <vxe-radio-group v-model="formData[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[row.code +'_'+ item.field]==opt.label">
                        <span>{{ opt.extraField }}</span>
                        <vxe-input v-model="formData[row.code + '_'+ opt.otereField]"  style="width: 200px;"></vxe-input>  
                      </template>
                      <template v-if="opt.extraFields&&formData[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[row.code + '_'+ ccopt.field]"  style="width: 200px;"></vxe-input>  
                        </template>
                      </template>
                    </vxe-radio>
                  </vxe-radio-group>
                  <span v-if="item.unit" class="unit"> {{ item.unit }}</span>
                </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.otherOption">
                          <vxe-checkbox  label="其他">
                            其他：
                            <vxe-input v-model="formData[row.code + '_'+ item.otherField]"  style="width: 200px;" 
                            :disabled="!(formData[row.code+'_'+item.field]?.indexOf('其他')>-1)">
                            </vxe-input>
                          </vxe-checkbox>
                          
                        </template>
                      </vxe-checkbox-group>
                  </span> 
                </div>   
                <template v-else-if="item.type=='textarea'">
                  <vxe-textarea v-model="formData[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[row.code +'_'+ item.field]"  size="mini" class="table-input" :style="{width:item.width}">
                  </vxe-input>
                  <span v-if="item.unit" class="unit"> {{ item.unit }}</span>
                </template>
               
              </template>
 
          </div>
        </template>
      </vxe-column>
      <vxe-column field="remarks" title="备注" width="200">
        <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 { tableFormData } from '../../data/tb8.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 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 {
    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 st = strKey.indexOf("_");
        let t1 = strKey.substring(0,st);
        let t2 = strKey.substring(st+1);
        await setFormValues(t1,t2,valData,1)
      }
    }

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

}
}


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 });
    
    const valueObj = {};
    for (const data of recordData) {
      const key = `${data.itempid}_${data.itemid}_${data.rind}`;
      valueObj[key] = data.content;
    }


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


  } 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: `加载数据失败`, status: 'error' })
  } finally {
   
  }

}

</script>
<style lang="less" scoped>  
/* 基础字体和排版 */  
.bank-report-table {  
  font-family: "SimSun", "宋体", serif;  
  font-size: 12px;  
  color: #000;  
  margin: 5px auto;  
  width: 90%; /* 统一使用一个宽度 */  
  height:80vh
}  

/* 表格样式 */  
.custom-table, .attachment-table {  
  width: 100%;  
  border: 1px solid #000;  
  border-collapse: collapse; /* 更整齐的边框 */  
}  

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

/* 内容单元格 */  
.content-cell {  
  line-height: 1.8;  
}  

/* 输入框样式 */  
.table-input,  
.vxe-input {  
  height: 24px;  
  line-height: 30px;  
  min-width: 150px;  
  margin: 0 2px;  
  padding: 0 5px;  
  border: none; /* 去掉多余的边框，只留底部边框 */  
  border-bottom: 1px solid #333;  
  background: transparent;  
  text-align: center;  
}  

/* 表单元素的标签和图标 */  
.vxe-radio--label,  
.vxe-checkbox--label {  
  font-size: 12px;  
}  

.vxe-radio--icon,  
.vxe-checkbox--icon {  
  font-size: 12px;  
}  

/* 单选框组和复选框组布局 */  
.vxe-radio-group,  
.vxe-checkbox-group {  
  display: inline-block;  
  margin-right: 5px;  
  max-width: 99%;
}  

/* 其他辅助样式 */  
.radio-group,
.checkbox-group {  
  display: inline-block;  
  margin-right: 5px;  
  max-width: 99%;
}  

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

/* 附件部分样式 */  
.attachments {  
  margin-top: 20px;  
  width: 100%;  
}  

.attachments h4 {  
  font-size: 14px;  
  font-weight: bold;  
  margin-bottom: 10px;  
}  

.attachment-table {  
  width: 100%;  
  border: 1px solid #000;  
  border-collapse: collapse; /* 统一边框处理 */  
}  

/* 无用或重复定义已优化移除 */  

/* 其他特殊块 */  
blockquote {  
  padding: 0 5px;  
  color: black;  
  cursor: pointer;  
}  

</style>  


<style scoped>
.extra-fields-container {
  margin-left: 40px;
  margin-top: 8px;
}

.extra-fields-prompt {
  margin-bottom: 8px;
}

.extra-field-item {
  margin-bottom: 12px;
}

.field-label {
  display: inline-block;
  min-width: 80px;
}

.other-option {
  margin-top: 8px;
}

.unit {
  margin-left: 8px;
  color: #888;
}
</style>