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

<!-- 检测记录编辑 -->
<template>
  <view>
    <!-- 相比于 SpreadDesignerGeneric 悬浮输入框，有拍摄图片，但是导航栏没有扩展性 -->
    <SpreadDesigner
      ref="spreadDesignerRef"
      :checkItemData="checkItemData"
      :reportList="reportList"
      :taskOrderItem="taskOrderItem"
      :templateBlob="templateBlob"
      @save="handleSave"
      @cancel="handleCancel"
      @close="handleCancel"
      @openCamera="handleOpenCamera"
      @selectedReport="handleSelectedReport"
    />
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import SpreadDesigner from '@/components/SpreadDesigner/spreadDesigner.vue'
import { onLoad } from '@dcloudio/uni-app'
import { getCheckerEquipmentDetailById, getDynamicTbVal, saveDynamicTbVal } from '@/api/task'
import { getStandardTemplate } from '@/api/index'
import { buildFileUrl } from '@/utils/index'
import { PressureCheckerMyTaskStatus } from '@/utils/dictMap'

const spreadDesignerRef = ref<any>(null)
const checkItemData = ref<any>(null)
const reportList = ref<any[]>([])
const taskOrderItem = ref<any>(null)
const templateBlob = ref<string>('')

let orderItemId = ''
let checkItemId = ''
let useOnline = ''
let templateId = ''
let equipCode = ''
let reportUrlParam = ''

const init = async () => {
  await handleGetCheckItemDetail(checkItemId, templateId)
  await getDetail()
}

const handleGetCheckItemDetail = async (
  reportId: string | undefined,
  newTemplateId: string | undefined,
) => {
  const isTemplateSwitch =
    checkItemData.value?.checkItemId && checkItemData.value.checkItemId !== reportId

  if (!reportId) {
    console.error('reportId 为空，无法获取模板详情')
    return
  }

  if (useOnline === '1') {
    const templateResult = await getStandardTemplate({ id: newTemplateId || '' })
    const templateDetail = (templateResult as any).data

    if (!templateDetail) {
      uni.showToast({ title: '模板缺失了，请检查！', icon: 'error' })
      uni.navigateBack()
      return
    }

    const dynamicTbResp = await getDynamicTbVal({
      refId: reportId,
    })
    const dynamicTb = dynamicTbResp.data
    const initJSONResult = {}
    for (let i = 0; i < dynamicTb.dynamicTbValRespVOList.length; i++) {
      const item = dynamicTb.dynamicTbValRespVOList[i]
      initJSONResult[item.colCode] = item.valValue
    }

    const recordTemplateUrl: string | undefined = templateDetail.fileUrl

    const blob = await getBlob(recordTemplateUrl || '')

    const dic = {
      blob: blob || '',
      reportUrl: recordTemplateUrl || '',
      instId: dynamicTb?.dynamicTbInsRespVO?.id || '',
      bindingPathSchema: templateDetail?.bindingPathSchema || '',
      bindingPathNameJson: templateDetail?.bindingPathNameJson,
      prepareJson: (initJSONResult as any) || '',
      reportName: templateDetail?.name || '',
      reportType: templateDetail?.reportType || '',
      taskStatus: templateDetail?.taskStatus || '',
      checkItemId: reportId,
      templateId: newTemplateId,
      templateUrl: recordTemplateUrl || '',
    }

    checkItemData.value = dic
    return dic
  } else {
    checkItemData.value = {
      blob: '',
      reportUrl: reportUrlParam || '',
      bindingPathSchema: '',
      bindingPathNameJson: {},
      prepareJson: '{}',
      reportName: '本地模板',
      reportType: 100,
      taskStatus: 200,
      checkItemId: reportId,
    }
    return checkItemData.value
  }
}

const getDetail = async () => {
  if (useOnline === '1') {
    const result = await getCheckerEquipmentDetailById({ id: orderItemId })
    if (result) {
      const resData = (result as any).data
      const resDataReportList = resData?.reportList
      let filteredReportList = []
      if (resDataReportList) {
        filteredReportList = resDataReportList
          .map((item: any) => ({
            ...item,
            equipId: resData.taskOrderItem.equipId,
            equipCode: resData.taskOrderItem.equipCode,
          }))
          .filter((item: any) =>
            [
              PressureCheckerMyTaskStatus.CONFIRMED,
              PressureCheckerMyTaskStatus.RECORD_INPUT,
            ].includes(item.taskStatus),
          )
      }

      reportList.value = filteredReportList
      taskOrderItem.value = resData?.taskOrderItem
    }
  }
}

