<template>
  <n-button type="primary" @click="showImportModal">导入数据</n-button>
  <n-modal
    v-model:show="showModal"
    :show-icon="false"
    preset="dialog"
    title="导入"
    :mask-closable="false"
  >
    <n-form :model="formValue" label-width="auto" show-require-mark>
      <n-form-item label="数据">
        <n-upload :default-upload="false" :max="1" @change="handleChange">
          <div style="display: flex;align-items: center;">
            <n-button>上传文件</n-button>
            <div style="margin-left: 20px;color: #2d8cf0;">进度：{{ sum }}/{{ dataList.length }}</div>
          </div>
        </n-upload>
      </n-form-item>
    </n-form>
    <div style="float: right;">
      <n-button @click="showModal=false">
        取消
      </n-button>
      <n-button type="primary" @click="submitCallback" :disabled="disableds" style="margin-left: 20px;">
        确认
      </n-button>
    </div>
  </n-modal>
</template>

<script setup>
import { addTaskDatas } from '@/api';
import { read, utils } from 'xlsx';
import { useDateFormat } from '@vueuse/core';
import { ref, watch } from 'vue';
const emit = defineEmits(['importFiles']);
const props = defineProps({
  task: {
    required: true,
    default: {},
  },
});
const disableds = ref(false)
const message = useMessage();
const sum = ref(0)
// 是否展示 Modal
const showModal = ref(false);

//
const dataList = ref([]);

/* 读取文件 */
const readFile = (file) => {
  return new Promise((resolve) => {
    const reader = new FileReader();
    reader.readAsBinaryString(file);
    reader.onload = (ev) => {
      resolve(ev.target.result);
    };
  });
};

// 组件状态变化的回调
const handleChange = async ({ file }) => {
  const dataBinary = await readFile(file.file);
  const workBook = read(dataBinary, {
    type: 'binary',
    cellDates: true,
  });
  const workSheet = workBook.Sheets[workBook.SheetNames[0]];
  dataList.value = utils.sheet_to_json(workSheet);
  console.log('导入',dataList.value)
  dataList.value.forEach((item) => {
    item['记录时间'] = useDateFormat(
      item['记录时间'],
      'YYYY-MM-DD HH:mm:ss'
    ).value;
  });

};

// 表单数据
const formValue = reactive({
  Time_start: null,
  Time_end: null,
  T_sn: '',
  T_id: '',
  page: 1,
  page_z: 9999,
});

// 显示导入
const showImportModal = () => {
  sum.value = 0
  showModal.value = true;
  disableds.value = false
};
watch(showModal,(newVal)=>{
  if(!newVal){
    sum.value = 0
    dataList.value=[]
  }
})
//
const submitCallback = async () => {
  sum.value = 0
  if(dataList.value.length==0){
    message.error('没有可导入数据哦，检查文件是否为空数据')
    return
  }else{
    disableds.value = true
    let chunk = 100;
    for (let i = 0; i < dataList.value.length; i += chunk) {
      let dataIt = await dataFun(dataList.value.slice(i, i + chunk))
      const resIt = await addTask(dataIt)
      sum.value += Number(resIt.data.Data)
      if(sum.value==dataList.value.length){
        message.success('数据导入完成')
        emit('importFiles');
        // disableds.value = false
      }
    }
  } 
};

const dataFun = (arr)=>{
  return new Promise(resolve=>{
    const arr1 = arr.map(item => item['SN'] + '|' + item['编号'] + '|' + item['温度℃'] + '|' + item['湿度%'] + '|' + item['记录时间'])
    setTimeout(()=>{
      resolve(arr1.join('?'))
    },100)
  })
}

//
const addTask = async (item) => {
  return new Promise(resolve=>{
    setTimeout(() => {
      const res = addTaskDatas({
        T_task_id: props.task.T_task_id,
        T_Data:item
      });
      resolve(res)
    },100)
   
  })
};
</script>

<style lang="scss" scoped></style>
