<script setup lang="ts">
import { showNotify, showSuccessToast } from 'vant';

import { useForm, useWatcher } from 'alova/client';
import { getSoakDataMethod, setSoakDataMethod } from '@/api/pda.api.ts';
import { fromSoakModel, type SoakModel } from '@/model/step.model.ts';
import { useStepStore } from '@/stores';

import type { ScanData } from '@/core/hook/useScan.ts';

const emits = defineEmits<{ back: [delta?: number] }>();

const storeStore = useStepStore();
const { dataset } = storeToRefs(storeStore);

const {
  loading: submitting,
  form: model,
  send, reset,
} = useForm(setSoakDataMethod, { immediate: false, initialForm: fromSoakModel() }).onSuccess(() => {
  showSuccessToast(`操作成功`);
  emits('back');
});

const { data, loading } = useWatcher(() => getSoakDataMethod(dataset.value?.id!), [dataset], {
  immediate: true,
  initialData: {},
  middleware: (_, next) => dataset.value?.id && next(),
})
  .onSuccess(({ data }) => {
    for (const [key, value] of Object.entries(data)) model.value[key as keyof SoakModel] = value;
  })
  .onError(({ error: message }) => {
    showDialog({ title: '温馨提示', message, closeOnClickOverlay: true }).then(() => emits('back'));
  });

function submit(picture: string[]) {
  let message = '';
  if (!+model.value.soakingWaterValue) {
    message = '请输入浸泡水量';
  } else if (!model.value.deviceCode) message = '请输入桶号';
  if (message) {
    showNotify({ message, type: 'warning' });
  } else {
    send(picture);
  }
}

defineExpose({
  scan(data: ScanData) {
    model.value.deviceCode = data?.code ?? '';
  },
  reset,
});
</script>

<template>
  <van-toast :show="loading" type="loading" forbid-click />

  <van-field class="suffix" v-model="model.soakingWaterValue" :readonly="submitting" type="digit" label="浸泡水量" placeholder="请输入浸泡水量">
    <template #extra>
      <div v-if="model.soakingWaterValue">ml</div>
    </template>
  </van-field>
  <van-field class="suffix" v-model="model.soakingTime" :readonly="submitting || !!data.soakingTime" type="digit" label="浸泡时间" placeholder="请输入浸泡时间">
    <template #extra>
      <div v-if="model.soakingTime">min</div>
    </template>
  </van-field>

  <slot name="scanner" title="扫描桶号" :disabled="submitting"></slot>
  <slot name="uploader" :disabled="submitting"></slot>

  <van-field v-model="model.soakingNote" :readonly="submitting" rows="2" autosize label="浸泡备注" type="textarea" placeholder="请输入备注内容" />

  <slot name="submit" title="浸泡节点上传" :submitting="submitting" :submit="submit"></slot>
</template>

<style scoped lang="scss">
.van-field.suffix {
  :deep(.van-field__value) {
    flex: none;
    //width: min-content;
    //min-width: 120px;
    max-width: 170px;

    input {
      text-align: center;
    }
  }
}
</style>
