<template>
  <div class="body-head">
    <el-tooltip
      class="item"
      effect="dark"
      :content="`请上传${format}（支持obj/ply/las/osgb/b3dm格式的数据），大小在${size}以内 `"
      placement="bottom-start"
      ><el-upload
        class="upload-demo"
        :multiple="false"
        :accept="accept"
        :show-file-list="false"
        :http-request="() => {}"
        :file-list="fileList"
        :disabled="percentage || !operateIsPermissionByPath('sync')"
        :before-upload="uploadCheck"
      >
        <el-button v-pdpath="'sync'" type="primary">
          <el-icon><Upload /></el-icon>{{ percentage ? "文件上传中" : "上传数据" }}
        </el-button>
      </el-upload>
    </el-tooltip>
  </div>

  <el-table
    :data="pagging.state.table.rows"
    tooltip-effect="dark"
    style="width: 100%"
    size="large"
  >
    <el-table-column label="序号" width="70" v-slot:default="{ $index }">
      <div style="text-align: center">
        {{ pagging.state.pag.size * (pagging.state.pag.currentPage - 1) + $index + 1 }}
      </div>
    </el-table-column>
    <el-table-column label="标题" prop="modelTitle"></el-table-column>
    <el-table-column label="原始数据格式" prop="modelDateType"></el-table-column>
    <el-table-column label="大小" prop="modelSize"></el-table-column>
    <el-table-column label="上传时间" v-slot:default="{ row }: { row: ModelScene }">
      {{ getStatusText(row) }}
    </el-table-column>
    <el-table-column label="所属架构" prop="deptName"></el-table-column>
    <el-table-column label="操作" v-slot:default="{ row }">
      <span
        class="oper-span"
        v-pdpath="['edit']"
        @click="editHanlder(row)"
        v-if="row.createStatus === ModelSceneStatus.SUCCESS"
      >
        修改
      </span>
      <span
        class="oper-span"
        v-pdpath="['view']"
        @click="openSceneUrl(row, OpenType.query)"
        v-if="row.createStatus === ModelSceneStatus.SUCCESS"
      >
        查看
      </span>
      <span
        class="oper-span delBtn"
        v-pdscene="row"
        @click="delOrCancel(row)"
        v-pdpath="'del'"
      >
        {{ row.createStatus !== ModelSceneStatus.RUN ? "删除" : "取消上传" }}
      </span>
    </el-table-column>
  </el-table>

  <el-dialog
    :model-value="!!percentage"
    :show-close="false"
    title="文件上传中"
    :close-on-click-modal="false"
  >
    <el-progress :percentage="percentage" />
  </el-dialog>
</template>

<script setup lang="ts">
import {
  ModelSceneStatus,
  ModelScene,
  cancelUploadModelScene,
  uploadModelScene,
  delModelScene,
  getModelSceneStatus,
} from "@/store/scene";
import {
  ModelMaxSize,
  ModelSceneStatusDesc,
  ModelSupportFormats,
  SceneTypePaths,
} from "@/constant/scene";
import { confirm } from "@/helper/message";
import { useUpload } from "@/hook/upload";
import { ScenePagging } from "./pagging";
import { ElMessage, ElMessageBox } from "element-plus";
import { watchPolling } from "@/hook/watchPolling";
import { OpenType, openSceneUrl } from "../case/help";
import { operateIsPermissionByPath } from "@/directive/permission";
import { editModelScene } from "./quisk";

const props = defineProps<{ pagging: ScenePagging }>();

const getStatusText = (scene: ModelScene) => {
  let desc = ModelSceneStatusDesc[scene.createStatus];
  if (scene.createStatus === ModelSceneStatus.RUN && scene.progress) {
    desc += ` ${scene.progress}% `;
  } else if (scene.createStatus === ModelSceneStatus.SUCCESS) {
    desc = scene.createTime;
  }
  return desc;
};

const delOrCancel = async (scene: ModelScene) => {
  const isDel = scene.createStatus !== ModelSceneStatus.RUN;
  const msg = isDel ? "确定要删除此数据？" : "确定要取消上传吗？";
ElMessageBox.confirm(msg, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    isDel ? await delModelScene(scene) : await cancelUploadModelScene(scene);
    props.pagging.refresh();
  });
  // if (await confirm(msg)) {
  //   isDel ? await delModelScene(scene) : await cancelUploadModelScene(scene);
  //   props.pagging.refresh();
  // }
};

const editHanlder = async (scene: ModelScene) => {
  if (await editModelScene({ model: scene })) {
    props.pagging.refresh();
  }
};

const {
  percentage,
  upload: uploadCheck,
  fileList,
  size,
  format,
  removeFile,
  accept,
} = useUpload({
  maxSize: ModelMaxSize,
  formats: ModelSupportFormats,
  upload: async (file, onPercentage) => {
    try {
      await uploadModelScene(file, onPercentage);
      props.pagging.refresh();
    } catch {}
    removeFile();
  },
});

// 处理后台正在处理的模型类
const refreshStatus = (models: ModelScene[]) => {
  const refreshStatusAll = models.map(async (scene) => {
    const { status, progress } = await getModelSceneStatus(scene);
    scene.createStatus = status;
    scene.progress = progress;
    if (status == ModelSceneStatus.SUCCESS) {
      props.pagging.refresh();
    }
  });
  return Promise.all(refreshStatusAll);
};

watchPolling(() => {
  const payload = (props.pagging.state.table.rows as ModelScene[]).filter(
    (item) => item.createStatus === ModelSceneStatus.RUN
  );
  return { start: payload.length > 0, payload };
}, refreshStatus);
</script>
