<template>
  <div>
    <Dialog v-model="diaVisible" diaTitle="文件预览" width="70%" height="90%" @close="closeFun">
      <template v-if="diaVisible && fileId">
        <div v-if="modeType === 'csv'" class="content">
          <CsvView :fileId="fileId" :row="csvData" />
        </div>
        <div v-if="modeType === 'kkFile'" class="content">
          <KkfileView :fileId="fileId" />
        </div>
        <div v-if="modeType === 'onlyOffice'" class="content">
          <iframe
            class="iframe"
            :src="`${env.VITE_API_SPDM_URL}/onlyOffice?fileId=${fileId}&fileData=${fileData}&fileKey=${fileKey}&userId=${userId}&tenantId=${tenantId}&token=${token}`"
          />
        </div>
      </template>
    </Dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import { downloadFileForEditApi, getFileBaseInfoApi } from '@/api/data/data';
import { listSimulationKeyResultApi } from '@/api/project/run';
import { getUserId } from '@/utils/user';
import Dialog from '@/components/common/dialog/index.vue';
import KkfileView from './kkfileView.vue';
import CsvView from './csvView.vue';
import { parsePermission } from '@/utils/permission';
import { isAcceptFileType } from '@/utils/file';
import { enableConfigByTenant, TENANT_ENUM } from '@/tenants/tenant';

interface Props {
  modelValue: boolean;
  fileId: any;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  fileId: 0,
});

const env = import.meta.env;
const diaVisible = ref(false);
const fileData = ref<any>('');
const fileKey = ref('fileKey');
const csvData = ref<any>({});
const userId = ref(localStorage.getItem('USER_ID'));
const token = ref(localStorage.getItem('TOKEN'));
const tenantId = ref(localStorage.getItem('TENANT_ID'));
const modeType = ref(''); // csv kkFile onlyOffice

const emit = defineEmits(['update:modelValue']);

watch(
  () => props.modelValue,
  (val: boolean) => {
    if (val) {
      initFun();
    } else {
      diaVisible.value = false;
    }
  }
);

const initFun = () => {
  if (!props.fileId) {
    return;
  }
  const params = {
    fileId: props.fileId,
  };
  getFileBaseInfoApi(params).then((res: any) => {
    if (res.code === 200) {
      const { originalName, permissionValue } = res.data;
      if (originalName.toLowerCase().endsWith('.csv')) {
        getCsvDataFun();
        modeType.value = 'csv';
        return;
      }
      if (enableConfigByTenant([TENANT_ENUM.LYRIC])) {
        modeType.value = 'kkFile';
        diaVisible.value = true;
        return;
      }
      if (parsePermission(permissionValue).write && isAcceptFileType(originalName, 'onlyOffice')) {
        modeType.value = 'onlyOffice';
        getOnlyOfficeFun();
      } else {
        modeType.value = 'kkFile';
        diaVisible.value = true;
      }
    }
  });
};

const getCsvDataFun = () => {
  const params = {
    fileId: props.fileId,
    current: 1,
    size: 1,
  };
  listSimulationKeyResultApi(params).then((res: any) => {
    if (res.code === 200) {
      csvData.value = res.data?.data[0] || {};
      diaVisible.value = true;
    }
  });
};

const getOnlyOfficeFun = () => {
  const params = {
    fileId: props.fileId,
  };
  downloadFileForEditApi(params).then((res: any) => {
    if (res.code === 200) {
      fileData.value = JSON.stringify(res.data);
      fileKey.value = `${props.fileId}_${getUserId()}`;
      diaVisible.value = true;
    }
  });
};

const closeFun = () => {
  emit('update:modelValue', false);
};
</script>

<style lang="scss" scoped>
.content {
  width: 100%;
  height: calc(100% - 5px);
  .iframe {
    width: 100%;
    height: 100%;
  }
}
</style>
