<template>
  <div>
    <el-button plain @click="open">上传视频文件</el-button>
    <el-button plain @click="$refs.file.click()">选择dicom文件</el-button>
    <input
      ref="file"
      type="file"
      name="file"
      webkitdirectory
      multiple
      @change="beginScanFiles($event)"
    />
    <div>
      <canvas id="img"></canvas>
    </div>
    <el-dialog title="上传视频" :close-on-click-modal="false" :visible.sync="IsOpen" width="450px" append-to-body>
      <my-videos @uploadOver="uploadOver" />
    </el-dialog>
  </div>
</template>

<script>
import MyVideos from '@/components/videos'
import * as cornerstoneWADOImageLoader from 'cornerstone-wado-image-loader'
// import charLS from '@cornerstonejs/codec-charls';
import * as cornerstone from 'cornerstone-core'
import dicomParser from "dicom-parser";
import { Anonymizer } from "dicomedit";
console.log(Anonymizer)
const script = `version "6.3"
temp := "chany"
(0008,0008) := "test"
(0010,0010) := temp
`;

const CharLs = require('@cornerstonejs/codec-charls')
const codecWrapper = {
  codec: undefined,
  Decoder: undefined,
  Encoder: undefined,
  encoderName: "JpegLSEncoder",
  decoderName: "JpegLSDecoder",
};
function setCodec(codecConfig, encoderName, decoderName, codec = {}) {
  codecConfig.Encoder = codec[encoderName];
  codecConfig.Decoder = codec[decoderName];
  codecConfig.codec = codec;
}
CharLs().then(res => {
  setCodec(codecWrapper, codecWrapper.encoderName, codecWrapper.decoderName, res);
})
export default {
  components: { MyVideos },
  data() {
    return {
      IsOpen: false,
      videoUrl: null,
      videoName: null
    }
  },
  methods: {
    async upload(name, file) {
      let res = await this.OSSclient.put(name, file)
      return res
    },
    beginScanFiles(e) {
      var files = e.target.files
      console.log(e.target.files)
      if (files.length > 0) {
        files.forEach(async (item, index) => {
          const reader = new FileReader();
          reader.onload = async (event) => {
            let buffer = event.target.result;
            const anonymizer = new Anonymizer(script, { test: 'hello' });
            anonymizer.loadDcm(new Uint8Array(buffer))
            await anonymizer.applyRules();
            let buffer1 = anonymizer.write()
            let data1 = dicomParser.parseDicom(new Uint8Array(buffer1))
            let data = dicomParser.parseDicom(new Uint8Array(buffer))
            // 传输语法 0002 0010
            // if(1.2.840.10008.1.2.1) 才压缩 => 1.2.840.10008.1.2.4.80
            let height = data.uint16('x00280011')
            let width = data.uint16('x00280010')
            let bitsPerSample = data.uint16('x00280100')
            let componentCount = data.string('x00280004')
            let transportSyntax = data.string('x00020010')
            // let pixel = data.byteArrayParser.readUint16('x7fe0x0010')
            let pixelDataElement = data.elements.x7fe00010;
            let pixelDataOffset = pixelDataElement.dataOffset;
            let pixelDataLength = pixelDataElement.length;
            let pixelDataBytes = data.byteArray.subarray(pixelDataOffset, pixelDataOffset + pixelDataLength)
            if (transportSyntax === '1.2.840.10008.1.2.1' && ~componentCount.indexOf('MONOCHROME')) {
              let encoder = new codecWrapper.Encoder();
              let decodedBytes = encoder.getDecodedBuffer({width: width, height: height, bitsPerSample: bitsPerSample, componentCount: 1})
              encoder.setNearLossless(0);
              // 像素数据 7fe0 0010
              decodedBytes.set(pixelDataBytes);
              let startTime = performance.now()
              encoder.encode()
              let endTime = performance.now();
              // dicom替换压缩像素 组装
              let encodeDurationInSeconds = endTime - startTime
              let encodedBytes = encoder.getEncodedBuffer();
              data.elements['x00020010'].value = '1.2.840.10008.1.2.4.80'
              console.log(data.elements['x7fe00010'].length)
              data.elements['x7fe00010'].length = encodedBytes.length
              console.log(data.elements['x7fe00010'].length)
              let mateDataBytes = data.byteArray.subarray(0, pixelDataOffset)
              let modifiedByteArray = new Uint8Array([...mateDataBytes, ...encodedBytes])
              let newData = new dicomParser.ByteStream(data.byteArrayParser, modifiedByteArray, 0)
              console.log(data)
              console.log(newData)
              console.log(dicomParser.parseDicom(new Uint8Array(newData.byteArray)))
              await this.upload(`test/${index}`, newData)
              encoder.delete();
              return
            }
          };
          reader.readAsArrayBuffer(item);
        })
      }
    },
    open() {
      this.IsOpen = true
    },
    uploadOver(isSuccess, res) {
      if (isSuccess) {
        this.IsOpen = false
        this.videoUrl = res.url
        this.videoName = res.name
      }
    }
  }
}
</script>

<style scoped>

</style>
