<script lang="ts" setup>
import {appMerchantOrderDeliverOrderPost, appMerchantOrderDeliveryListPost} from "@/service";
import {useConfigStore} from "@/store";
import ChooseImage from "@/components/choose-image/choose-image.vue";
import {z} from 'zod';

const {t} = useI18n();
const emits = defineEmits(['submit'])
const configStore = useConfigStore()

const show = ref(false);

const formData = reactive({
  deliveryPhone: '',
  orderId: '',
  deliveryAvatar: '',
  deliverySurname: '',
  deliveryFirstName: '',
})

// Zod 校验 schema
const formSchema = z.object({
  deliveryPhone: z.string().min(1, t('pages-user.order.startDeliveryForm.validation.deliveryPhoneRequired')),
  orderId: z.string().min(1, t('pages-user.order.startDeliveryForm.validation.orderIdRequired')),
  deliverySurname: z.string().min(1, t('pages-user.order.startDeliveryForm.validation.deliverySurnameRequired')),
  deliveryFirstName: z.string().min(1, t('pages-user.order.startDeliveryForm.validation.deliveryFirstNameRequired')),
})

function onOpen(orderId: string) {
  formData.orderId = orderId
  show.value = true;
  // 获取最新配送订单的配送员信息
  getLatestDeliveryOrderInfo()
}

const userList = ref([])
// 当前选中的配送员信息下标
const currentSort = ref(null)

function getLatestDeliveryOrderInfo() {
  appMerchantOrderDeliveryListPost({}).then(res => {
    console.log('获取最新配送订单的配送员信息', res)
    userList.value = res.data
    isShowAdd.value = res.data.length <= 0;
  })
}

function changeUser(item: any, index: number) {
  currentSort.value = index
  formData.deliveryAvatar = item.deliveryAvatar
  formData.deliverySurname = item.deliverySurname
  formData.deliveryFirstName = item.deliveryFirstName
  formData.deliveryPhone = item.deliveryPhone
}

function handleClose() {
  show.value = false;
}

function handleSubmit() {
  try {
    // 使用 zod 校验表单数据
    formSchema.parse(formData)

    // 校验通过，调用接口
    appMerchantOrderDeliverOrderPost({
      body: {
        ...formData
      }
    }).then(res => {
      emits('submit')
      handleClose()
    })
  } catch (error) {
    // 校验失败，显示错误信息
    if (error instanceof z.ZodError) {
      const firstError = error.errors[0]
      uni.showToast({
        title: firstError.message,
        icon: 'none'
      })
    }
  }
}

const chooseImageRef = ref()

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

function onImageChange(file: any) {
  if (file.length > 0) {
    formData.deliveryAvatar = file[0]
  }
}

const isShowAdd = ref(false)


defineExpose({
  onOpen,
});
</script>

