<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '',
    navigationStyle: 'custom',
    disableScroll: true,
  },
}
</route>

<template>
  <div>
    <SpreadDesignerGeneric
      :businessConfig="businessConfig"
      :templateData="templateData"
      :templateBlob="templateBlob"
      @save="handleSave"
      @cancel="handleCancel"
    />
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import SpreadDesignerGeneric from '@/components/SpreadDesigner/spreadDesignerGeneric.vue'
import { onLoad } from '@dcloudio/uni-app'
import { buildFileUrl } from '@/utils/index'
import { useConfigStore } from '@/store/config'
import {
  SecurityCheckFuncName,
  requestFunc as securityCheckRequestFunc,
} from '@/api/ApiRouter/taskOrderSecurityCheck'
import { getStandardTemplate } from '@/api/index'
import { getDynamicTbVal, saveDynamicTbVal } from '@/api/task'

const configStore = useConfigStore()
const equipType = configStore.getEquipType()

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 = ''
let orderId: string = ''
let mode: 'edit' | 'create' = 'edit'
let securityCheckId: string = ''

onLoad((options: any) => {
  templateId = options.templateId
  orderId = options.orderId
  mode = options.mode || 'edit'
  securityCheckId = options.securityCheckId || ''
  init()
})

const instId = ref<string>('')
const refId = ref<string>('')
const init = async () => {
  if (!templateId) {
    return
  }
  refId.value = null
  if (mode === 'create') {
    const createResp = await securityCheckRequestFunc(
      SecurityCheckFuncName.createSecurityCheckItem,
      equipType,
      {
        businessType: 300,
        conclusion: '',
        date: null,
        name: '进入现场（设备）前安全检查记录',
        orderId,
        templateId,
      },
    )
    refId.value = createResp.data
  } else {
    refId.value = securityCheckId
  }

  const res = await getStandardTemplate({ id: templateId })
  const resData = (res as any).data
  const dataMap: any = {}

  const dynamicTbValResp = await getDynamicTbVal({ refId: refId.value })
  const dynamicTb: any = dynamicTbValResp.data
  instId.value = dynamicTb?.dynamicTbInsRespVO?.id || ''
  for (let i = 0; i < dynamicTb.dynamicTbValRespVOList.length; i++) {
    const item = dynamicTb.dynamicTbValRespVOList[i]
    dataMap[item.colCode] = item.valValue
  }

  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 错误
      },
    })
  })
}

const handleSave = async (data: any) => {
  const result = await saveDynamicTbVal({ params: data.dataJSON, instId: instId.value })
  if (result?.code === 0 && result?.data) {
    uni.showToast({ title: '保存成功', icon: 'success' })
  } else {
    const msg = result?.msg || '保存失败'
    uni.showToast({ title: msg, icon: 'error' })
  }
  const updateResp = await securityCheckRequestFunc(
    SecurityCheckFuncName.updateSecurityCheckItem,
    equipType,
    {
      id: refId.value,
      jsonData: JSON.stringify(data.dataJSON),
    },
  )
}

const handleCancel = () => {
  uni.navigateBack()
}
</script>
