<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.preservationTemp"
          label="保存温度"
          placeholder="如：-80°C"
          maxlength="90"
          :readonly="isDetail"
          :rules="isDetail ? [] : [{ required: true, message: '请输入保存温度' }]"
        />
        <van-field
          v-model="state.form.storageLocation"
          label="存放地点"
          placeholder="请输入存放地点"
          maxlength="255"
          :readonly="isDetail"
          :rules="isDetail ? [] : [{ required: true, message: '请输入存放地点' }]"
        />
        <van-field
          v-model="state.form.inboundDate"
          label="入库日期"
          placeholder="请选择入库日期"
          :readonly="isDetail"
          :rules="isDetail ? [] : [{ required: true, message: '请选择入库日期' }]"
          @click="isDetail || (showDatePicker = true)"
        />
        <van-field
          v-model="state.form.inboundPerson"
          label="入库人"
          placeholder="当前用户"
          readonly
        />
        <van-field
          v-model="state.form.quantity"
          label="入库量"
          placeholder="如：10包"
          maxlength="255"
          :readonly="isDetail"
          :rules="isDetail ? [] : [{ required: true, message: '请输入入库量' }]"
        />
      </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="isEditMode ? '保存修改' : '立即提交'" :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 isEditMode = computed(() => pageMode.value === 'edit')

const state = reactive({
  form: {
    id: 0,
    strainName: '',
    preservationTemp: '',
    storageLocation: '',
    inboundDate: formatDate(new Date(), 'YYYY-mm-dd'),
    inboundPersonId: 0,
    inboundPerson: '',
    quantity: '',
  }
})

const onConfirmDate = () => {
  showDatePicker.value = false
  state.form.inboundDate = `${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.inboundPersonId = u.id
  state.form.inboundPerson = u.nickName || ''
  state.form.inboundDate = formatDate(new Date(), 'YYYY-mm-dd')
}

const loadData = async (id: number) => {
  const [err, res]: any = await to(strainApi.getInboundById({ id }))
  if (err) return
  const d = res?.data
  if (d) {
    state.form = {
      id: d.id || 0,
      strainName: d.strainName || '',
      preservationTemp: d.preservationTemp || '',
      storageLocation: d.storageLocation || '',
      inboundDate: d.inboundDate ? d.inboundDate.slice(0, 10) : '',
      inboundPersonId: d.inboundPersonId || 0,
      inboundPerson: d.inboundPerson || '',
      quantity: d.quantity || '',
    }
  }
}

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 post = isEditMode.value ? strainApi.updateInbound : strainApi.createInbound
  const [err]: any = await to(post(params))
  submitting.value = false
  if (err) return

  showNotify({ type: 'success', message: isEditMode.value ? '修改成功' : '新增成功' })
  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>
