<template>
  <div>
    <div class="btnBox">
      <div @click="checkNow">
        <img :src="addPng" alt="" />
        <span>新的比对</span>
      </div>
      <div @click="reloadCheck">
        <img :src="againPng" alt="" />
        <span>重新比对</span>
      </div>
      <div @click="excelPort">
        <img :src="dervicePng" alt="" />
        <span>导出所有结果</span>
      </div>
    </div>
    <div class="tableBox">
      <el-table
        ref="multipleTableRef"
        :data="tableList"
        style="width: 100%; height: calc(100vh - 320px)"
        stripe
        @selection-change="handleSelectionChange"
        @select-all="chooseAll"
        :header-cell-style="{
          background: '#F7F8FB !important',
          color: '#7484AB',
          borderBottom: '1px solid #A3ADE0 !important',
          fontWeight: '400',
        }"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          label="对比scd"
          width="190"
          :show-overflow-tooltip="true"
        >
          <template #default="scope">{{ scope.row.name }}</template>
        </el-table-column>
        <el-table-column
          property="CREATED_TIME"
          label="时间"
          width="auto"
          :show-overflow-tooltip="true"
        />
        <el-table-column fixed="right" label="操作" width="120">
          <template #default="scope">
            <el-button
              link
              type="primary"
              size="small"
              @click="searchScdCheck(scope.row)"
              ><el-icon> <View /> </el-icon>查看</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- <div>新的对比
      <LookScd
        v-if="lookScdModal"
        :lookScdModal="lookScdModal"
        :aktType="aktType"
        @lookScdBack="lookScdBack"
      >
      </LookScd>
    </div> -->
    <!-- 新的对比弹窗 -->
    <el-dialog
      @close="cancelClick"
      v-model="lookScdModal"
      width="30vw"
      style="height: 400px"
      append-to-body
      draggable
    >
      <template #header>
        <div class="my-header">
          <div class="title">请选择对比的SCD文件</div>
        </div>
      </template>
      <div
        class="uploda-file"
        v-loading="loadingAdd"
        element-loading-text="上传文件中..."
      >
        <span class="file-title">选择文件</span>
        <el-input
          v-model="chooseFile"
          class="w-50 m-2"
          placeholder="点击右侧按钮上传文件"
          clearable
          @clear="clearFile"
        >
          <template #suffix>
            <img
              v-if="chooseFile"
              :src="uploadSPng"
              alt=""
              style="width: 20px; height: 20px"
            />
            <img
              v-if="loadingAddError"
              :src="uploadEPng"
              alt=""
              style="width: 20px; height: 20px"
            />
          </template>
        </el-input>
        <el-upload
          v-model:file-list="fileList"
          :limit="1"
          class="upload-demo"
          :http-request="uploadFile"
          :on-exceed="exceed"
          :show-file-list="false"
        >
          <template #trigger>
            <div class="upload-title">
              <img :src="uploadPng" alt="" />
              <span>上传文件</span>
            </div>
          </template>
        </el-upload>
      </div>
      <div class="sure-file">
        <div v-if="!isAnalysis && AnalysisProcess" class="analysis success">
          文件解析完成
        </div>
        <div v-else-if="isAnalysis && AnalysisProcess" class="analysis fail">
          文件解析失败
        </div>
        <div v-if="chooseFile && !AnalysisProcess" class="analysis">
          文件正在解析中,请等待...
        </div>
        <!-- <div
          class="sures"
          :class="{ 'sures-success': !isAnalysis && AnalysisProcess }"
        >
          确认上传
        </div> -->

        <div
          class="sures sures-success"
          v-if="!isAnalysis && AnalysisProcess"
          @click="yesAnalysisClick"
        >
          开始对比
        </div>
        <div class="sures" v-else @click="noAnalysisClick">开始对比</div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  ref,
  onMounted,
  toRefs,
  watch,
  nextTick,
  defineEmits,
  onUnmounted,
} from "vue";
import scdCheck from "@/api/scdCheck/scdCheck";
import {
  uploadfile,
  tmpParse,
  compStart,
  compstatView,
} from "@/api/scdCheck/scdCheck2";
import scd from "@/api/scd";
import systemRow from "@/api/systemRow";
import {
  ElMessage,
  ElLoading,
  ElMessageBox,
  ElNotification,
} from "element-plus";
import LookScd from "../modalCom/LookScd.vue";
import dervicePng from "@/assets/image/scdcheck/derive.png";
import againPng from "@/assets/image/scdcheck/again.png";
import addPng from "@/assets/image/scdcheck/add.png";
import uploadPng from "@/assets/image/scdcheck/upload.png";
import uploadSPng from "@/assets/image/scdcheck/upload_success.png";
import uploadEPng from "@/assets/image/scdcheck/upload_error.png";