<template>
  <wd-popup v-model="show" custom-style="border-radius:32rpx 32rpx 0 0;" position="bottom"
            @close="handleClose">
    <view>
      <view class="flex-center-sb h-102rpx bg-#F7F7F7 px-30rpx">
        <view class="text-30rpx text-#999" @click="handleClose">{{ t('common.cancel') }}</view>
        <view class="text-34rpx text-#333">{{ t('pages-user.order.startDeliveryForm.title') }}</view>
        <view class="text-30rpx text-#FF6106" @click="handleSubmit">{{ t('common.confirm') }}</view>
      </view>

      <!--已经有配送员信息-->
      <template v-if="!isShowAdd">
        <scroll-view class="h-400rpx" scroll-y="true">
          <view class="px-30rpx">
            <template v-for="(item, index) in userList">
              <view class="w-full py-24rpx bg-white flex-center-sb" @click="changeUser(item, index)">
                <view class="flex items-center">
                  <image
                      :src="item.deliveryAvatar"
                      class="w-76rpx h-76rpx rounded-50%"
                      mode="aspectFill"
                  />
                  <view class="ml-20rpx">
                    <view>{{ item.deliverySurname || '' }} {{ item.deliveryFirstName || '' }}</view>
                    <view>{{ item.deliveryPhone || '' }}</view>
                  </view>
                </view>
                <image
                    :src="
                  index === currentSort
                  ? '/static/images/chef/152.png'
                   : '/static/images/chef/134.png'
                  "
                    class="w-40rpx h-40rpx"
                    mode="aspectFit"
                />
              </view>
            </template>
          </view>
        </scroll-view>

        <view class="px-30rpx w-full" @click="isShowAdd = true">
          <wd-button class="w-full !h-98rpx">{{ t('pages-user.recipe.index.add') }}</wd-button>
        </view>
      </template>
      <template v-else>
        <view class="px-30rpx py-20rpx">
          <view class="mt-20rpx">
            <view class="text-28rpx lh-28rpx text-#333 font-500 mb-20rpx">
              {{ t('pages-user.order.startDeliveryForm.deliveryAvatar') }}
            </view>
            <view class="h-98rpx" @click="chooseImage">
              <image
                  v-if="formData.deliveryAvatar"
                  :src="formData.deliveryAvatar"
                  class="w-76rpx h-76rpx rounded-50%"
                  mode="aspectFill"
              />
              <image
                  v-else
                  class="w-76rpx h-76rpx rounded-50%"
                  mode="aspectFill"
                  src="@img/chef/default_avatar.png"
              />
            </view>
          </view>
          <view class="mt-20rpx">
            <view class="text-28rpx lh-28rpx text-#333 font-500 mb-20rpx">
              {{ t('pages-user.order.startDeliveryForm.deliveryPhone') }}
            </view>
            <view class="flex-center-sb h-98rpx px-24rpx rounded-16rpx bg-#F6F6F6">
              <wd-input
                  v-model="formData.deliveryPhone"
                  :focus-when-clear="false"
                  :placeholder="t('common.enter')"
                  clearable
                  confirm-type="done"
                  custom-class="!text-30rpx !bg-transparent flex-1"
                  no-border
                  placeholderStyle="font-size: 30rpx;color: #999;"
                  use-prefix-slot
              >
              </wd-input>
            </view>
          </view>
          <view class="mt-20rpx">
            <view class="text-28rpx lh-28rpx text-#333 font-500 mb-20rpx">
              {{ t('pages-user.order.startDeliveryForm.deliverySurname') }}
            </view>
            <view class="flex-center-sb h-98rpx px-24rpx rounded-16rpx bg-#F6F6F6">
              <wd-input
                  v-model="formData.deliverySurname"
                  :focus-when-clear="false"
                  :placeholder="t('common.enter')"
                  clearable
                  confirm-type="done"
                  custom-class="!text-30rpx !bg-transparent flex-1"
                  no-border
                  placeholderStyle="font-size: 30rpx;color: #999;"
                  use-prefix-slot
              >
              </wd-input>
            </view>
          </view>
          <view class="mt-20rpx">
            <view class="text-28rpx lh-28rpx text-#333 font-500 mb-20rpx">
              {{ t('pages-user.order.startDeliveryForm.deliveryFirstName') }}
            </view>
            <view class="flex-center-sb h-98rpx px-24rpx rounded-16rpx bg-#F6F6F6">
              <wd-input
                  v-model="formData.deliveryFirstName"
                  :focus-when-clear="false"
                  :placeholder="t('common.enter')"
                  clearable
                  confirm-type="done"
                  custom-class="!text-30rpx !bg-transparent flex-1"
                  no-border
                  placeholderStyle="font-size: 30rpx;color: #999;"
                  use-prefix-slot
              >
              </wd-input>
            </view>
          </view>
        </view>
      </template>
      <view :style="[configStore.iosSafeBottomPlaceholder]"></view>
    </view>
  </wd-popup>
  <ChooseImage ref="chooseImageRef" @change="onImageChange"/>
</template>

<style lang="scss" scoped>
:deep(.wd-input__clear) {
  background-color: transparent !important;
}
</style>