<script setup>
import { postWorkDataCompleteApi } from '@/api/elevator'
import { useUpload } from '@/composables/use-upload'
const { uploadFile } = useUpload()

const instance = getCurrentInstance().proxy
const eventChannel = instance.getOpenerEventChannel()

const fileList = ref({
  // 轿顶
  carRoofAttachment: [],
  // 轿厢
  cabinAttachment: [],
  // 机房
  machineRoomAttachment: [],
  // 底坑
  pitAttachment: [],
  // 轿门
  doorAttachment: [],
  // 井道
  channelAttachment: []
})
const uploadDisables = ref({
  carRoofAttachment: false,
  cabinAttachment: false,
  machineRoomAttachment: false,
  pitAttachment: false,
  doorAttachment: false,
  channelAttachment: false
})
const uploadList = [
  { key: 'carRoofAttachment', name: '轿顶' },
  { key: 'cabinAttachment', name: '轿厢' },
  { key: 'machineRoomAttachment', name: '机房' },
  { key: 'pitAttachment', name: '底坑' },
  { key: 'doorAttachment', name: '轿门' },
  { key: 'channelAttachment', name: '井道' }
]
const afterRead = ({ file }, name) => {
  const { thumb } = file
  uploadDisables.value[name] = true
  uploadFile([thumb], async ({ url }) => {
    fileList.value[name].push({ url, thumb })
    uploadDisables.value[name] = false
  })
}
const deletePic = (index, name) => {
  fileList.value[name].splice(index, 1)
}

const signatureRef = ref(null)
// const instance = getCurrentInstance()
const clear = () => {
  if (signatureInfo.value.index === 0) {
    signatureRef.value.clear()
  } else if (signatureInfo.value.index === 1) {
    signatureRef2.value.clear()
  }
}
const undo = () => {
  if (signatureInfo.value.index === 0) {
    signatureRef.value.undo()
  } else if (signatureInfo.value.index === 1) {
    signatureRef2.value.undo()
  }
}
const uploadSign = () => {
  const { id } = options.value
  return new Promise((resolve) => {
    const isEmpty = signatureRef.value.isEmpty()
    if (isEmpty) {
      uni.$u.toast('签名不能为空')
      return
    }
    signatureRef.value.canvasToTempFilePath({
      success: ({ tempFilePath }) => {
        uploadFile([tempFilePath], async ({ url }) => {
          // await postWorkDataCompleteApi({
          //   id,
          //   signRecord: url
          // })
          resolve(url)
        })
        // uni.saveImageToPhotosAlbum({
        //   filePath: tempFilePath,
        //   success: () => {
        //     // uni.$u.toast('保存成功')
        //     uploadFile([tempFilePath], async ({ url }) => {
        //       await postWorkDataRecordUploadApi(
        //         [{ remark: '', attachmentUrl: url, attachmentType: 1 }],
        //         id
        //       )
        //       getWorkDataInfo()
        //     })
        //   },
        //   fail: () => {
        //     uni.$u.toast('上传失败')
        //   }
        // })
      }
    })
  })
}

const signatureRef2 = ref(null)
const signatureInfo = ref({
  index: 0,
  list: []
})
const confirmFirst = async () => {
  uni.showLoading({
    title: '请等待...',
    mask: true
  })
  const { index } = signatureInfo.value
  if (index === 0) {
    const isEmpty = signatureRef.value.isEmpty()
    if (isEmpty) {
      uni.$u.toast('第一位维保签名不能为空')
      return
    }
    signatureRef.value.canvasToTempFilePath({
      success: ({ tempFilePath }) => {
        uploadFile([tempFilePath], async ({ url }) => {
          signatureInfo.value.list.push(url)
          signatureInfo.value.index = 1
          uni.hideLoading()
        })
      },
      fail: () => {
        uni.hideLoading()
      }
    })
  }
}
const uploadSign2 = () => {
  return new Promise((resolve) => {
    const isEmpty = signatureRef2.value.isEmpty()
    if (isEmpty) {
      uni.$u.toast('第二位维保签名不能为空')
      return
    }
    signatureRef2.value.canvasToTempFilePath({
      success: ({ tempFilePath }) => {
        uploadFile([tempFilePath], async ({ url }) => {
          signatureInfo.value.list.push(url)
          uni.hideLoading()
          resolve(url)
        })
      },
      fail: () => {
        uni.hideLoading()
      }
    })
  })
}

const submit = async () => {
  // const signRecord = await uploadSign()
  const {
    carRoofAttachment,
    cabinAttachment,
    machineRoomAttachment,
    pitAttachment,
    doorAttachment,
    channelAttachment
  } = fileList.value
  const { id } = options.value

  uploadList.forEach(({ key, name }) => {
    if (!fileList.value[key].length) {
      uni.$u.toast(`请上传${name}照片`)
      throw new Error(`请上传${name}照片`)
    }
  })

  await uploadSign2()
  const signRecord = signatureInfo.value.list.join(',')

  const { error, result } = await postWorkDataCompleteApi({
    workId: id,
    workType: 3,
    carRoofAttachment: carRoofAttachment[0].url,
    cabinAttachment: cabinAttachment[0].url,
    machineRoomAttachment: machineRoomAttachment[0].url,
    pitAttachment: pitAttachment[0].url,
    doorAttachment: doorAttachment[0].url,
    channelAttachment: channelAttachment[0].url,
    signRecord
  })
  if (error) {
    uni.$u.toast(result.msg || '系统异常，请稍后重试')
    return
  }
  uni.$u.toast('提交成功')
  eventChannel.emit('done', {})
  setTimeout(() => {
    uni.navigateBack()
  }, 1500)
}