import { useRoute } from "vue-router";
import createds from "@/utils/scdMqtt.js";
const route = useRoute();
const emit = defineEmits(["scdTreeBack","scdView","scdJpadList"]);
let tableList = ref([]);
let multipleTableRef = ref();
let alreadyTriggered = ref(false);
let scdid = ref([]);
const loading = ref(false);
let lookScdArr = ref([]);
let lookScdModal = ref(false);
const fileList = ref([]); //上传的文件
const loadingAdd = ref(false); //文件上传的加载状态
const loadingAddError = ref(false); //文件上传的加载状态
const chooseFile = ref("");
const handleSelectionChange = (e) => {
  //复选
};
const chooseAll = (e) => {
  //全选
};
const checkNow = (e) => {
  //scd比对
  lookScdModal.value = true;
};
const excelPort = () => {
  //导出excel
  systemRow
    .portExcel({
      code: "scd-comp-result",
    })
    .then((res) => {
      if (res.data) {
        return;
      } else {
        ElMessage({
          message: res.msg,
          type: "info",
        });
      }
    });
};
const reloadCheck = () => {
  //重新比对
  checkNow();
};
const exceed = (files) => {
  if (fileList.value.length > 0) {
    ElMessage({
      type: "warning",
      message: "请清除选择文件后重新选择!",
    });
  }
};
const uploadFile = async (e) => {
  fileList.value = [];
  chooseFile.value = "";
  loadingAddError.value = false;
  loadingAdd.value = true;
  const fileRes = await uploadfile({
    file: e.file,
    station_id: route.query.stationId,
    is_checkin: 0,
    data_type: "a_scd",
  });
  if (fileRes.code == 0) {
    fileList.value.push(fileRes.data);
    chooseFile.value = fileRes.data.filename;
    loadingAdd.value = false;
    ElMessage({
      type: "success",
      message: "上传成功!",
    });
    const resParse = await tmpParse({
      station_id: route.query.stationId,
      scd_name: fileRes.data.filename,
      scd_path: fileRes.data.path,
    });
    startMqtt(`/jujutong/scd_check_tools/parse/#`);
  } else {
    loadingAdd.value = false;
    loadingAddError.value = true;
    ElMessage({
      type: "error",
      message: "上传失败!",
    });
  }
};
  //查看scd对比
  let data = {};
