<template>
  <div class="drawer-dialog-container">
    <van-popup v-model:show="state.dialog.isShowDialog" position="right" :style="{ width: '85vw', maxWidth: '460px', height: '100vh' }"
      :closeable="true" round @close="onCancel" :close-on-click-overlay="false">
      <div class="drawer-wrapper">
        <header class="drawer-header">
          <h3>{{ state.dialog.title }}</h3>
        </header>
        <div class="drawer-body">
          <van-form ref="expertDialogFormRef" @submit="onSubmit">
            <van-cell-group inset>
              <van-field v-model="state.form.returnDate" label="转回日期" placeholder="请选择时间" readonly
                is-link @click="showReturnDatePicker = true" />

              <van-field  v-model="state.form.returnTransport" label="运输方式" placeholder="请输入" />

              <van-field label="雄性">
                <template #input>
                  <van-stepper v-model="state.form.returnMaleNumber" integer :min="0" />
                </template>
              </van-field>

              <van-field label="雌性">
                <template #input>
                  <van-stepper v-model="state.form.returnFemaleNumber" integer :min="0" />
                </template>
              </van-field>

              <van-field v-model="state.form.notReturnReason" label="未返回动物情况说明"
                placeholder="请输入" type="textarea" rows="3" />

              <van-field label="门禁卡是否归还">
                <template #input>
                  <van-radio-group v-model="state.form.accessCardReturn" direction="horizontal">
                    <van-radio :name="1">是</van-radio>
                    <van-radio :name="0">否</van-radio>
                  </van-radio-group>
                </template>
              </van-field>
            </van-cell-group>
          </van-form>
        </div>
        <footer class="drawer-footer">
          <van-button block type="primary" @click="onSubmit">
            提交
          </van-button>
        </footer>
      </div>
    </van-popup>

    <van-popup v-model:show="showReturnDatePicker" position="bottom" :style="{ height: '80vh' }" round>
      <van-calendar v-model:show="showReturnDatePicker" @confirm="onReturnDateConfirm" />
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import to from 'await-to-js'
import { showNotify, showToast } from 'vant'
import type { FormInstance } from 'vant/es'

import { usePlatAnimalCageApplicationApi } from '/@/api/platform/animal'
import { TurnBackPayload, TakeawayList } from '/@/constants/pageConstants'
import { filterFields } from '/@/utils/func'
import dayjs from 'dayjs'

const emit = defineEmits(['refresh'])

const platAnimalCageApplicationApi = usePlatAnimalCageApplicationApi()

const expertDialogFormRef = ref<FormInstance>()
const showReturnDatePicker = ref(false)

const createDefaultForm = (): TurnBackPayload => ({
  takeawayId: 0,
  returnDate: '',
  returnTransport: '',
  accessCardReturn: 1,
  returnFemaleNumber: 0,
  returnMaleNumber: 0,
  notReturnReason: '',
  takeawayType: '10',
})

const state = reactive<{
  form: TurnBackPayload
  dialog: { isShowDialog: boolean; type: string; title: string; submitTxt: string }
}>({
  form: createDefaultForm(),
  dialog: {
    isShowDialog: false,
    type: '',
    title: '',
    submitTxt: '',
  },
})

const validateForm = () => {
    if (!state.form.returnDate) {
      showNotify({ type: 'warning', message: '请选择转回日期' })
      return false
    }

    if (!state.form.returnTransport) {
      showNotify({ type: 'warning', message: '请输入运输方式' })
      return false
    }

    if (!state.form.returnMaleNumber && !state.form.returnFemaleNumber) {
      showNotify({ type: 'warning', message: '请添加雄性或雌性数量' })
      return false
    }

    if (!state.form.notReturnReason) {
      showNotify({ type: 'warning', message: '请输入未返回动物情况说明' })
      return false
    }

  return true
}

const openDialog = async (sourceData: TakeawayList) => {
  state.dialog.title = '登记转回'
  state.form = {
    ...createDefaultForm(),
    takeawayId: sourceData.id,
  }

  state.dialog.isShowDialog = true
}

const closeDialog = () => {
  expertDialogFormRef.value?.resetValidation?.()
  state.form = createDefaultForm()
  state.dialog.isShowDialog = false
  showReturnDatePicker.value = false
}

const onCancel = () => {
  closeDialog()
}

const onSubmit = async () => {
  if (!validateForm()) return

  const post = platAnimalCageApplicationApi.createPlatAnimalTakeawayReback
  const payload = filterFields({
    ...state.form,
    returnDate: state.form.returnDate ? dayjs(state.form.returnDate).format('YYYY-MM-DD') : '',
    returnMaleNumber: Number(state.form.returnMaleNumber) || 0,
    returnFemaleNumber: Number(state.form.returnFemaleNumber) || 0,
  })

  const [err]: ToResponse = await to(post(payload))

  if (err) return
  showToast({ type: 'success', message: '操作成功' })
  closeDialog()
  emit('refresh')
}

const onReturnDateConfirm = (date: Date | Date[]) => {
  const selectedDate = Array.isArray(date) ? date[0] : date
  state.form.returnDate = dayjs(selectedDate).format('YYYY-MM-DD')
  showReturnDatePicker.value = false
}

defineExpose({
  openDialog,
})
</script>
<style lang="scss" scoped>
.drawer-dialog-container {
  .drawer-wrapper {
    display: flex;
    flex-direction: column;
    height: 100vh;
  }

  .drawer-header {
    padding: 16px;
    border-bottom: 1px solid #f0f0f0;

    h3 {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
      text-align: center;
    }
  }

  .drawer-body {
    flex: 1;
    overflow-y: auto;
    padding: 16px 12px 80px;
  }

  .drawer-footer {
    padding: 16px;
    border-top: 1px solid #f0f0f0;
    background-color: #fff;
  }
}
</style>
