<template>
  <div class="h-full flex flex-col gap-y-3">
    <n-page-header @back="$router.back">
      <template #title> 报告生成 </template>
      <template #extra>
        <n-space>
          <n-popconfirm @positive-click="putTemplateData">
            <template #trigger>
              <n-button type="primary">生成报告</n-button>
            </template>
            确认生成报告？
          </n-popconfirm>
          <n-button type="primary" @click="showUploadModal"
            >上传验证报告</n-button
          >
        </n-space>
      </template>
    </n-page-header>
    <n-scrollbar :style="{ maxHeight: `${height - 150}px` }" trigger="none">
      <FormList :form-list="formValue.formList" />
      <!-- <n-button @click="handleClick">button</n-button> -->
    </n-scrollbar>
  </div>
  <n-modal
    style="width: 30%"
    v-model:show="modal.showModal"
    :show-icon="false"
    preset="dialog"
    :mask-closable="false"
    :title="modal.title"
    @close="onCloseModal"
  >
    <n-upload
      class="w-full"
      list-type="image-card"
      :default-upload="false"
      :max="1"
      @change="handleChange"
      v-if="modal.title === '上传验证'"
    >
      上传文件
    </n-upload>
    <template v-else>
      <n-card embedded :bordered="false">
        <template #header>
          <div class="flex justify-center">
            <n-progress
              :status="
                keyInfo.Code === 600
                  ? 'default'
                  : keyInfo.Code === 601
                  ? 'success'
                  : 'error'
              "
              type="dashboard"
              gap-position="bottom"
              :percentage="keyInfo.Schedule"
            />
          </div>
        </template>
        <n-scrollbar
          style="max-height: 300px"
          trigger="none"
          ref="scrollbarRef"
        >
          <div class="flex" v-for="(item, index) of items" :key="index">
            <n-badge class="mr-5" type="info" :value="index + 1" />
            <span>{{ item }}</span>
          </div>
        </n-scrollbar>
      </n-card>
    </template>
    <template #action>
      <n-space v-if="modal.title === '上传验证'">
        <n-button @click="modal.showModal = false">取消</n-button>
        <n-button type="primary" @click="editTaskInfo">确认</n-button>
      </n-space>
      <n-button
        v-else
        type="primary"
        :disabled="keyInfo.Code !== 601"
        @click="handleDownload"
        >下载文件</n-button
      >
    </template>
  </n-modal>
</template>

<script setup>
import {
  putVerifyTemplateMapData,
  editTask,
  getTaskDataClassList,
  getVerifyTemplateMapDataList,
  generateReport,
  generateKey,
} from '@/api';
import * as qiniu from 'qiniu-js';
import { getToken } from '@/utils/storage/sessionToken';
import { getFileToken } from '@/common';
import { useWindowSize } from '@vueuse/core';
import { NButton } from 'naive-ui';
import { onBeforeUnmount } from 'vue';
import FormList from '@/components/FormList.vue';

const { height } = useWindowSize();

const message = useMessage();

const scrollbarRef = ref(null);

const task = window.sessionStorage.getItem('task')
  ? JSON.parse(window.sessionStorage.getItem('task'))
  : {};

// 表单对象
const formValue = reactive({
  pdf: '',
  formList: [],
});

const handleClick = () => {
  console.log(formValue.formList);
};

// 查询数据
const queryData = reactive({
  T_source: 2,
  T_task_id: task.T_task_id,
  T_VerifyTemplate_id: task.T_VerifyTemplate_id,
});

//
const classList = ref([]);

// 模态框数据源
const modal = reactive({
  showModal: false,
  title: '',
});

//
const handleChange = async ({ file }) => {
  const token = await getFileToken(file.name.split('.')[1]);
  const observable = qiniu.upload(
    file.file,
    file.name,
    token,
    {},
    {
      useCdnDomain: true,
    }
  );
  observable.subscribe({
    next: (result) => {
      // 主要用来展示进度
      console.warn(result);
    },
    error: () => {
      message.error('上传失败');
    },
    complete: (res) => {
      formValue.pdf = res.key;
    },
  });
};

// 显示上传验证对话框
const showUploadModal = () => {
  modal.title = '上传验证';
  modal.showModal = true;
};

// 上传验证
const editTaskInfo = async () => {
  try {
    const { data: res } = await editTask({
      T_task_id: queryData.T_task_id,
      T_pdf2: formValue.pdf,
    });
    if (res.Code === 200) {
      message.success(res.Msg);
      modal.showModal = false;
    }
  } catch (e) {
    console.log(e);
  }
};

// 验证报告生成 报告
const generateReportInfo = async (obj) => {
  const { data: res } = await generateReport({
    T_task_id: task.T_task_id,
    T_VerifyTemplate_id: task.T_VerifyTemplate_id,
    ...obj,
  });
  if (res.Code === 200) {
    generateKeyInfo(res.Data);
  }
};

