<script lang="ts" setup>

import { ElDialog } from 'element-plus';

const props = withDefaults(defineProps<{
  fields:any[],
  formId:string,
  commitFunc:()=>void,
  closeFunc:()=>void,  //父级只需销毁组件
}>(),{})

//主表字段
const uploadURL=import.meta.env.VITE_APP_BASE_API+"/systemapi/task_management/import_form_list"
const checkList=ref<string[]>([]) 
const uploadFormData = computed(() => {
  return {
    formId: props.formId, // 用户的uuid
  }
});

onMounted(()=>{
  props.fields.forEach((val)=>{
    if (val.item && val.name!=="id"){
      checkList.value.push(val.name)
    }
  })
})

//上传失败 
function handleSigLoadErr(error: Error, uploadFile: UploadFile, uploadFiles:UploadFiles){
  ElMessage.error("导入失败")
}

function onDownloadTemplate(){
  //标题行
  const arr:string[]=[]
  props.fields.forEach((val)=>{
    if(checkList.value.includes(val.name)){
      arr.push(`"(${val.name})\n${val.item.label}"`)
    }
  })
  const filename= "导入模板.csv"
  const csvString = arr.join(',');
  const blob = new Blob([csvString], { type: "text/csv;charset=utf-8;" });
  const link = document.createElement("a");
  if (link.download !== undefined) { // feature detection
    // Browsers that support HTML5 download attribute
    const url = URL.createObjectURL(blob);
    link.setAttribute("href", url);
    link.setAttribute("download", filename);
    link.style.visibility = "hidden";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }
}
</script>

<template>
  <el-dialog :model-value="true" :style="{height: '60%',width:'60%'}" @close="props.closeFunc">
    <h3>请选择导入的字段</h3>
    <div style="display: flex; flex-direction:column;width: 80%; height: 50%;margin-top: 20px;">
      <el-checkbox-group v-model="checkList">
        <template v-for="vals in props.fields">
          <el-checkbox v-if="vals.item && vals.name!=='id'" :key="vals.name"  :value="vals.name" >
            {{ vals.item.label }}
          </el-checkbox>
        </template>
      </el-checkbox-group>
    </div>
    <div style="width: 80%;margin: 20px;">
      *  请下载<a @click="onDownloadTemplate"> 导入模板</a>，不要修改模板的首行标题行。
    </div>
    <el-upload class="el-button el-button--default" 
      :data="uploadFormData"
      accept=".csv,.xls,.xlsx,.XLS,.XLSX"
      :on-error="handleSigLoadErr"
      :on-success="commitFunc"
      :action="uploadURL" :limit="1">
      <span>导入</span>
    </el-upload>
  </el-dialog>
</template>
<style>
    /* dialog的body内容样式设置*/
    .el-dialog__body{
        height: 96%;
        display: flex;
        flex-direction: column;
        align-items: center;
    }
    .el-dialog{
      /* 让整个弹出窗口位置更高一些*/
      --el-dialog-margin-top:7vh; 
    }
    
</style>