<template>
  <view class="p-base">
    <CuNavbar title="清洁任务提交"></CuNavbar>
    <view class="card-shadow px-base">
      <uv-form
        labelPosition="left"
        :model="form"
        :rules="rules"
        ref="formRef"
        errorType="toast"
        labelWidth="150rpx"
      >
        <uv-form-item required label="清洁范围" prop="description">
          <uv-input
            placeholder="请输入清洁范围"
            inputAlign="right"
            :border="`none`"
            v-model="form.description"
          >
          </uv-input>
        </uv-form-item>
        <uv-line color="#f5f5f5"></uv-line>
        <uv-form-item
          label="报销凭证"
          labelPosition="top"
          prop="photos"
          required
        >
          <view class="w-full mt-15rpx">
            <uv-upload
              :maxCount="9"
              multiple
              :fileList="form.photos"
              @afterRead="afterRead"
              @delete="deletePic"
              name="photos"
            ></uv-upload>
          </view>
        </uv-form-item>
      </uv-form>
    </view>
    <view class="mt-100rpx">
      <uv-button type="primary" @click="submit">提交</uv-button>
    </view>

    <uv-modal
      ref="modalRef"
      title="提示"
      content="确定提交吗?"
      @confirm="onSubmit"
      :showCancelButton="true"
    ></uv-modal>
  </view>
</template>
<script setup>
import CuNavbar from '@/components/cu-navbar/index'
import { ref, reactive, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { http } from '@/utils/request'
const formRef = ref(null)
const modalRef = ref(null)
const id = ref(0)
const loading = ref(false)
const form = reactive({
  description: '',
  photos: [],
})
const rules = reactive({
  description: [{ required: true, message: '请输入清洁范围' }],
  photos: {
    type: 'array',
    required: true,
    message: '请上传报销凭证',
  },
})
onLoad((options) => {
  id.value = options.id
})

const submit = () => {
  formRef.value.validate().then((res) => {
    modalRef.value.open()
  })
}

const onSubmit = async () => {
  if (loading.value) return
  loading.value = true
  try {
    await http.request({
      url: `/tasks/${id.value}/submit`,
      method: 'POST',
      header: {
        Accept: 'application/json',
      },
      data: {
        task_hygiene: {
          description: form.description,
          photos: form.photos.map((item) => item.url),
        },
      },
    })
    uni.showToast({
      title: '提交成功',
      icon: 'none',
    })
    formRef.value.resetFields()
    uni.$emit('task:submit', resData)
    uni.navigateBack()
  } catch (error) {
    console.log(error)
  } finally {
    loading.value = false
  }
}

const afterRead = async (event) => {
  let lists = [].concat(event.file)
  let fileListLen = form[event.name].length

  lists.map((item) => {
    form[event.name].push({
      ...item,
      status: 'uploading',
      message: '上传中',
    })
  })
  for (let i = 0; i < lists.length; i++) {
    const result = await uploadFilePromise(lists[i].url)
    let item = form[event.name][fileListLen]
    form[event.name].splice(
      fileListLen,
      1,
      Object.assign(item, {
        status: 'success',
        message: '',
        url: result,
      })
    )
    fileListLen++
  }
}

const uploadFilePromise = (url) => {
  return new Promise((resolve, reject) => {
    http
      .upload('/fileupload', {
        filePath: url,
        name: 'file',
      })
      .then((res) => {
        resolve(res.url)
      })
      .catch((err) => {
        reject(err)
      })
  })
}

const deletePic = (event) => {
  form[event.name].splice(event.index, 1)
}
</script>
