<template>
  <el-container class="container">
    <el-aside class="data-tree">
      <div class="oper">
        <el-button type="primary" :icon="Refresh" @click="loadData">刷新</el-button>
        <el-button type="danger" :icon="Delete" @click="handleDelete">删除</el-button>
      </div>
      <div class="table">
        <el-table :data="fileDatas" style="width: 100%; height: 100%; border: 1px solid #dcdfe6;" highlight-current-row
          @selection-change="handleSelectionChange" stripe row-key="Id" @row-click="handleRowClick"
          ref="smartWellResultRef">
          <el-table-column type="selection" width="28" />
          <el-table-column prop="OutGraphicFile" label="文件名" width="*" show-overflow-tooltip>
            <template #default="scope">
              <el-link @click="handleOpenFile(scope.row)">
                <div :style="{ padding: '0' }">{{ scope.row.OutGraphicFile }}</div>
              </el-link>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="55" style="margin: 0;padding: 0;">
            <template #default="scope">
              <el-tooltip content="删除" placement="top">
                <el-button :icon="Delete" type="danger" size="small" circle @click="handelDeleteRow(scope.row)"
                  style="margin-right: 5px;padding: 0;" />
              </el-tooltip>
              <!-- <el-tooltip content="二次布井" placement="top">
                <el-button :icon="Switch" type="primary" size="small" circle @click="reCalc(scope.row)"
                  style="margin: 0;padding: 0;" />
              </el-tooltip> -->
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-aside>
    <el-main class="main">
      <WellRecommend :tokenKey="currentTokenKey" ref="wrRef" />
    </el-main>
    <LoadingDialog v-model="loading" ref="loadingRef" :timeout="3000" message="正在加载数据……" @timeout="onTimeout" />
  </el-container>
</template>
<script setup>
definePageMeta({
  requiresAuth: true
});
import { ref, onMounted } from 'vue'
import { Refresh, Delete } from "@element-plus/icons-vue";
import { getWellRecommendList, deleteWellRecommendRecords } from '~/services/wellRecommandService'
import { emitter } from "~/utils/eventBus";
import { ElMessageBox } from 'element-plus';
const { $toastMessage } = useNuxtApp();
import { generateGUID } from "~/utils/common";
import { STORAGE_KEYS } from "~/utils/storageKeys"
import { EMIT_COMMAND } from '~/utils/commandTypes';
// 当前页图件token的 key
const currentTokenKey = STORAGE_KEYS.WELL_RECOMMAND_TOKEN;
const openFileKey = STORAGE_KEYS.WELL_RECOMMAND_OPEN_FILE_ID;

const loading = ref(false);
const loadingRef = ref(null);

const smartWellResultRef = ref(null);

const selectedRows = ref([]);

// 打开的文件
const openFileItem = ref(null);

const fileDatas = ref(null);

const wrRef = ref(null);

const loadData = async (showLoading = false) => {
  try {
    if (showLoading) {
      loading.value = true;
    }
    selectedRows.value = [];
    const response = await getWellRecommendList();
    if (!response) {
      $toastMessage.error("获取井推荐列表失败");
      return;
    }
    fileDatas.value = response;
    await nextTick();
    const storageFileId = localStorage.getItem(openFileKey);
    if (storageFileId) {
      const storageFile = fileDatas.value.find(w => w.Id === storageFileId);
      if (storageFile) {
        // handleRowClick(openFileItem.value);
        handleOpenFile(storageFile);
        smartWellResultRef.value.toggleRowSelection(storageFile);
      }
    }
  } catch (error) {
    console.error('获取井推荐列表异常：', error);
    $toastMessage.error('获取井推荐列表失败！');
  } finally {
    closeLoading();
  }
};

// 获取选中项
const handleSelectionChange = (selection) => {
  selectedRows.value = selection;
}

const handleRowClick = (row) => {
  clearSelection();
  smartWellResultRef.value.toggleRowSelection(row, true);
}

