<template>
  <window-size>
    <van-form @submit="onSubmit" style="margin-top: 12px">
      <van-cell-group inset>
        <van-field
            v-model="request.phoneNo"
            name="phoneNo"
            label="联系电话"
            placeholder="请填写手机号"
            required
            :rules="[{required: true, message: '请填写您的手机号'}]"
        />
        <van-field
            v-model="request.drugName"
            name="drugName"
            label="药品名称"
            placeholder="请填写药品名称"
            required
            :rules="[{required: true, message: '请填写药品名称'}]"
        />
        <van-field
            v-model="request.drugQuantity"
            name="drugQuantity"
            label="药品数量"
            placeholder="请填写药品数量"
            type="digit"
            required
            :rules="[{validator, message: '请填写药品数量'}]"
        />
        <van-field
            v-model="request.drugFactory"
            name="drugFactory"
            label="生产厂家"
            placeholder="请填写药品生产厂家"
            required
            :rules="[{required: true, message: '请填写药品生产厂家'}]"
        />
        <van-field
            v-model="request.drugSpecification"
            name="drugSpecification"
            label="药品规格"
            placeholder="请填写药品规格"
        />
        <van-field name="uploader" label="药品照片">
          <template #input>
            <van-uploader v-model="files" :max-count="1"/>
          </template>
        </van-field>
        <van-field
            v-model="request.expContent"
            name="expContent"
            label="补充说明"
            type="textarea"
            :maxlength="128"
            show-word-limit
            placeholder="补充性说明，非必填"
        />
      </van-cell-group>
      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>
  </window-size>
</template>

<script setup>
import router from "@/router";
import {reactive, ref} from "vue";
import {resize} from "@/utils/image";
import {importDrugPurchase} from "@/api/import-drug-purchase";
import {showDialog} from "vant";

const phoneNo = router.currentRoute.value.params.phoneNo

const files = ref([])
const request = reactive({
  phoneNo: phoneNo,
  drugName: null,
  drugQuantity: null,
  drugFactory: null,
  drugSpecification: null,
  expContent: null,
  drugImg: null
})

function validator(val) {
  return val > 0
}

function executeSubmit(img) {
  request.drugImg = img
  importDrugPurchase(request).then((res) => {
    showDialog({
      title: '提交成功',
      message: res,
      showCancelButton: false,
      showConfirmButton: true,
    }).then(() => {
      router.push('/hospitalService')
    })
  })
}

function onSubmit() {
  if (files.value.length > 0) {
    resize(files.value[0].content, executeSubmit)
  } else {
    executeSubmit(null)
  }
}

</script>