<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 { getEnvBaseUrl } from '@/utils/index'
import { getStandardTemplate } from '@/api/index'
import { getDynamicTbVal, saveDynamicTbVal } from '@/api/task'

const businessConfig = ref({
  businessType: 'CZZD',
  title: '指导书编辑',
  disableNavigate: true, // 是否禁用跳转，默认不禁用

  ui: {
    title: '指导书编辑',
    saveButtonText: '保存',
    cancelButtonText: '取消',
    showAdditionalToolbar: true,
    customButtons: [],
  },
})
const templateBlob = ref<string>('')
const templateData = ref<any>({})
const skipEntryKeys = ref<string[]>([])

let templateId: string = ''
let orderId: string = ''
let mode: 'edit' | 'create' = 'edit'
let workInstructionId: string = ''

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

const instId = ref<string>('')
const init = async () => {
  skipEntryKeys.value = []
  if (!templateId) {
    return
  }
  const res = await getStandardTemplate({ id: templateId })
  const resData = (res as any).data
  const dataMap: any = {}

  const dynamicTbValResp = await getDynamicTbVal({ refId: workInstructionId })
  const dynamicTb: any = dynamicTbValResp.data
  instId.value = dynamicTb?.dynamicTbInsRespVO?.id || ''
  for (let i = 0; i < dynamicTb.dynamicTbValRespVOList.length; i++) {
    const item = dynamicTb.dynamicTbValRespVOList[i]
    const val = item.valValue
    if (typeof val === 'string' && /\.(jpg|png)$/i.test(val)) {
      skipEntryKeys.value.push(item.colCode)
      continue
    }
    dataMap[item.colCode] = val
  }

  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 excelBlob = await fetchExcel(workInstructionId, templateId)
  const fileBase64 = await blobToBase64(excelBlob)
  templateBlob.value = fileBase64
}

const fetchExcel = async (refId: string | number, templateId: string | number): Promise<Blob> => {
  const apiPath = '/pressure2/excel/excel'
  let requestUrl = apiPath
  if (JSON.parse(import.meta.env.VITE_APP_PROXY) && import.meta.env.MODE === 'development') {
    requestUrl = import.meta.env.VITE_APP_PROXY_PREFIX + apiPath
  } else {
    requestUrl = getEnvBaseUrl() + apiPath
  }

  const token = uni.getStorageSync('APP_ACCESS_TOKEN')
  const headers: Record<string, string> = { 'Content-Type': 'application/json' }
  if (token) {
    headers.Authorization = `Bearer ${token}`
  }

  const response = await fetch(requestUrl, {
    method: 'POST',
    headers,
    body: JSON.stringify({ refId, templateId }),
  })

  if (!response.ok) {
    throw new Error(`获取Excel失败, status ${response.status}`)
  }

  return await response.blob()
}

const blobToBase64 = (blob: Blob): Promise<string> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = () => {
      const base64 = (reader.result as string).split(',')[1]
      resolve(base64)
    }
    reader.onerror = reject
    reader.readAsDataURL(blob)
  })
}

const handleSave = async (data: any) => {
  const reqData = {}
  for (const key in data.dataJSON) {
    if (skipEntryKeys.value.includes(key)) {
      continue
    }
    const element = data.dataJSON[key];
    reqData[key] = element
  }
  const result = await saveDynamicTbVal({ params: reqData, 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 handleCancel = () => {
  uni.navigateBack()
}
</script>
