<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-button type="primary" @click="setCopy">复制</n-button>
          <n-button type="primary" @click="setPaste">粘贴</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: 40%"
    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
              :indicator-placement="'inside'"
              :status="
                keyInfo.Code === 600
                  ? 'default'
                  : keyInfo.Code === 601
                  ? 'success'
                  : 'error'
              "
              type="line"
              gap-position="bottom"
              :percentage="keyInfo.Schedule"
            />
          </div>
        </template>
        <div  class=" pis" style="overflow:auto;height:200px;" ref="scrollbarRef"
        >
         <div class="flex" v-for="(item, index) of items" :key="index"> <!-- items -->
            <n-badge class="mr-5" type="info" :value="index + 1" />
            <span>{{ item }}</span>
          </div>
        </div>
      </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,TempCopy
} 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 { nextTick, onBeforeUnmount, onUpdated } from 'vue';
import FormList from '@/components/FormList.vue';
import { useStore } from 'vuex';
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 store = useStore()
//复制
const setCopy = ()=>{
  message.success("复制成功")
  store.commit('setTaskId',queryData.T_task_id)  
 
}
//粘贴
const setPaste = async ()=>{
  console.log('粘贴',store.state.TaskId,queryData.T_task_id)
  if(store.state.TaskId==''){
    message.error('请先复制模板，在进行粘贴哦')
    return
  }
  const resIt = await TempCopy({
    T_copy_task_id: store.state.TaskId,
    T_paste_task_id: queryData.T_task_id,
    T_source:2
  })
  if(resIt.data.Code==200){
    message.success('粘贴成功') 
    getTemplateList()
  }
}
// 模态框数据源
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) => {
  console.log('提交',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(() => {
  if(keyInfo.value.Item){
    nextTick(()=>{
      scrollbarRef.value.scrollTop = scrollbarRef.value.scrollHeight
    })
    return keyInfo.value.Item.split('\n').filter((item) => item) 
  }else{
    return [];
  }
 

 
});


// 验证报告生成 获取生成结果
const generateKeyInfo = async (key) => {
  
  const { data: res } = await generateKey({
    key,
  });
  if (res.Code === 600) {
    timer = setTimeout(() => {
      generateKeyInfo(key);
    }, 3000);
  } else {
    clearTimeout(timer);
  }
  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);
  //  return
    const VerifyTemplateMapData = arr.map((item,i) => {
      
      if (item.T_label === 3) {
        console.log('等于3',item.T_value,item.T_label,i)
        return {
          T_VerifyTemplateMap_id: item.T_VerifyTemplateMap_id,
          T_value: item.T_value.length!=0?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 === 9) {
        console.log('等于9',item.T_value,item.T_label,i)
        return {
          T_VerifyTemplateMap_id: item.T_VerifyTemplateMap_id,
          T_value: item.T_value!=null?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) {
        console.log('等于12',item.T_value,item.T_label,i)
        if(item.T_value[0]==null && item.T_value[1]==null){
          return {
            T_VerifyTemplateMap_id: item.T_VerifyTemplateMap_id,
            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,
          };
        }else{
          if(item.T_value[0]!=null){
            return {
              T_VerifyTemplateMap_id: item.T_VerifyTemplateMap_id,
              T_value: `${item.T_value[0]}/${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[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 if (item.T_label === 13) {
        console.log('等于13',item.T_value,item.T_label,i)
        if(item.T_value[0]==null && item.T_value[1]==null){
          return {
            T_VerifyTemplateMap_id: item.T_VerifyTemplateMap_id,
            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,
          };
        }else{
          if(item.T_value[0]!=null){
            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[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 {
        console.log('等于其他',item.T_value,item.T_label,i)
        return {
          T_VerifyTemplateMap_id: item.T_VerifyTemplateMap_id,
          T_value: item.T_value!=null?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,
        };
      }
    });
    console.log('提交参数',VerifyTemplateMapData)
    // return
    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) {
        console.log('打印arr',i)
        if (i.T_label === 3 || i.T_label === 9) {          
          obj[i.T_name] = i.T_value!=null?i.T_value.join('|'):'';
        } else if (i.T_label === 12 ) {
          console.log('打印12',i.T_value)
          if(i.T_value[0]== null && i.T_value[1]==''){
            console.log('12',i.T_value)
            obj[i.T_name] = ''
          }else{
            if(i.T_value[0]==null && i.T_value[1]!=null){
              obj[i.T_name] = ''+ '/' + i.T_value[1]
            }else if(i.T_value[0]!=null && i.T_value[1]==null){
              obj[i.T_name] = i.T_value[0] + '/' + ''
            }else{
              obj[i.T_name] = i.T_value[0] + '/' + i.T_value[1]
            }
            console.log('打印arr22222',obj[i.T_name])
          }
        } else if (i.T_label === 13) {    
          console.log('等于时间',i.T_value[0]!=null , i.T_value[1]!=null)
          if(i.T_value[0]!=null && i.T_value[1]!=null){//两个都有值
            obj[i.T_name] = `${i.T_value[0].join('|')+'/'+i.T_value[1]}`;
          }else if(i.T_value[0]!=null && i.T_value[1]==null){//选择了时间-没文本
            obj[i.T_name] = `${i.T_value[0].join('|')+'/'}`;
          }else if(i.T_value[0]==null && i.T_value[1]!=null){
            obj[i.T_name] = `${'/'+i.T_value[1]}`;
          }else{//都没选
            obj[i.T_name] = ''
          }
        } 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);
    console.log('999999999999999',res)
    formValue.formList = res.Data;

    formValue.formList.forEach(item => {
      if (item.T_label === 3){
        if(item.T_value=='' || item.T_value==null){
          item.T_value = []
        }else{
          item.T_value = item.T_value.split('|')
        }
      }else if(item.T_label == 9){
        if(item.T_value=='' || item.T_value==null){
          item.T_value = null
        }else{
          item.T_value = item.T_value.split('|')
        }
      }else if (item.T_label === 12) {
        if(item.T_value=='' || item.T_value==null){
          item.T_value = [null,null]
        }else{
          if(item.T_value.split('/')[0]==""){
            item.T_value = [null, item.T_value.split('/')[1]]
          }else{
            item.T_value = [item.T_value.split('/')[0], item.T_value.split('/')[1]]
          }
         
        }
      } else if (item.T_label === 13) {
        console.log('=================================等于13',item)
        if(item.T_value=='' || item.T_value==null){
          item.T_value = [null,null]
        }else{
          if(item.T_value.split('/')[0]==""){//前面时间区间没选
            item.T_value = [null, item.T_value.split('/')[1]]
          }else{//前面时间区间已经选
            item.T_value = [item.T_value.split('/')[0].split('|'), item.T_value.split('/')[1]]
          }
        }
      } 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>
