<script setup>
import dayjs from 'dayjs'
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 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
  uploadFile([thumb], async ({ url }) => {
    fileList.value[name].push({ url, thumb })
  })
}
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 form = ref(null)
const model = ref({
  faultCause: '',
  reason: ''
})
const rules = ref({})

const showDatePicker = ref(false)
const finishTime = ref(dayjs().format('YYYY-MM-DD HH:mm:ss'))
const doDatePicker = () => {
  showDatePicker.value = true
  finishTime.value = dayjs().format('YYYY-MM-DD HH:mm:ss')
}
const confirmPicker = ({ value }) => {
  showDatePicker.value = false
  finishTime.value = value
  uni.showModal({
    title: '提示',
    content: '已确认日期吗？',
    success: (res) => {
      if (res.confirm) {
        submit()
      }
    }
  })
}

const submit = async () => {
  const signRecord = await uploadSign()
  const {
    carRoofAttachment,
    cabinAttachment,
    machineRoomAttachment,
    pitAttachment,
    doorAttachment,
    channelAttachment
  } = fileList.value
  const { id } = options.value
  const { error, result } = await postWorkDataCompleteApi({
    workId: id,
    workType: 1,
    finishTime: finishTime.value,
    faultCause: model.value.faultCause,
    reason: model.value.reason,
    carRoofAttachment: carRoofAttachment[0]?.url,
    cabinAttachment: cabinAttachment[0]?.url,
    machineRoomAttachment: machineRoomAttachment[0]?.url,
    pitAttachment: pitAttachment[0]?.url,
    doorAttachment: doorAttachment[0]?.url,
    channelAttachment: channelAttachment[0]?.url,
    // 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 v-if="false" 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-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"
            @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>
      <up-form
        ref="form"
        label-width="80"
        label-position="top"
        :model="model"
        :rules="rules"
      >
        <up-form-item
          label="故障原因："
          prop="faultCause"
          :border="`${'none'}`"
        >
          <up-textarea
            v-model="model.faultCause"
            placeholder="请输入故障原因"
            maxlength="300"
            count
            height="150"
          />
        </up-form-item>
        <up-form-item label="原因分析：" prop="reason" :border="`${'none'}`">
          <up-textarea
            v-model="model.reason"
            placeholder="请输入原因分析"
            maxlength="300"
            count
            height="150"
          />
        </up-form-item>
      </up-form>
    </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="doDatePicker"
      />
    </view>
  </view>

  <up-datetime-picker
    v-model="finishTime"
    title="选择完成时间"
    :show="showDatePicker"
    mode="datetime"
    @confirm="confirmPicker"
  />
</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>
