<template>
  <div>
    <SpreadDesignerGeneric
      :businessConfig="businessConfig"
      :templateData="templateData"
      :templateBlob="templateBlob"
    />
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import SpreadDesignerGeneric from '@/components/SpreadDesigner/spreadDesignerGeneric.vue'
import { onLoad } from '@dcloudio/uni-app'

import { getStandardTemplate } from '@/api/index'
import { buildFileUrl } from '@/utils/index'

const businessConfig = ref({
  businessType: 'AQJC',
  title: '安全检查记录编辑',
  disableNavigate: true, // 是否禁用跳转，默认不禁用

  ui: {
    title: '安全检查记录',
    saveButtonText: '保存',
    cancelButtonText: '取消',
    showAdditionalToolbar: true,
    customButtons: [],
  },
})
const templateBlob = ref<string>('')
const templateData = ref<any>({})

let templateId: string = ''

onLoad((options: any) => {
  templateId = options.templateId
  init()
})

const init = async () => {
  if (!templateId) {
    return
  }
  const res = await getStandardTemplate({ id: templateId })
  const resData = (res as any).data
  const dataMap = {}

  templateData.value = {
    schema: resData.bindingPathSchema ? JSON.parse(resData.bindingPathSchema) : {},
    data: {
      ...dataMap,
      templateId,
      templateUrl: resData.fileUrl,
    },
    pathNameMapping: JSON.parse(resData.bindingPathNameJson),
    template: templateId,
    templateUrl: resData.fileUrl,
  }

  const fileUri = resData.fileUrl
  const fileUrl = buildFileUrl(fileUri)
  const fileBase64 = await downloadFileAsBase64(fileUrl)
  templateBlob.value = fileBase64
}

const downloadFileAsBase64 = (fileUrl: string): Promise<string> => {
  return new Promise((resolve, reject) => {
    uni.request({
      url: fileUrl,
      method: 'GET',
      responseType: 'arraybuffer',
      success: (res) => {
        if (res.statusCode === 200) {
          const arrayBuffer = res.data as ArrayBuffer
          const uint8Array = new Uint8Array(arrayBuffer)
          const binaryString = uint8Array.reduce((data, byte) => {
            return data + String.fromCharCode(byte)
          }, '')
          const base64 = btoa(binaryString)
          resolve(base64) // 成功时 resolve Base64 字符串
        } else {
          reject(new Error(`Request failed with status ${res.statusCode}`))
        }
      },
      fail: (err) => {
        reject(err) // 失败时 reject 错误
      },
    })
  })
}
</script>
