<template>
  <n-button type="primary" @click="showImportModal">导入数据</n-button>
  <n-modal
    v-model:show="showModal"
    :show-icon="false"
    preset="dialog"
    title="导入"
  >
    <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 { addTaskData } from '@/api';
import { read, utils } from 'xlsx';
import { useDateFormat } from '@vueuse/core';
import { ref, watch } from 'vue';

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);
  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)=>{
  console.log('监听',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
    for (let i = 0; i <  dataList.value.length; i++) {
      let resIt  = await addTask(dataList.value[i]);
      sum.value +=1
      if(resIt.data.Code!=200){
        break
      }
      if(sum.value==dataList.value.length){
        message.success('数据导入完成')
        disableds.value = false
      }
  }
  }
  
  
};

//
const addTask = async (item) => {
  return new Promise(resolve=>{
    setTimeout(() => {
      const res = addTaskData({
        T_task_id: props.task.T_task_id,
        T_sn: item['SN'],
        T_id: item['编号'],
        T_t: item['温度'],
        T_rh: item['湿度'],
        T_time: item['记录时间'],
      });
      resolve(res)
    },200)
   
  })
};
</script>

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