<template>
  <PageWrapper  contentFullHeight="true" style="height:90%;background:red;overflow: 'hidden'">
      <a-row :gutter="12" style="background:#d9d9d9;padding:10px 10px;overflow: 'hidden'">
          <a-col :span="7">
            <a-card style="margin:0px"> 
              <div style="font-size:15px;overflow-y: auto;height:calc(90vh - 60px);">
                  <a-directory-tree :showLine="showLine" :tree-data="systemCategoryData"
                      v-model:expandedKeys="expandedKeys"
                      v-model:selectedKeys="selectedKeys"
                      @select="onTreeSelect"
                      >
                  </a-directory-tree>
              </div>
            </a-card>  
          </a-col>
          <a-col :span="17">
            <a-card style="height:calc(90vh - 66px)" bodyStyle="background:#FFFFFF;overflow-y: auto;height:100%" :title="cardTitle">
              <template #extra><a href="#" @click="saveSurverExe()">保存</a></template>
              <div style="font-size:15px;height:100%">  
                  <a-form layout="horizontal" :model="formData" :label-col="{span:4}" :wrapper-col="{span:18}">
                  <a-form-item v-for="(item,ind) in cfgList" :key="ind" :label="item.attrName" style="margin-bottom: 10px;">
                    <div style="display: flex; align-items: center;margin: 0 0 8px 0">
                      <a-textarea v-model:value="formData[item['cfgFormKey']]" style="width:80%" placeholder="请输入" />
                      <a-button  type="link" @click="handleSave(item)">保存</a-button>
                      <a-button danger  type="link" v-if="item.collMethod==2&&!formData[item['cfgFormKey']]" @click="handlePullData(item)">获取</a-button>
                    </div>
                  </a-form-item>
                </a-form>
                
              </div>
            </a-card>
          </a-col>
      </a-row>   
      
  </PageWrapper>    

</template>
<script lang="ts" setup>
  import {ref,reactive,computed} from 'vue';
  import { loadTreeData} from '/@/views/system/category/category.api';
  import { queryDataFromAPI } from '/@/views/wb/manage/WbCompanyInfo.api';
  import { saveOrUpdateBatch,queryAlllist,saveOrUpdate} from '/@/views/wb/survey/WbSurveyResult.api';
  import {defHttp} from '/@/utils/http/axios';

  const queryAllByCode = '/wb.survey/wbSurveyCfg/queryAllByCode';
  const emit = defineEmits(['register','success']);

  const formData = reactive<Record<string, any>>({});
  const systemCategoryData = ref([]);
  const showLine = ref(false)
  const expandedKeys = ref([]);
  const selectedKeys = ref([]);
  const companyInfo =ref();
  const cardTitle =ref("");
  const cfgList = ref([])

  const dataFromThirdAPI = ref({})
  const oldFormVals =ref({})

  async function onTreeSelect(selectedKeys, e:{selected: Boolean, selectedNodes,node,event}) {
    if(e.selected) {
      let domainCode = e.node.code;
      cardTitle.value = e.node.title;
      cfgList.value = await findCfgList(domainCode);
      cfgList.value.forEach(function(data) {
        let strKey = data["id"] + "_" + data["domainCode"]
        data["cfgFormKey"] = strKey
        let oldObjVal = oldFormVals.value[strKey];
        if(oldObjVal) {
          data["oldid"] = oldObjVal.id
          formData[data['cfgFormKey']] = oldObjVal.surveyResult
        } else {
          formData[data['cfgFormKey']] = dataFromThirdAPI.value [data["attrKey"]]
        }
      });
    }     
  }

  async function setDomainData(pcode) {
      let list =  expandedKeys.value =  []
      systemCategoryData.value =list=  await loadTreeData({'async': false,'pcode':pcode});
      if(!list||list.length==0) return;
      //let isLeaf = false;
      // do {
      //   if(!list[0].leaf) {
      //     let childs = list[0].children;
      //     if(childs.length>0) {
      //       expandedKeys.value.push(list[0].key)
      //       list = childs
      //       isLeaf = false;
      //     } 
      //   } else {
      //     selectedKeys.value.push(list[0].key)
      //     isLeaf = true;
      //     let domainName = list[0].title
      //     let domainCode = list[0].code
      //     cfgList.value = await findCfgList(domainCode);

      //   }

      // } while(!isLeaf)

  }


  setDomainData("B06")

  //form 表单

 

  async function findCfgList(code) {
    return await defHttp.get({url: queryAllByCode,params:{code:code}}); 
  }

  async function saveSurverExe() {
    formData["cid"] =  companyInfo.value.id
    let oldIdObj= {};
    cfgList.value.forEach(function(cfg) {
      oldIdObj[cfg["cfgFormKey"]] = cfg['oldid']
    });
    formData["oldIdObj"] =  oldIdObj;
    await saveOrUpdateBatch(formData)
  }

  // async function handleSubmit(v) {
  //   try {
  //     let values = await validate();
  //     if(recordTp.value==2) {
  //       setQuarterToDate(values)
  //     }
  //     setDrawerProps({confirmLoading: true});
  //     await saveOrUpdate(values, isUpdate.value);
  //     closeDrawer();
  //     emit('success');
  //   } finally {
  //     setDrawerProps({confirmLoading: false});
  //   }
  // }


  async function handlePullData(record){
    if(!record.apiId) return
     cfgList.value.forEach(function(cfg) {
      if(cfg["attrKey"]){
        formData[cfg['cfgFormKey']] = dataFromThirdAPI.value [cfg["attrKey"]]
      }
    });
  }

  async function setCompanyInfo(obj){
      companyInfo.value = obj
      formData["cid"] = obj["id"];
      dataFromThirdAPI.value = await queryDataFromAPI({ cid: companyInfo.value.id,apiId:0})
      oldFormVals.value = await queryAlllist({ cid: companyInfo.value.id,domainCode:'B06*'})
  }


  async function handleSave(item){
    let tpmFormObj = {}
    tpmFormObj["id"] =  item["oldid"];
    tpmFormObj["cid"] = formData["cid"];
    tpmFormObj["domainCode"] =  item["domainCode"];
    tpmFormObj["surveyItemId"] = item.id;
    tpmFormObj["surveyResult"] = formData[item['cfgFormKey']];

    let isUpdate = item["oldid"]?true:false
    let retData= await saveOrUpdate(tpmFormObj, isUpdate)
    oldFormVals.value[item['cfgFormKey']] = retData

  }

  defineExpose({
      setCompanyInfo
  });

  

</script>

<style scope>
.underline-input {
border-left:none;
border-top:none;
border-right:none;
width: 100%;
}
</style>