<template>
  <RenderWidget />
</template>

<script setup lang="tsx" name="LjFilePreview">
import { ref, onMounted, nextTick, computed, inject, watch } from "vue";
import { GetCacheFile } from "@/api/modules/common";
import LjDialog from "@/components/LjDialog/index.vue";
import type { FileData } from "@/typings/business";
import { isArray } from "@/utils/is";
import PreviewImage from "./compontents/PreviewImage.vue";
import PreviewFile from "./compontents/PreviewFile.vue";
import { getBase64Type } from "@/utils/index";
import { cloneDeep } from "lodash-es";

interface LjFileProps {
  /**
   * @description 抽屉基础属性
   */
  drawerProp?: any;
  /**
   * @description 文件数据
   */
  files: FileData | FileData[];
  /**
   * @description 初始预览图像索引，小于 url-list 的长度
   */
  initialIndex?: number;
  // switch?: (data: any) => void;
}

// interface FileParams {
//   /**
//    * @description 附件类型id
//    */
//   billtype: number;
//   classid?: number;
//   relid?: number;
//   relidmx?: number;
//   scid?: number | undefined;
//   relcode?: string | undefined;
// }

const props = withDefaults(defineProps<LjFileProps>(), {
  // drawerProp: {
  //   width: "80%",
  //   "destroy-on-close": true
  // }
});

const emit = defineEmits(["update:files", "closed"]);

// /**
//  * @description 抽屉默认属性
//  */
// const drawerDefineProp = {
//   draggable: true,
//   overflow: true,
//   modalClass: "lj-file-dialog"
// };

const currentIndex = ref(0);
const getIfImage = (index: number) => {
  return getBase64Type(fileList.value[index]?.fileType).indexOf(":image/") > -1;
};

const fileList = ref<FileData[]>([]);
const active = ref(false);
const PreviewFileRef = ref();
const PreviewImageRef = ref();

watch(
  () => props.files,
  newVal => {
    console.log("watch files newVal :>> ", newVal);
    currentIndex.value = props.initialIndex ?? 0;
    let _val = cloneDeep(newVal);
    if (isArray(newVal)) {
      fileList.value = _val;
    } else {
      fileList.value = [_val];
    }
  },
  {
    immediate: true,
    deep: true
  }
);

watch(
  () => props.initialIndex,
  newVal => {
    console.log("watch initialIndex newVal :>> ", newVal);
    currentIndex.value = newVal ?? 0;
  },
  {
    immediate: true
  }
);

// /**
//  * @description Base64转Blob
//  * @param b64Data
//  * @param contentType
//  * @param sliceSize
//  */
// const b64toBlob = (b64Data: any, contentType: any, sliceSize: any) => {
//   let b = b64Data.toString();

//   b64Data = b.split(",")[1];
//   console.log("b64Data :>> ", b64Data);

//   let byteCharacters = atob(b64Data);

//   let byteArrays = [];

//   for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
//     let slice = byteCharacters.slice(offset, offset + sliceSize);

//     let byteNumbers = new Array(slice.length);

//     for (let i = 0; i < slice.length; i++) {
//       byteNumbers[i] = slice.charCodeAt(i);
//     }

//     let byteArray = new Uint8Array(byteNumbers);

//     byteArrays.push(byteArray);
//   }
//   console.log("byteArrays :>> ", byteArrays);

//   let blob = new Blob(byteArrays, { type: contentType });

//   return blob;
// };

/**
 * @description 获取文件数据
 * @param md5Str md5
 */
const getData = async (md5Str: string, index: number) => {
  let _last = getIfImage(currentIndex.value);
  currentIndex.value = index;
  let _now = getIfImage(currentIndex.value);
  let res = fileList.value[index].fileData;
  if (!res) {
    let params = { filemd5: md5Str };
    res = await GetCacheFile(params);
    fileList.value[index].fileData = getBase64Type(fileList.value[index].fileType) + res.filedata;
  }
  console.log("ifImage.value _now _last:>> ", index, _now, _last);
  if (_now) {
    // 当前是image
    if (_last) {
      // 上一次也是image
      return fileList.value[index].fileData;
    } else {
      // 上一次是file
      nextTick(() => {
        console.log("1PreviewImageRef.value :>> ", PreviewImageRef.value);
        PreviewImageRef.value && PreviewImageRef.value.switchImage(index);
      });
      return false;
    }
  } else {
    // 当前是file
    if (_last) {
      // // 上一次也是image
      nextTick(() => {
        PreviewFileRef.value && PreviewFileRef.value.show();
      });
      return false;
    } else {
      // 上一次是file
      return fileList.value[index].fileData;
    }
  }
};

const show = () => {
  active.value = true;

  nextTick(() => {
    let _now = getIfImage(currentIndex.value);
    console.log("show-widget ,ifImage.value :>> ", show, _now);
    // let _type = "";
    // if (isArray(props.files)) {
    //   _type = getBase64Type(props.files[0].fileType);
    // } else {
    //   _type = getBase64Type(props.files.fileType);
    // }
    // if (_type.indexOf(":image") > -1) {
    if (_now) {
    } else {
      PreviewFileRef.value.show();
    }
  });
};

const autoClosed = () => {
  active.value = false;
  console.log("autoClosed :>> ", active.value);
  emit("closed");
};

/**
 * *************************************************************************
 * @description 主入口
 */
const RenderWidget = () => {
  let _type = "";
  if (!props.files || (isArray(props.files) && props.files.length === 0))
    return (
      <>
        <div></div>
      </>
    );
  // if (isArray(props.files)) {
  //   _type = getBase64Type(props.files[0].fileType);
  // } else {
  //   _type = getBase64Type(props.files.fileType);
  // }

  // if (_type.indexOf(":image") > -1) {
  //   return (
  //     <>
  //       {active.value && (
  //         <PreviewImage files={fileList.value} initialIndex={props.initialIndex} updated={getData} closed={autoClosed} />
  //       )}
  //     </>
  //   );
  // } else {
  //   return <>{active.value && <PreviewFile ref={PreviewFileRef} files={fileList.value} drawerProp={props.drawerProp} />}</>;
  // }

  console.log("RenderWidget ifImage.value :>> ", getIfImage(currentIndex.value), currentIndex.value);
  console.log("fileList.value :>> ", fileList.value);

  return (
    <>
      {active.value &&
        (getIfImage(currentIndex.value) ? (
          <PreviewImage
            ref={PreviewImageRef}
            files={fileList.value}
            initialIndex={currentIndex.value}
            updated={getData}
            closed={autoClosed}
          />
        ) : (
          <PreviewFile
            ref={PreviewFileRef}
            files={fileList.value}
            initialIndex={currentIndex.value}
            drawerProp={props.drawerProp}
            updated={getData}
          />
        ))}
    </>
  );
};

defineExpose({
  show
});
</script>

<style lang="scss"></style>
