<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-scrollbar>
  </div>
  <n-modal style="width: 60%" v-model:show="modal.showModal" :show-icon="false" preset="dialog" :title="modal.title" @close="onCloseModal">
    <n-upload 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="line" gap-position="bottom" :percentage="keyInfo.Schedule" />
          </div>
          
        </template>
        <div class=" pis" v-show="loadingFun==false" style="overflow:auto;height:400px;" 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-spin v-show="loadingFun==true" :show="true">
            <n-alert title="请等待..." type="success">
              服务器正在处理中，请等待...
            </n-alert>
          </n-spin>
      </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,
  generateScheme,
  generateKey,
  TempCopy
} from '@/api';
import * as qiniu from 'qiniu-js';
import { getToken } from '@/utils/storage/sessionToken';
import { getFileToken } from '@/common';
import { NButton, useMessage } from 'naive-ui';
import { useWindowSize } from '@vueuse/core';
import { onBeforeUnmount } from 'vue';
import FormList from '@/components/FormList.vue';
import { useStore } from 'vuex';

const { height } = useWindowSize();

const message = useMessage();
const loadingFun = ref(false)
const scrollbarRef = ref(null);

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

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

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

//
const classList = ref([]);

// 模态框数据源
const modal = reactive({
  showModal: false,
  title: '',
});
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: 1
  })
  if (resIt.data.Code == 200) {
    message.success('粘贴成功')
    getTemplateList()
  }
}

/**
 * 上传文件
 * @param file
 * @returns {Promise<void>}
 */
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_pdf1: formValue.pdf,
    });
    if (res.Code === 200) {
      message.success(res.Msg);
      modal.showModal = false;
    }
  } catch (e) {
    console.log(e);
  }
};
const obsData = reactive({
  obj: {}
})
// 验证报告生成 方案
const generateSchemeInfo = async (obj) => {
  obsData.obj = obj
  var times = null
  const { data: res } = await generateScheme({
    T_task_id: task.T_task_id,
    T_VerifyTemplate_id: task.T_VerifyTemplate_id,
    ...obj,
  });
  if (res.Code === 200) {
    loadingFun.value = false
    generateKeyInfo(res.Data);
  } else if (res.Code == 501) {
    loadingFun.value = true
    times = setTimeout(() => {
      generateSchemeInfo(obsData.obj);
    }, 1000);
  } else {
    loadingFun.value = true
    clearTimeout(times);
  }
};

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);
  }
  scrollbarRef.value.scrollTo({
    top: 9999,
    behavior: 'smooth',
  });
  keyInfo.value = res;
};

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

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

/**
 * 生成报告
 * @returns {Promise<void>}
 */
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 = {};
      console.log('打印arr', arr)
      for (let i of arr) {
        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) {
          if (i.T_value[0] != null && i.T_value[1] != null) {
            obj[i.T_name] = ''
          } else {
            obj[i.T_name] = `${i.T_value[0] == null ? '' : i.T_value[0].join('|') + '/' + i.T_value[1] == null ? '' : i.T_value[1]}`;
          }
        } else {
          obj[i.T_name] = i.T_value;
        }
      }

      modal.title = '生成报告';
      modal.showModal = true;
      generateSchemeInfo(obj);
    }
  } catch (e) {
    console.log(e);
  }
};

/**
 * 获取设备列表
 * @returns {Promise<void>}
 */
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);
  }
};

/**
 * 模板标签数据（列表）
 * @returns {Promise<void>}
 */
// 获取模板标签数据（列表）
const getTemplateList = async () => {
  try {
    const { data: res } = await getVerifyTemplateMapDataList(queryData);
    console.log('999999999999999', res)
    // return
    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) {
        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>