const searchScdCheck = async (row) => {
  data = {}
  data = row;
  emit('scdView',data)
  const loading = ElLoading.service({
    lock: true,
    text: "正在查询数据",
    background: "rgba(0, 0, 0, 0.7)",
  });
  const res = await compstatView({
    comp_id: row.id,
  });
  if (res.code == 0) {
    emit('scdJpadList',res.data)
    loading.close();
  }
};
const lookScdBack = (data, row) => {
  //选择scd文件模态框返回数据
  lookScdModal.value = data;
  lookScdArr.value = row;
  emit("scdTreeBack", lookScdArr.value);
};
const aktType = () => {
  //初始化数据
  scdCheck
    .flashStationDui({ station_id: route.query.stationId })
    .then((res) => {
      //获取差异纪录列表
      tableList.value = res.data;
    });
};
// mqtt=======
const PublicMqtt = ref(null);
const mesg = ref(null); //订阅成功的消息
const isAnalysis = ref(false); //解析是否成功
const AnalysisProcess = ref(false); //解析是否完成
const startMqtt = (val) => {
  //val = 订阅地址
  //设置订阅地址
  PublicMqtt.value = new createds(val);
  //初始化mqtt
  PublicMqtt.value.init();
  //链接mqtt
  PublicMqtt.value.link();
  getMessage();
};
//获取订阅数据
const getMessage = () => {
  PublicMqtt.value.client.on("message", (topic, message) => {
    // topic包含error就表示解析错误，message此时就是错误信息
    AnalysisProcess.value = true;
    mesg.value = JSON.parse(message.toString());
    if (topic.includes("error")) {
      isAnalysis.value = true;
      ElMessage({
        type: "error",
        message: mesg.value,
      });
    } else {
      isAnalysis.value = false;
    }
    console.log(mesg.value, "返回的数据", topic);
  });
};
//取消MQTT订阅
const unsubscribe = () => {
  //如果页面并没有初始化MQTT，无需取消订阅
  if (PublicMqtt.value) {
    PublicMqtt.unsubscribes();
  }
};
onUnmounted(() => {
  //页面销毁结束订阅
  if (PublicMqtt.value) {
    PublicMqtt.value.unsubscribes();
    PublicMqtt.value.over();
  }
});
// mqtt=======
// 取消弹窗
const cancelClick = () => {
  loadingAddError.value = false;
  loadingAdd.value = false;
};
//点击输入框中的清除按钮
const clearFile = () => {
  fileList.value = [];
};
watch(
  () => chooseFile.value,
  (newValue) => {
    if (!newValue) {
      fileList.value = [];
    }
  }
);
//解析完成开始对比的点击
const yesAnalysisClick = () => {
  ElMessageBox.confirm(
    "该操作耗时较长，校验开始后将清除原有校验结果且无法中止,确定开始吗?",
    "Warning",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(async () => {
      ElNotification({
        title: "信息",
        message: "正在进行SCD的一致性比对...请稍候",
        duration: 0,
      });
      const anRes = await compStart({
        type: "SCD",
        station_id: route.query.stationId,
        source_scd_id: route.query.id,
        target_scd_id: mesg.value.rootid,
        comp_id: 0,
      });
      if (anRes.code == 0) {
        ElNotification.closeAll();
        loadingAdd.value = false;
        aktType();
        ElMessage({
          type: "success",
          message: "对比完成!",
        });
      }
    })
    .catch((err) => {
    });
};
//解析失败活未完成开始对比的点击
const noAnalysisClick = () => {
  ElMessage({
    type: "warning",
    message: "请上传文件并等待文件解析完成!",
  });
};
const parentData = ref(null);
onMounted(() => {
  parentData.value = JSON.parse(route.query.parentData);
  aktType();
});
</script>

<style scoped lang="scss">
.btnBox > div,
.upload-title {
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 8px;
  cursor: pointer;
  background: url("~@/assets/image/scdcheck/bgscd.png") no-repeat center;
  border-radius: 2px;
  font-size: 14px;
  color: #255ce7;
  img {
    width: 20px;
    height: 20px;
    margin: 0 4px 0 0;
  }
}
.upload-title {
  width: 102px;
  background-size: 103px 50px;
  margin-top: 4px;
}
.btnBox {
  display: flex;
  margin-bottom: 12px;

  & > div:first-child,
  & > div:nth-child(2) {
    width: 102px;
    background-size: 102px 45px;
  }
  & > div:last-child {
    width: 128px;
    background-size: 128px 45px;
  }
}
.my-header {
  border-bottom: 1px solid #a3ade0;
  font-size: 16px;
  color: #1a2447;
  .title {
    padding-bottom: 15px;
  }
}
.uploda-file {
  display: flex;
  align-items: center;
}
.upload-demo {
  display: flex;
}
.sure-file {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.sures {
  background: #dfe8ff;
  margin-left: 60px;
  color: #fff;
  width: 124px;
  height: 32px;
  margin-top: 60px;
  line-height: 32px;
  text-align: center;
  cursor: pointer;
}
.sures-success {
  background: #255ce7;
}
.sureUpload {
}
.file-title {
  width: 90px;
  color: #1a2447;
  font-size: 14px;
  margin-right: 8px;
}
:deep(.el-input__wrapper) {
  height: 38px;
  border: 1px solid #a3ade0;
}
.analysis {
  margin-left: 67px;
  margin-top: 10px;
  color: #255ce7;
}
.analysis.success {
  color: #3be078;
}
.analysis.fail {
  color: #e50505;
}
:deep(.el-message-box) {
  vertical-align: inherit !important;
}
</style>