<template>
  <BasicDrawer placement="right" 
  @register="registerDrawer" 
  v-bind="$attrs" 
  :showFooter="showFooter"
  :title="pageTitle" width="80%"> 
  <PageWrapper  contentFullHeight="true" contentClass="flex" style="height:100%">
      <a-row :gutter="10" style="background:#ececec;padding:10px;">
            <a-col :span="8">
                  <a-card style="width: 100%" title="调查报告">
                    <div style="font-size:15px;overflow-y: auto;height:755px;padding:0px 0px 0px 5px;margin-right:10px">
                      <a-directory-tree :showLine="showLine"  :tree-data="leftTree" 
                        v-model:expandedKeys="expandedKeys"
                        v-model:selectedKeys="selectedKeys"
                        @select="onTreeSelect"
                      >
                      </a-directory-tree>
                    </div>
                  </a-card>
            </a-col>

            <a-col :span="16">
              <div style="font-size:15px;overflow-y: auto;height:862px;padding:0px 0px 0px 0px;margin-right:10px">
                <a-card style="width: 100%;padding:7px 0px;margin:5px 0px" v-for="(item,ind)  in tplItemDatas" :key="ind">
                  <template #extra>
                      <a-button type="link" @click="handleSubmit(item.code)">保存</a-button>
                  </template>
                  <template #title>
                      <div class="btitle">
                        <JEllipsis :value="item.code+'.'+ item.sname" length="50"/>
                      </div>
                  </template>
                 
                  <a-form :label-col="labelCol" :wrapper-col="wrapperCol">
                    <a-form-item label="当前现状">
                      <div style="display: flex;flex-wrap: wrap;"  v-if="item.valNum>1">
                        <template v-for="(itemEle,ind2) in item.sformatAry" :key="ind2">
                          <a-space v-if="itemEle=='number'" style="margin:5px">
                            【<a-input-number  v-model:value="formDataObj[item.code]['vals'][ind2]"  class="underline-input"></a-input-number>】
                          </a-space>
                          <a-space v-else-if="itemEle=='yesno'" style="margin:5px">
                            【 <a-radio-group  v-model:value="formDataObj[item.code]['vals'][ind2]" :options="['是','否']"> </a-radio-group>】</a-space>
                          <a-space v-else-if="itemEle=='string'" style="margin:5px">
                            【<a-input  v-model:value="formDataObj[item.code]['vals'][ind2]"  class="underline-input" style="width:300px"></a-input>】
                          </a-space>
                          <a-space v-else-if="itemEle=='des'" style="margin:5px">
                            【<a-textarea  v-model:value="formDataObj[item.code]['vals'][ind2]"  class="underline-input" style="width:300px"></a-textarea>】
                          </a-space>
                          <a-space v-else style="margin:5px">{{itemEle}}</a-space>
                        </template>
                       
                      </div>    
                      <div style="display: flex;flex-wrap: wrap;"  v-else>
                        <template v-for="(itemEle,ind) in item.sformatAry" :key="ind">
                          <a-space v-if="itemEle=='number'" style="margin:5px">
                            【<a-input-number  v-model:value="formDataObj[item.code]['vals']"  class="underline-input"></a-input-number>】
                          </a-space>
                          <a-space v-else-if="itemEle=='yesno'" style="margin:5px">
                            【 <a-radio-group  v-model:value="formDataObj[item.code]['vals']" :options="['是','否']"> </a-radio-group>】</a-space>
                          <a-space v-else-if="itemEle=='string'" style="margin:5px">
                            【<a-input  v-model:value="formDataObj[item.code]['vals']"  class="underline-input" style="width:300px"></a-input>】
                          </a-space>
                          <a-space v-else-if="itemEle=='des'" style="margin:5px">
                            【<a-textarea  v-model:value="formDataObj[item.code]['vals']"  class="underline-input" style="width:300px"></a-textarea>】
                          </a-space>
                          <a-space v-else style="margin:5px">{{itemEle}}</a-space>
                        </template>
                      </div>
                    </a-form-item>
                    <a-form-item label="具体描述">
                      <a-textarea  placeholder="" allow-clear rows="3" v-model:value="formDataObj[item.code]['content']"/>
                    </a-form-item>
                    <a-form-item label="材料清单">
                      <SurveyUserDataFileTable :ref="setBaseRefs(item.code)"  :values="fileData[item.code]"  :fieldKey="item.code"/>
                    </a-form-item>
                  </a-form>
                </a-card>
              </div>  
            </a-col>
      </a-row>      
  </PageWrapper>    
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed } from 'vue';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { MoreOutlined} from '@ant-design/icons-vue';
  import {BasicTable, useTable, TableAction,EditRecordRow,BasicColumn} from '/@/components/Table';
  import { cloneDeep } from 'lodash-es';
  import { listTree } from '../SurveyTplMain.api';
  import { allList } from '../SurveyTplItem.api';
  import { JEllipsis } from '/@/components/Form';
  import { userDataList,saveOrUpdate } from '../SurveyUserData.api';
  import SurveyUserDataFileTable from './SurveyUserDataFileTable.vue';

  const showFooter = ref(false)

  const curSelNode = ref({})
  const showLine = ref(false)
  const expandedKeys = ref([]);
  const selectedKeys = ref([]);
  const leftTree = ref([])
  const tplItemDatas = ref([])

  interface FormData {
    id: string,
    ufid: string,
    code: string,
    tplid: string,
    content: string,
    files: string,
    vals: any,
  }

  const formData = reactive<FormData>({
    id: '',
    ufid: '',
    code: '', 
    tplid: '',
    content: '',
    files: '',
    vals: ''
  });

  const formDataObj = ref<Record<string, FormData>>({});
  const fileData = ref({});

  const labelCol= { span: 3 };
  const wrapperCol= { span: 21 };

  const [registerDrawer] = useDrawerInner(async (data) => {
    showFooter.value = false; 
    formData.ufid = data.record.id
  });

  const pageTitle = ref("首都机场财务公司")

  async function setTplMainDatas() {
    leftTree.value = await listTree({})
  }

  async function setTplItemDatas(tplid) {
    let itemDatas =  await allList({tplid:tplid})
    if(!itemDatas||itemDatas.length==0) {
      return ;
    }

    let valList =   await userDataList({tplid:tplid})
    let tmpFileData={}

    for(let i=0;i<itemDatas.length;i++){
      let code = itemDatas[i]["code"];
      setFormatValEle(itemDatas[i])
      let formDataTmp = { ...formData };
      formDataTmp["code"] = code
      let m = itemDatas[i]["valNum"]*1

      if(m>1) {
        formDataTmp["vals"] = {}
      } else {
        formDataTmp["vals"] = ""
      }
 
      formDataObj.value[code] =formDataTmp;
      tmpFileData[code] = itemDatas[i]["files"]
    }

    tplItemDatas.value =itemDatas
    
    if(valList&&valList.length>0) {
      for(let i=0;i<valList.length;i++){
        let formDataTmp = { ...formData };
        if(valList[i]["vals"]) {
          if(valList[i]["vals"].indexOf("{")>-1) {
            valList[i]["vals"] =  JSON.parse(valList[i]["vals"]);
            Object.assign(formDataTmp, valList[i])
          } else {
            Object.assign(formDataTmp, valList[i])
          }
        } 
        
        formDataObj.value[valList[i]["code"]] =formDataTmp;
        setFileValue(formDataTmp)
      }
    }

    for (let code in tmpFileData) {
      if(!tmpFileData.hasOwnProperty(code)){
        continue
      }
      if(fileData.value[code]) {
        continue;
      }
      if(!tmpFileData[code]) {
        continue;
      }
      setFileData(tmpFileData[code],code)
    }

  }

  setTplMainDatas()

  function onTreeSelect(selectedKeys, e:{selected: Boolean, selectedNodes,node,event}) {
    if(e.selected) {
      curSelNode.value = e.node;
      let id = e.node.id
      formData.tplid = id
      setTplItemDatas(id)
    }
  }

  function setFormatValEle(strObj) {
   let tmpAry =  strObj["sformat"].split(/(【[^】]+】)/);
   tmpAry = tmpAry.filter(item => item !== "");
   let valDesAry = strObj["valdes"].split("|")
   let p = 0
   for(let i=0;i<tmpAry.length;i++) {
     if(tmpAry[i].indexOf("【")==0) {
      tmpAry[i] = valDesAry[p++] || "string"
     }
   }
    strObj["sformatAry"] = tmpAry
    strObj["valNum"] = valDesAry.length
    
  }

  const baseRefs = {};
  const setBaseRefs = (index) => {
    return (ref) => {
      baseRefs['child' + index] = ref;
    };
  };

  function handleSubmit(code){
    let formDataTmp = formDataObj.value[code]
    Object.values(baseRefs).forEach(childComponent => {
      if(childComponent){
          let resObj =  childComponent.getData?.();
          let field = resObj['field']
          if(field==code&&resObj.value) {
            formDataTmp['files'] = JSON.stringify(resObj.value)
            return 
          }
        }
    });
    let isUpdate = formDataTmp.id?true:false

    if(formDataTmp["vals"]) {
      if( typeof formDataTmp["vals"] === "object" && formDataTmp["vals"] !== null) {
        formDataTmp["vals"] = JSON.stringify(formDataTmp["vals"])
      }
    }


    saveOrUpdate(formDataTmp,isUpdate)
  }

  function setFileData(files,code) {
    if(!files) return ;
    let tmpAry = files.split("\n");
    let tmpAryObj  = []
    for(let j=0;j<tmpAry.length;j++){
      let fileName = tmpAry[j].trim(); 
      if (fileName) {
        let tmp1 = {key:j, name: fileName, fileurl: "" };
        tmpAryObj.push(tmp1);
      }
    }
    fileData.value[code] = tmpAryObj
  }


  function setFileValue(itemData) {
    let files = itemData["files"]
    if(!files) return ;
    let tmpAry = JSON.parse(files)
    let tmpAryObj  = []
    for(let j=0;j<tmpAry.length;j++){
      let valAry = tmpAry[j].split("|"); 
      let tmp1 = {key:j, name: valAry[0], fileurl: valAry[1]};
      tmpAryObj.push(tmp1);
    }
    fileData.value[itemData.code] = tmpAryObj

  }


  

</script>

<style scope>
.underline-input {
  border-left:none;
  border-top:none;
  border-right:none;
  width: 100px;
}
.btitle {
    font-family: Arial, sans-serif; /* 使用一个常见的字体 */
    font-size: 16px; /* 设置字体大小 */
    color: #007bff; /* 设置字体颜色 */
    text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3); /* 添加文字阴影效果 */
    margin-bottom: 0px; 
}
</style>