<template>
  <div class="app-container">
    <van-form ref="formRef" @submit="onSubmit" required="auto">
      <h4 class="mb8 mt8">领用信息</h4>
      <van-cell-group>
        <van-field
          v-model="state.form.strainName"
          label="菌毒种名称"
          placeholder="请输入菌毒种名称"
          maxlength="255"
          :readonly="isDetail"
          :rules="isDetail ? [] : [{ required: true, message: '请输入菌毒种名称' }]"
        />
        <van-field
          v-model="state.form.usageDate"
          label="领用日期"
          placeholder="请选择领用日期"
          :readonly="isDetail"
          :rules="isDetail ? [] : [{ required: true, message: '请选择领用日期' }]"
          @click="isDetail || (showDatePicker = true)"
        />
        <van-field
          v-model="state.form.usagePerson"
          label="领用人"
          placeholder="当前用户"
          readonly
        />
        <van-field
          v-model="state.form.usageQuantity"
          label="领用数量"
          placeholder="如：6包"
          maxlength="255"
          :readonly="isDetail"
          :rules="isDetail ? [] : [{ required: true, message: '请输入领用数量' }]"
        />
        <van-field
          v-model="state.form.purpose"
          label="用途"
          placeholder="请输入用途"
          type="textarea"
          rows="2"
          autosize
          maxlength="2048"
          :readonly="isDetail"
        />
        <van-field
          v-model="state.form.remainingQuantity"
          label="剩余量"
          placeholder="如：46包"
          maxlength="255"
          :readonly="isDetail"
        />
      </van-cell-group>

      <van-action-bar placeholder>
        <van-action-bar-icon icon="wap-home-o" text="首页" @click="router.push('/home')" />
        <van-action-bar-icon icon="revoke" text="返回" @click="router.push('/strain')" />
        <van-action-bar-button v-if="!isDetail" type="primary" text="立即提交" :loading="submitting" native-type="submit" />
      </van-action-bar>
    </van-form>

    <van-popup v-model:show="showDatePicker" position="bottom">
      <van-date-picker v-model="currentDate" title="选择日期" @confirm="onConfirmDate" @cancel="showDatePicker = false" />
    </van-popup>
  </div>
</template>

<script lang="ts" setup>
import to from 'await-to-js'
import { computed, onMounted, reactive, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useStrainApi } from '/@/api/strain'
import { useUserInfo } from '/@/stores/userInfo'
import { formatDate } from '/@/utils/formatTime'
import { showNotify } from 'vant'

const router = useRouter()
const route = useRoute()
const strainApi = useStrainApi()
const userStore = useUserInfo()

const formRef = ref()
const showDatePicker = ref(false)
const currentDate = ref([new Date().getFullYear(), new Date().getMonth() + 1, new Date().getDate()])
const submitting = ref(false)

const pageMode = computed(() => (route.query.mode as string) || 'add')
const isDetail = computed(() => pageMode.value === 'detail')

const state = reactive({
  form: {
    id: 0,
    strainName: '',
    usageDate: formatDate(new Date(), 'YYYY-mm-dd'),
    usagePersonId: 0,
    usagePerson: '',
    usageQuantity: '',
    purpose: '',
    remainingQuantity: '',
  }
})

const onConfirmDate = () => {
  showDatePicker.value = false
  state.form.usageDate = `${currentDate.value[0]}-${String(currentDate.value[1]).padStart(2, '0')}-${String(currentDate.value[2]).padStart(2, '0')}`
}

const initForm = () => {
  const u = userStore.userInfos
  state.form.usagePersonId = u.id
  state.form.usagePerson = u.nickName || ''
  state.form.usageDate = formatDate(new Date(), 'YYYY-mm-dd')
}

const loadData = async (id: number) => {
  const [err, res]: any = await to(strainApi.getUsageById({ id }))
  if (err) return
  const d = res?.data
  if (d) {
    state.form = {
      id: d.id || 0,
      strainName: d.strainName || '',
      usageDate: d.usageDate || '',
      usagePersonId: d.usagePersonId || 0,
      usagePerson: d.usagePerson || '',
      usageQuantity: d.usageQuantity || '',
      purpose: d.purpose || '',
      remainingQuantity: d.remainingQuantity || '',
    }
  }
}

const onSubmit = async () => {
  const [errValid] = await to(formRef.value.validate())
  if (errValid) return

  submitting.value = true
  const params = JSON.parse(JSON.stringify(state.form))
  const [err]: any = await to(strainApi.createUsage(params))
  submitting.value = false
  if (err) return

  showNotify({ type: 'success', message: '新增成功' })
  setTimeout(() => {
    router.push('/strain')
  }, 1000)
}

onMounted(async () => {
  const id = route.query.id
  if (id) {
    await loadData(Number(id))
  } else {
    initForm()
  }
})
</script>

<style lang="scss" scoped>
.app-container {
  h4 {
    margin: 10px 0;
    height: 20px;
    line-height: 20px;
    padding-left: 16px;
    &::before {
      display: inline-block;
      content: '';
      background-color: #3c78e3;
      width: 4px;
      height: 20px;
      margin-right: 4px;
      vertical-align: top;
    }
  }
}
</style>
