<script lang="ts" setup>
import ChooseImage from "@/components/choose-image/choose-image.vue";
import {appMerchantOrderArrivedOrderPost} from "@/service";

const {t} = useI18n();
const formData = ref({
  orderId: '',
  dishImage: []
})

onLoad((options) => {
  if (options.id) {
    formData.value.orderId = options.id
  }
})

function removeImage(index: number) {
  formData.value.dishImage.splice(index, 1)
}

function onImageChange(file: any) {
  if (file.length > 0) {
    formData.value.dishImage.push(file[0])
  }
}

const chooseImageRef = ref()

function handleChooseImage() {
  if (chooseImageRef.value?.init) {
    chooseImageRef.value.init();
  }
}


function submitDelivery() {
  // if (formData.value.dishImage.length === 0) {
  //   uni.showToast({
  //     title: t('pages-user.order.deliveredOrder.uploadPhoto'),
  //     icon: 'none'
  //   })
  //   return
  // }
  appMerchantOrderArrivedOrderPost({
    body: {
      orderId: formData.value.orderId,
      deliveryPhotos: formData.value.dishImage.join(',')
    }
  }).then(res => {
    uni.showToast({
      title: t('toast.submitSuccess'),
      icon: 'none'
    })
    setTimeout(() => {
      uni.navigateBack()
    }, 1000)
  })
}
</script>

<template>
  <view>
    <navbar :title="t('pages-user.order.delivered')"></navbar>
    <view class="px-30rpx">
      <view class="pt-52rpx pb-32rpx text-36rpx text-#333 font-500">
        {{ t('pages-user.order.deliveredTips') }}:
      </view>

      <view class="grid grid-cols-3 gap-20rpx">
        <template v-for="(item, index) in formData.dishImage">
          <view class="relative w-210rpx h-210rpx">
            <image
                v-if="item"
                class="absolute top-0rpx right-0rpx z-1 w-36rpx h-36rpx"
                src="@img/chef/190.png"
                @click="removeImage(index)"
            ></image>
            <image
                :src="item"
                class="w-210rpx h-210rpx rounded-16rpx"
                mode="aspectFill"
            ></image>
          </view>
        </template>

        <view v-if="formData.dishImage.length < 4" class="w-210rpx h-210rpx center flex-col bg-#F6F6F6 rounded-20rpx"
              @click="handleChooseImage">
          <wd-icon color="#3D3D3D" name="add" size="32px"></wd-icon>
          <text class="text-30rpx lh-30rpx text-#333 mt-20rpx">{{ t('pages-user.food.add-food.addPicture') }}</text>
        </view>
      </view>
    </view>

    <fixed-bottom-large-btn
        :text="t('common.confirm')"
        class="z-100"
        fixed
        @click="submitDelivery"
    />

    <ChooseImage ref="chooseImageRef" @change="onImageChange"/>
  </view>
</template>

<style>
page {
  background-color: #fff;
}
</style>