<style lang="scss" scoped>
.attach-container-left {
  display: flex;
  flex-direction: column;
  justify-items: flex-end;

  img {
    height: 45px;
  }
}

.attach-container-left-line {
  display: inline-flex;
  flex-wrap: nowrap;

  img {
    height: 20px;
  }
}
</style>
<template>
  <div class="attach-container">
    <el-tooltip placement="top" effect="light">
      <div :class="inline?'attach-container-left-line':'attach-container-left'">
        <template v-if="state.isImage">
          <img :src="u.fmt.fmtImg(state.uid)"/>
        </template>
        <template v-else><img :src="state.icon"/></template>

        <el-button text size="small" :title="state.name" @click="handlePreview">{{ state.name }}</el-button>
      </div>
      <div class="attache-container-right">
        <slot name="extraRight"></slot>
      </div>
      <template #content>
        <el-button-group>
          <el-button size="small" type="success" text v-if="downable&&!readonly" @click="handleDownload"> 下载</el-button>
          <el-button size="small" type="danger" text v-if="!readonly" @click="handleDelete"> 删除</el-button>
        </el-button-group>


      </template>
    </el-tooltip>
    <Preview ref="previewRef" :url="state.previewUrl" :name="state.name"/>
    <ExcelEditor ref="excelEditorRef" :url="state.previewUrl" :name="state.name" :uid="state.uid"/>
  </div>
</template>

<!--统一文件展示组件、预览、编辑、删除管理-->
<script setup lang="ts" name="Attach">
import {reactive, onMounted, ref, onBeforeUnmount, defineAsyncComponent, computed} from 'vue';
import u from "/@/utils/u";
import {$get} from "/@/utils/request";
import {Msg} from "/@/utils/message";


const Preview = defineAsyncComponent(() => import("/@/components/preview/Preview.vue"));
const ExcelEditor = defineAsyncComponent(() => import("/@/components/excel/ExcelEditor.vue"));
// const Luckysheet = defineAsyncComponent(() => import("/@/components/excel/Luckysheet.vue"));

// 定义父组件传过来的值
const props = defineProps({
  attach: {
    type: Object,
    default: () => {
      return {
        id: 0,
        uid: '',
        name: '',
        size: 0,
      }
    }
  },
  readonly: {
    type: Boolean,
    default: false
  },
  editable: {
    type: Boolean,
    default: false
  },
  downable: {
    type: Boolean,
    default: false
  },
  deletable: {
    type: Boolean,
    default: false
  },
  inline: {
    type: Boolean,
    default: false
  }
})

const edit = computed(() => {
  if (props.editable && props.attach) {
    props.attach.uid.toLowerCase().endsWith(".xlsx");
  }
  return false;
});

// const luckysheetRef = ref();
const excelEditorRef = ref();
const previewRef = ref();
// 定义子组件向父组件传值/事件
const emit = defineEmits(['on-preview', 'on-edit', 'on-download', 'on-delete']);

import {preview} from 'vue3-image-preview'


// 定义变量内容
const state = reactive({
  uid: '',
  icon: '',
  name: '',
  content: '',
  previewUrl: '',
  isImage: false,
  attachConf: [
    {
      suffix: ['jpg', 'jpeg', 'png', 'gif', 'svg'],
      icon: '@/assets/mime/jpg.svg'
    },
    {
      suffix: ["mp4", "ogg", "avi", "webm"],
      icon: '@/assets/mime/video.svg'
    },
    {
      suffix: ["mp3", "amr", "avi", "wav"],
      icon: '@/assets/mime/audio.svg'
    },
    {
      suffix: ["doc", "docx"],
      icon: '@/assets/mime/docx.svg'
    },
    {
      suffix: ["xls", "xlsx"],
      icon: '@/assets/mime/xlsx.svg'
    },
    {
      suffix: ["ppt", "pptx"],
      icon: '@/assets/mime/pptx.svg'
    },
    {
      suffix: ["pdf"],
      icon: '@/assets/mime/pdf.svg'
    },
    {
      suffix: ["txt", "log", "css"],
      icon: '@/assets/mime/txt.svg'
    },
    {
      suffix: ["zip", "rar", "7z", "gz", "xz", "tar"],
      icon: '@/assets/mime/rar.svg'
    },
    {
      suffix: ["html", "htm"],
      icon: '@/assets/mime/web.svg'
    },
    {
      suffix: ["java", "js", "php", "py", "sh", "bat"],
      icon: '@/assets/mime/bat.svg'
    },
  ]
});

// 页面销毁时
onBeforeUnmount(() => {
});

onMounted(() => {
  init();
})

const init = () => {
  console.log(props.attach)
  let {name, size, id, uid} = props.attach;
  if (name) {
    state.name = name;
  } else {
    if (uid) {
      state.name = uid;
    }
  }

  if (!uid) {
    throw new Error('文件不存在~');
  }
  state.uid = uid;
//文件类型判断
  let suffix = uid.substring(uid.lastIndexOf(".") + 1).toLowerCase();

  let conf = state.attachConf.find(k => k.suffix.includes(suffix));
  console.log(suffix, conf)
  if (conf) {
    state.icon = conf.icon;
  } else {
    state.icon = "@/assets/mime/other.svg"
  }

  if (state.attachConf[0].suffix.includes(suffix)) {
    state.isImage = true;
  }

}

const handlePreview = () => {
  if (state.isImage) {
    preview({images: u.fmt.fmtImg(state.uid)})
  } else {
    handleReady();
    previewRef.value.handlePreview();
  }

  emit('on-preview', state.uid)
}

const handleReady = async () => {
  //1.获取预览的key
  try {
    let key = await $get(`/preview/getKey/${state.uid}`);
    //2.打开预览页面
    state.previewUrl = `${u.url.preview}${key}`
    console.log(state.previewUrl)
  } catch (e) {
    Msg.message(`文件地址错误，请稍后再试`, 'error')
  }

  // .then((res: any) => {
  //    let key = res;
  //    //2.打开预览页面
  //    state.previewUrl = `${u.url.preview}${key}`
  //    console.log(state.previewUrl)
  //
  //  }).catch((e) => {
  //    console.error(e)
  //    Msg.message(`文件地址错误，请稍后再试`,'error')
  //  })
}

const handleDownload = () => {
  let url = u.fmt.fmtUrl(state.uid)
  window.open(url, '_blank')
  emit('on-download', state.uid)
}

const handleEdit = async () => {
  await handleReady();
  let suffix = state.name.substring(state.name.lastIndexOf(".")).toLowerCase();
  if (suffix.endsWith(".xlsx")) {
    excelEditorRef.value.handleEdit();
    // luckysheetRef.value.initLuckysheet()
  } else {
    Msg.message(`暂不支持该格式文件的在线编辑功能`)
  }
  emit('on-edit', state.uid)
}

const handleDelete = () => {
  emit('on-delete', state.uid)
}

defineExpose({
  handlePreview
});


</script>