const clearSelection = () => {
  // if (selectedRows.value) {
  //   selectedRows.value.forEach(item => {
  //     smartWellResultRef.value.toggleRowSelection(item, false);
  //   });
  // }
  smartWellResultRef.value.clearSelection()
  console.log("执行清空选择")
  // drawResults.value.toggleAllSelection(false);
  // drawResults.value.toggleAllSelection();
};

// 单行删除
const handelDeleteRow = async (item) => {
  selectedRows.value.push(item);
  await handleDelete();
}

// // 二次布井
// const reCalc = (item) => {
//   // 先打开文件
//   handleOpenFile(item);
//   emitter.emit("reCalc", item);
// }

// 删除数据
const handleDelete = async () => {
  if (selectedRows.value.length === 0) {
    $toastMessage.warning("请选择要删除的文件！");
    return;
  }

  ElMessageBox.confirm(`您确定要删除选中的数据吗?`, "删除确认", {
    confirmButtonText: "确认删除",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      const selectKeys = selectedRows.value.map(item => item.Id);

      try {
        if (selectKeys.some(item => item === openFileItem.value.Id)) {
          emitter.emit(EMIT_COMMAND.SOURCE_CHANGED);
        }
        const response = await deleteWellRecommendRecords(generateGUID(), selectKeys.join(','));
        if (response > 0) {
          await loadData();

          $toastMessage.success("删除数据成功！");
          selectedRows.value = [];
        } else {
          $toastMessage.error("删除失败！");
        }
      } catch (error) {
        $toastMessage.error("删除异常！");
        console.error("删除异常：", error);
      }
    })
    .catch(() => {
    });
};

// 打开文件操作（点击操作）
const handleOpenFile = (item) => {
  // console.log("打开文件:", item);
  openFileItem.value = item;
  emitter.emit(EMIT_COMMAND.CALC_PROPERTY, item);
  emitter.emit(EMIT_COMMAND.SOURCE_CHANGED);
  // emitter.emit(EMIT_COMMAND.EVT_TYPE, { type: EMIT_COMMAND.OPEN_FILE, cmdID: currentTokenKey, data: JSON.stringify({ fileName: item.OutGraphicFile }) });
  wrRef.value?.doOpenFile(item.OutGraphicFile);
  localStorage.setItem(openFileKey, item.Id);
};

onMounted(async () => {
  nextTick();
  await loadData();

  emitter.on(EMIT_COMMAND.REFRESH_RESULT, async () => {
    await loadData(false);
  });
});

onUnmounted(() => {
  emitter.off(EMIT_COMMAND.REFRESH_RESULT);
});

// 加载数据超时处理
const onTimeout = () => {
  $toastMessage.error("加载数据失败，请稍后重试！");
}

// 关闭加载窗口
const closeLoading = () => {
  if (loadingRef.value) {
    loadingRef.value.close();
  } else {
    loading.value = false;
  }
}
</script>
<style scoped>
.data-tree {
  width: 300px;
  /* height: calc(100vh - 55px); */
  height: 100%;
  border: none;
  overflow-y: auto;
}

.main {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}

.file-links {
  display: flex;
  list-style: none;
  gap: 0.1rem;
  flex-direction: column;
  overflow-y: auto;
  height: 100%;
  width: 100%;
  margin-top: 10px;
  padding-left: 10px;
}

.file-links a {
  text-decoration: none;
  color: #333;
  padding: 0.5rem;
  transition: color 0.3s;
}

.file-links a:hover {
  color: #42b983;
  cursor: pointer;
}

.file-links a.active {
  color: #42b983;
  border-bottom: 2px solid #42b983;
  font-weight: bold;
}

.oper {
  width: 100%;
  height: 40px;
  margin: 0;
  padding-left: 10px;
}

.table {
  width: 100%;
  height: 100%;
  overflow-y: auto;
}
</style>
