<template>
  <com-head
    :options="options"
    v-model="currentTypeId"
    notContent
    v-if="options.length"
  />

  <div class="body-layer">
    <template v-if="currentTypeId === 2">
      <Photos :caseId="caseId" />
    </template>
    <template v-else-if="currentTypeId === 3">
      <Records :caseId="caseId" :title="caseInfoData.caseTitle" />
    </template>
    <template v-else-if="currentTypeId === 4">
      <Manifest :caseId="caseId" :title="caseInfoData.caseTitle" />
    </template>
    <template v-else>
      <div class="body-head">
        <h3 style="visibility: hidden">场景管理</h3>
        <div>
          <template v-if="isDraw">
            <el-button type="primary" @click="gotoDraw(BoardType.map, -1)">
              创建{{ BoardTypeDesc[BoardType.map] }}
            </el-button>
            <el-button type="primary" @click="gotoDraw(BoardType.scene, -1)">
              创建{{ BoardTypeDesc[BoardType.scene] }}
            </el-button>
          </template>
          <el-button type="primary" @click="addCaseFileHandler">
            上传
          </el-button>
        </div>
      </div>

      <el-table
        :data="files"
        tooltip-effect="dark"
        style="width: 100%"
        size="large"
      >
        <el-table-column label="序号" width="70" v-slot:default="{ $index }">
          <div style="text-align: center">
            {{ $index + 1 }}
          </div>
        </el-table-column>
        <el-table-column
          label="名称"
          v-slot:default="{ row }: { row: CaseFile }"
        >
          <span v-if="!inputCaseTitles.includes(row)">
            {{ row.filesTitle }}
            <el-icon class="edit-title" @click="inputCaseTitles.push(row)">
              <EditPen />
            </el-icon>
          </span>
          <template v-else>
            <ElInput
              v-model="row.filesTitle"
              placeholder="请输入文件名"
              focus
              :maxlength="50"
              style="width: 280px"
            >
              <template #append>
                <el-button type="primary" plain @click="updateFileTitle(row)">
                  确定
                </el-button>
              </template>
            </ElInput>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime"></el-table-column>
        <el-table-column
          label="操作"
          v-slot:default="{ row }: { row: CaseFile }"
        >
          <span class="oper-span" @click="query(row)"> 查看 </span>
          <span
            class="oper-span"
            @click="gotoDraw(row.imgType!, row.filesId)"
            v-if="row.imgType !== null"
          >
            编辑
          </span>
          <span class="oper-span delBtn" @click="del(row)"> 删除 </span>
        </el-table-column>
      </el-table>
    </template>
  </div>
</template>

<script setup lang="ts">
import comHead from "@/components/head/index.vue";
import { confirm } from "@/helper/message";
import { RouteName, router } from "@/router";
import { FileDrawType, BoardTypeDesc } from "@/constant/caseFile";
import { computed, onMounted, onUnmounted, ref, watchEffect } from "vue";
import { addCaseFile } from "./quisk";
import { title, desc } from "@/store/system";
import {
  CaseFile,
  CaseFileType,
  getCaseFileTypes,
  getCaseFiles,
  delCaseFile,
  BoardType,
} from "@/store/caseFile";
import { getCaseInfo, updateCaseInfo } from "@/store/case";
import { appConstant } from "@/app";
import { ElIcon, ElInput, ElMessage } from "element-plus";
import Photos from "./photos/index.vue";
import Records from "./records/index.vue";
import Manifest from "./records/manifest.vue";

const caseId = computed(() => {
  const caseId = router.currentRoute.value.params.caseId;
  if (caseId) {
    return Number(caseId);
  }
});
const caseInfoData = ref<any>();

const inputCaseTitles = ref<CaseFile[]>([]);

const updateFileTitle = async (caseFile: CaseFile) => {
  if (!caseFile.filesTitle.trim()) {
    return ElMessage.error("卷宗标题不能为空！");
  }
  await updateCaseInfo(caseFile);
  inputCaseTitles.value = inputCaseTitles.value.filter(
    (item) => item !== caseFile
  );
};

const currentTypeId = ref<number>();
const types = ref<CaseFileType[]>([]);
const options = computed(() =>
  types.value.map((item) => ({
    name: item.filesTypeName,
    value: item.filesTypeId,
  }))
);
const isDraw = computed(() => currentTypeId.value === FileDrawType);

const files = ref<CaseFile[]>([]);
const refresh = async () => {
  files.value = await getCaseFiles({
    caseId: caseId.value!,
    filesTypeId: currentTypeId.value,
  });
};
watchEffect(() => caseId.value && currentTypeId.value && refresh());

const query = (file: CaseFile) => {
  const ext = file.filesUrl
    .substring(file.filesUrl.lastIndexOf("."))
    .toLocaleLowerCase();
  if ([".raw", ".dcm"].includes(ext)) {
    window.open(
      `/xfile-viewer/index.html?file=${file.filesUrl}&name=${file.filesTitle}&time=` +
        Date.now()
    );
  } else {
    window.open(file.filesUrl + "?time=" + Date.now());
  }
};
const del = async (file: CaseFile) => {
  if (await confirm("确定要删除此数据？")) {
    await delCaseFile({ caseId: caseId.value!, filesId: file.filesId });
    refresh();
  }
};

const addCaseFileHandler = async () => {
  await addCaseFile({ caseId: caseId.value!, fileType: currentTypeId.value! });
  refresh();
};

const gotoDraw = (type: BoardType, id: number) => {
  router.push({
    name: RouteName.drawCaseFile,
    params: { caseId: caseId.value!, type, id },
  });
};

onMounted(async () => {
  try {
    types.value = await getCaseFileTypes();
    currentTypeId.value = types.value[0].filesTypeId;
    const caseInfo = await getCaseInfo(caseId.value!);
    if (caseInfo) {
      caseInfoData.value = caseInfo;
      title.value =
        (await getCaseInfo(caseId.value!)).caseTitle + " | 卷宗管理";
      desc.value = "";
    } else {
      console.error("该案件不存在！");
      throw "该案件不存在！";
      // router.replace({ name: RouteName.noCase });
    }
  } catch (error) {
    console.error("该案件不存在！");
    router.replace({ name: RouteName.noCase });
  }
});

onUnmounted(() => {
  title.value = appConstant.title;
  desc.value = appConstant.desc;
});
</script>

<style scoped lang="scss">
.edit-title {
  cursor: pointer;
  margin-left: 10px;
}
</style>