const getBlob = async (url: string): Promise<string> => {
  if (!url) return ''
  const fileUrl = buildFileUrl(url)
  return downloadFileAsBase64(fileUrl)
}

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)
        } else {
          reject(new Error(`Request failed with status ${res.statusCode}`))
        }
      },
      fail: (err) => {
        reject(err)
      },
    })
  })
}

const handleSave = async (data: any) => {
  try {
    if (useOnline === '1') {
      const instId = data.instId
      const result = await saveDynamicTbVal({ params: data.prepareJson, instId })
      if (result?.code === 0 && result?.data) {
        uni.showToast({ title: '保存成功', icon: 'success' })
      } else {
        const msg = result?.msg || '保存失败'
        uni.showToast({ title: msg, icon: 'error' })
      }
    } else {
      uni.showToast({ title: '文件存储成功', icon: 'success' })
      uni.$emit('webViewSaved', {
        checkItemId: data.checkItemId,
        localReportUrl: data.reportUrl,
        bindingPathSchema: data.bindingPathSchema,
        prepareJson: data.prepareJson,
        images: data.images,
      })
      uni.navigateBack()
    }
  } catch (error) {
    console.error('保存失败:', error)
    uni.showToast({ title: '保存失败', icon: 'error' })
  }

  // try {
  //   if (useOnline === '1') {
  //     const uploadItems: any[] = []
  //     if (data.blob) {
  //       const uploadRes = await reportUploadApi({
  //         items: [{ reportId: data.checkItemId, image: data.blob }],
  //       })
  //       if ((uploadRes as any)?.data) {
  //         const uploadedUrl = Array.isArray((uploadRes as any).data)
  //           ? (uploadRes as any).data[0]
  //           : (uploadRes as any).data
  //         data.reportUrl = uploadedUrl || data.reportUrl
  //       }
  //     }

  //     const submitResult = await saveTaskReportTemplate({
  //       id: data.checkItemId,
  //       reportUrl: data.reportUrl,
  //       prepareJson: data.prepareJson,
  //     })

  //     if ((submitResult as any)?.data) {
  //       if (data.images && data.images.length > 0) {
  //         const images = [...data.images]
  //         for (const image of images) {
  //           const imgUploadRes = await reportUploadApi({
  //             items: [{ reportId: data.checkItemId, image: image.imgUrl }],
  //           })
  //           if ((imgUploadRes as any)?.data) {
  //             const uploadedImgUrl = Array.isArray((imgUploadRes as any).data)
  //               ? (imgUploadRes as any).data[0]
  //               : (imgUploadRes as any).data
  //             image.imgUrl = uploadedImgUrl
  //           }
  //         }
  //         await saveTaskReportTemplateImages({ itemReportId: data.checkItemId, images })
  //       }

  //       uni.showToast({ title: '保存成功', icon: 'success' })
  //       uni.$emit('webViewSaved', {
  //         checkItemId: data.checkItemId,
  //         reportUrl: data.reportUrl,
  //         bindingPathSchema: data.bindingPathSchema,
  //         prepareJson: data.prepareJson,
  //         isOnline: true,
  //       })
  //       uni.navigateBack()
  //     }
  //   } else {
  //     uni.showToast({ title: '文件存储成功', icon: 'success' })
  //     uni.$emit('webViewSaved', {
  //       checkItemId: data.checkItemId,
  //       localReportUrl: data.reportUrl,
  //       bindingPathSchema: data.bindingPathSchema,
  //       prepareJson: data.prepareJson,
  //       images: data.images,
  //     })
  //     uni.navigateBack()
  //   }
  // } catch (error) {
  //   console.error('保存失败:', error)
  //   uni.showToast({ title: '保存失败', icon: 'error' })
  // }
}

const handleCancel = () => {
  uni.navigateBack()
}

const handleOpenCamera = () => {
  console.log('打开相机')
}

const handleSelectedReport = async (data: any) => {
  if (data.reportId === checkItemData.value?.checkItemId) {
    return
  }

  try {
    const dic = await handleGetCheckItemDetail(data.reportId, data.templateId)
    if (dic && spreadDesignerRef.value) {
      spreadDesignerRef.value.updateCheckItemData(dic)
    }
  } catch (error) {
    console.error('模板切换失败:', error)
    uni.showToast({ title: '模板切换失败', icon: 'error' })
  }
}

onLoad((options: any) => {
  orderItemId = options.orderItemId || ''
  checkItemId = options.checkItemId || ''
  useOnline = options.useOnline || '0'
  templateId = options.templateId || ''
  equipCode = options.equipCode || ''
  reportUrlParam = options.reportUrl || ''

  if (!checkItemId) {
    console.error('checkItemId 为空')
    uni.navigateBack()
    return
  }

  init()
})
</script>
