<template>
  <n-button type="primary" @click="showImportModal"
    >导入数据（冷链平台）</n-button
  >
  <n-modal
    style="width: 30%"
    v-model:show="showModal"
    :show-icon="false"
    preset="dialog"
    title="导入"
  >
    <n-space vertical>
      <n-card>
        <n-form
          :model="formValue"
          label-placement="left"
          label-width="auto"
          show-require-mark
        >
          <n-form-item label="起止时间">
            <n-date-picker
              value-format="yyyy.MM.dd HH:mm:ss"
              type="datetimerange"
              @update:formatted-value="
                (value) => {
                  formValue.Time_start = value[0];
                  formValue.Time_end = value[1];
                }
              "
            />
          </n-form-item>
          <n-form-item label="SN" path="T_sn">
            <n-input v-model:value="formValue.T_sn" />
          </n-form-item>
          <n-form-item label="探头编号" path="T_id">
            <n-input v-model:value="formValue.T_id" />
          </n-form-item>
        </n-form>
        <template #action>
          <div class="flex justify-end">
            <n-button type="primary" @click="getDataList">查询</n-button>
          </div>
        </template>
      </n-card>
      <n-card title="数据总量">
        <template #header-extra>
          <n-spin :show="spinShow">
            <n-progress
              type="dashboard"
              gap-position="bottom"
              :percentage="100"
            >
              <span class="text-center font-bold"
                >{{ percentage }}/{{ total }}</span
              >
            </n-progress>
          </n-spin>
        </template>
        <n-descriptions bordered class="mt-auto">
          <n-descriptions-item label="SN">
            {{ formValue.T_sn }}
          </n-descriptions-item>
          <n-descriptions-item label="探头编号">
            {{ formValue.T_id }}
          </n-descriptions-item>
        </n-descriptions>
        <template #action>
          <div class="flex justify-end">
            <n-popconfirm @positive-click="handleImport">
              <template #trigger>
                <n-button type="primary" :disabled="disableds">导入</n-button>
              </template>
              是否确认导入？
            </n-popconfirm>
          </div>
        </template>
      </n-card>
    </n-space>
  </n-modal>
</template>

<script setup>
import { getV3DataList, addTaskDatas } from '@/api';
import { useMessage } from 'naive-ui';

const message = useMessage();

const notification = useNotification();

const props = defineProps({
  task: {
    required: true,
    default: {},
  },
});
const disableds = ref(false)
// 是否展示 Modal
const showModal = ref(false);

// 是否展示 Spinner
const spinShow = ref(false);

//
const dataList = ref([]);

// 总数
const total = ref(0);

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

// 当前完成数
const percentage = ref(0);

// 显示导入
const showImportModal = () => {
  showModal.value = true;
  formValue.Time_start = null;
  formValue.Time_end = null;
  formValue.T_sn = null;
  formValue.T_id = null;
  disableds.value = false
  // formValue.Time_start = '2023.04.25 00:00:00';
  // formValue.Time_end = '2023.04.25 00:30:00';
  // formValue.T_sn = 2023141974576341;
  // formValue.T_id = 1;

  total.value = 0;
  percentage.value = 0;
};

// 批量导入
const handleImport = async () => {
  if (dataList.value.length === 0) {
    return message.info('无数据');
  }
  disableds.value = true
  let arr = dataList.value
  let chunk = 100;
  for (let i = 0; i < arr.length; i += chunk) {
    let dataIt = await dataFun(arr.slice(i, i + chunk))
    
    const resIt = await addTask(dataIt)
    console.log('已经处理',resIt)

    percentage.value += Number(resIt.data.Data)
    if(percentage.value==total.value){
      message.success('数据导入完成')
    }
  }


  // for (let i = 0 ;i< arr.length;i++) {
  //     const {data:res} = await addTask(arr[i]);
  //     if (res.Code == 200) {
  //       percentage.value += 1;
  //       if (percentage.value === total.value) {
  //         notification.success({
  //           title: 'ok! 导入数据已完成',
  //           duration: 2000,
  //           keepAliveOnHover: true,
  //         });
  //       }
  //     }else{
  //       break
  //     }
  //   }

};

const dataFun = (arr)=>{
  return new Promise(resolve=>{
    const arr1 = arr.map(item => item.T_sn + '-'+ item.T_id + '|' + item.T_id + '|' + item.T_t + '|' + item.T_rh + '|' + item.T_time)
    resolve(arr1.join('?'))
  })
}
// 导入任务
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)
   
  })
};



// 查询数据
const getDataList = async () => {
  console.log('查询1',formValue)
  
  const sto = await inspect(formValue)
  console.log('查询2',formValue)
  if(sto){
    // spinShow.value = true;
    const { data: res } = await getV3DataList({
      Time_start: formValue.Time_start + '',
      Time_end: formValue.Time_end + '',
      T_snid: `${formValue.T_sn},${formValue.T_id}|`,
      page: 1,
      page_z: 9999,
    });
    dataList.value = res.Data.Data || [];
    total.value = res.Data.Num || 0;
  }else{
    message.error('搜索条件全部必填哦')
  }
};
const inspect = (value)=>{
  return new Promise(resolve=>{
    if(value.Time_start!= null && value.Time_end!=null && value.T_sn!=null && value.T_id!=null){
      resolve(true)
    }else{
      resolve(false)
    }
  })
 
} 
</script>

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