<template>
  <view class="">
    <CuNavbar title="合同上传">
      <template #right>
        <view class="text-24rpx text-white" @click="submit">提交</view>
      </template>
    </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="name">
          <uv-input placeholder="请输入合同名称" inputAlign="right" :border="`none`" v-model="form.name"> </uv-input>
        </uv-form-item>
        <uv-line color="#f5f5f5"></uv-line>
        <uv-form-item label="合同照片" labelPosition="top" prop="images" required>
          <view class="w-full mt-15rpx">
            <uv-upload
              :maxCount="9"
              multiple
              :fileList="form.images"
              @afterRead="afterRead"
              @delete="deletePic"
              name="images"
            ></uv-upload>
          </view>
        </uv-form-item>
      </uv-form>
    </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({
  name: "",
  images: []
})
const rules = reactive({
  name: [{ required: true, message: "请输入清洁范围" }],
  images: {
    type: "array",
    required: true,
    message: "请上传报销凭证"
  }
})
onLoad(options => {
  id.value = options.id
  if (id.value) {
    http
      .request({
        url: `/agreements/${options.id}`,
        method: "GET",
        header: {
          Accept: "application/json"
        }
      })
      .then(res => {
        form.name = res.name
        form.images = res.images
      })
  }
})

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

const onSubmit = async () => {
  if (loading.value) return
  loading.value = true
  try {
    let url = id.value ? `/agreements/${id.value}` : "/agreements"
    let method = id.value ? "PUT" : "POST"
    await http.request({
      url: url,
      method: method,
      header: {
        Accept: "application/json"
      },
      data: {
        name: form.name,
        images: form.images.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>
