<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({
  // 新换件
  repairReplaceRecord: [],
  // 维修后
  repairAfterRecord: []
})
const uploadDisables = ref({
  repairReplaceRecord: false,
  repairAfterRecord: false
})
const uploadList = [
  { key: 'repairReplaceRecord', name: '新换件' },
  { key: 'repairAfterRecord', 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 = () => {
  signatureRef.value.clear()
}
const undo = () => {
  signatureRef.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 submit = async () => {
  const signRecord = await uploadSign()
  const { repairReplaceRecord, repairAfterRecord } = fileList.value
  const { id } = options.value
  if (!repairReplaceRecord.length) {
    return uni.$u.toast('请上传新换件照片')
  }
  if (!repairAfterRecord.length) {
    return uni.$u.toast('请上传维修后照片')
  }
  const { error, result } = await postWorkDataCompleteApi({
    workId: id,
    workType: 2,
    repairReplaceRecord: repairReplaceRecord[0]?.url,
    repairAfterRecord: repairAfterRecord[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>上传维修照片</view>
      <view w-full f-s-s flex-wrap mt-12>
        <view
          v-for="(item, index) in uploadList"
          :key="index"
          w-300
          h-400
          mr-10
          f-c-c
          flex-col
          flex-none
        >
          <up-upload
            :file-list="fileList[item.key]"
            :max-count="1"
            :preview-full-image="true"
            :width="150"
            :height="150"
            :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 px-28 my-32>
      <view text-32>请在下方签名</view>
    </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"
      />
    </view>
    <view 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>
      <!-- <button @click="save">保存</button> -->
    </view>
  </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>