const options = ref({})
onLoad(async (e) => {
  options.value = e
})
</script>

<template>
  <view min-h-100vh pb-100>
    <view class="upload-container" px-28 my-32>
      <view text-32>
        上传电梯照片
        <text text-red text-28>（上传双人维保照片）</text>
      </view>
      <view w-full f-s-s flex-wrap mt-12>
        <view
          v-for="(item, index) in uploadList"
          :key="index"
          w-220
          h-300
          mr-10
          f-c-c
          flex-col
          flex-none
        >
          <up-upload
            :file-list="fileList[item.key]"
            :max-count="1"
            :preview-full-image="true"
            :width="110"
            :height="110"
            :disabled="uploadDisables[item.key]"
            @afterRead="afterRead($event, item.key)"
            @delete="deletePic($event, item.key)"
          />
          <view text-center text-26 mt-8>请上传{{ item.name }}照片</view>
        </view>
      </view>
    </view>

    <!-- <view
      z-1
      left-0
      top-0
      right-0
      bottom-0
      m-auto
      text-40
      text-center
      color-gray
      my-12
    >
      请在下方签名
    </view> -->
    <view px-28 my-32>
      <view text-32 f-s-c>
        请在下方签名
        <span text-red>
          （第{{ signatureInfo.index === 0 ? '一' : '二' }}位维保人）
        </span>
      </view>
    </view>
    <view my-20 f-c-c>
      <up-button
        size="small"
        :custom-style="{ width: '80px' }"
        type="error"
        @click="clear"
      >
        清空
      </up-button>
      <up-button
        size="small"
        :custom-style="{ 'margin-left': '10px', width: '80px' }"
        type="info"
        @click="undo"
      >
        撤消
      </up-button>
      <up-button
        v-if="signatureInfo.index === 0"
        size="small"
        :custom-style="{ 'margin-left': '10px', width: '80px' }"
        type="primary"
        @click="confirmFirst"
      >
        下一个签名
      </up-button>
      <!-- <button @click="save">保存</button> -->
    </view>
    <view w-746 h-600 mx-auto relative border-1 border-dotted border-gray f-c-c>
      <view
        w-full
        h-full
        absolute
        top-0
        left-0
        z--1
        text-60
        color="#DDDDDD"
        f-c-c
        class="signature-placeholder"
      >
        请在此处签名
      </view>

      <HandwrittenSignature
        ref="signatureRef"
        style="width: 746rpx; height: 596rpx"
        disable-scroll
        :open-smooth="true"
        background-color="transparent"
        uid="0"
        pen-color="black"
        :pen-size="10"
        :min-line-width="2"
        :style="{
          display: signatureInfo.index === 0 ? 'block' : 'none',
          position: 'absolute',
          top: '0',
          left: '0',
          right: '0',
          bottom: '0',
          margin: 'auto',
          zIndex: 2
        }"
      />
      <HandwrittenSignature
        ref="signatureRef2"
        style="width: 746rpx; height: 596rpx"
        disable-scroll
        :open-smooth="true"
        background-color="transparent"
        uid="0"
        pen-color="black"
        :pen-size="10"
        :min-line-width="2"
      />
    </view>
    <view v-if="false" mt-20 f-c-c mb-100>
      <up-button
        size="small"
        :custom-style="{ width: '80px' }"
        type="error"
        @click="clear"
      >
        清空
      </up-button>
      <up-button
        size="small"
        :custom-style="{ 'margin-left': '10px', width: '80px' }"
        type="info"
        @click="undo"
      >
        撤消
      </up-button>
      <up-button
        v-if="signatureInfo.index === 0"
        size="small"
        :custom-style="{ 'margin-left': '10px', width: '80px' }"
        type="primary"
        @click="confirmFirst"
      >
        下一个签名
      </up-button>
      <!-- <button @click="save">保存</button> -->
    </view>
    <view h-100 />
  </view>

  <view position="fixed" w-full h-130 bottom-0 z-9 f-s-c flex-col bg-white>
    <view absolute left-0 right-0 m-auto bottom-36>
      <up-button
        type="primary"
        text="提交"
        :custom-style="{
          width: '650rpx'
        }"
        @click="submit"
      />
    </view>
  </view>
</template>

<style lang="scss" scoped>
.upload-container ::v-deep .u-upload {
  flex: none !important;
}

.signature-placeholder {
  letter-spacing: 4px;
  // 横线 - 虚线
  &::before {
    content: '';
    width: 100%;
    height: 0px;
    background-color: transparent;
    border-bottom: 1px dotted #ccc;
    position: absolute;
    top: 50%;
    left: 0;
    right: 0;
    margin: 0 auto;
    margin-top: -1px;
  }
  &::after {
    content: '';
    width: 0;
    height: 100%;
    background-color: transparent;
    border-right: 1px dotted #ccc;
    position: absolute;
    top: 0;
    left: 50%;
    right: 0;
    margin: auto 0;
    margin-left: -1px;
  }
}
</style>