let timer = 0;
const keyInfo = ref({});
const items = computed(() => {
  return keyInfo.value.Item
    ? keyInfo.value.Item.split('\n').filter((item) => item)
    : [];
});

// 验证报告生成 获取生成结果
const generateKeyInfo = async (key) => {
  const { data: res } = await generateKey({
    key,
  });
  if (res.Code === 600) {
    timer = setTimeout(() => {
      generateKeyInfo(key);
    }, 3000);
  } else {
    clearTimeout(timer);
  }
  scrollbarRef.value.scrollTo({
    top: 9999,
    behavior: 'smooth',
  });
  keyInfo.value = res;
};

// 关闭对话框时触发
const onCloseModal = () => {
  keyInfo.value = {};
  clearTimeout(timer);
};

// 下载文件
const handleDownload = () => {
  window.open(keyInfo.value.Data);
};

// 生成报告
const putTemplateData = async () => {
  
  try {
    const arr = toRaw(formValue.formList);
    const VerifyTemplateMapData = arr.map((item) => {
      if (item.T_label === 3 || item.T_label === 9) {
        return {
          T_VerifyTemplateMap_id: item.T_VerifyTemplateMap_id,
          T_value: item.T_value.join('|'),
          T_source: item.T_source,
          T_flow_sort: item.T_flow_sort,
          T_max_time: item.T_max_time,
          T_min_time: item.T_min_time,
        };
      } else if (item.T_label === 12) {
        return {
          T_VerifyTemplateMap_id: item.T_VerifyTemplateMap_id,
          T_value: item.T_value.join('/'),
          T_source: item.T_source,
          T_flow_sort: item.T_flow_sort,
          T_max_time: item.T_max_time,
          T_min_time: item.T_min_time,
        };
      } else if (item.T_label === 13) {
        return {
          T_VerifyTemplateMap_id: item.T_VerifyTemplateMap_id,
          T_value: `${item.T_value[0].join('|')}/${item.T_value[1]}`,
          T_source: item.T_source,
          T_flow_sort: item.T_flow_sort,
          T_max_time: item.T_max_time,
          T_min_time: item.T_min_time,
        };
      } else {
        return {
          T_VerifyTemplateMap_id: item.T_VerifyTemplateMap_id,
          T_value: item.T_value + '',
          T_source: item.T_source,
          T_flow_sort: item.T_flow_sort,
          T_max_time: item.T_max_time,
          T_min_time: item.T_min_time,
        };
      }
    });
    const token = getToken();
    const { data: res } = await putVerifyTemplateMapData({
      User_tokey: token,
      T_source: queryData.T_source,
      T_task_id: queryData.T_task_id,
      T_VerifyTemplate_id: queryData.T_VerifyTemplate_id,
      VerifyTemplateMapData,
    });
    if (res.Code === 200) {
      const obj = {};
      for (let i of arr) {
        if (i.T_label === 3 || i.T_label === 9) {
          obj[i.T_name] = i.T_value.join('|');
        } else if (i.T_label === 12) {
          obj[i.T_name] = i.T_value.join('/');
        } else if (i.T_label === 13) {
          obj[i.T_name] = `${i.T_value[0].join('|')}/${i.T_value[1]}`;
        } else {
          obj[i.T_name] = i.T_value;
        }
      }
      modal.title = '生成报告';
      modal.showModal = true;
      generateReportInfo(obj);
    }
  } catch (e) {
    console.log(e);
  }
};

// 获取设备列表
const getClassList = async () => {
  try {
    const { data: res } = await getTaskDataClassList({
      T_task_id: queryData.T_task_id,
    });
    classList.value = res.Data || [];
  } catch (e) {
    console.log(e);
  }
};

// 模板标签数据（列表）
const getTemplateList = async () => {
  try {
    const { data: res } = await getVerifyTemplateMapDataList(queryData);
    formValue.formList = res.Data;
    formValue.formList.forEach((item) => {
      if (item.T_label === 3 || item.T_label === 9) {
        item.T_value = item.T_value ? item.T_value.split('|') : null;
      } else if (item.T_label === 12) {
        item.T_value = item.T_value
          ? [item.T_value.split('/')[0], item.T_value.split('/')[1]]
          : null;
      } else if (item.T_label === 13) {
        item.T_value = item.T_value
          ? [item.T_value.split('/')[0].split('|'), item.T_value.split('/')[1]]
          : null;
      } else {
        item.T_value = item.T_value ? item.T_value : null;
      }
    });
  } catch (e) {
    console.log(e);
  }
};

onBeforeUnmount(() => {
  // 取消订阅
  clearTimeout(timer);
});

// getClassList();
getTemplateList();
</script>

<style scoped></style>
