<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.recordDate"
          label="日期"
          placeholder="请选择日期"
          :readonly="isDetail"
          :rules="isDetail ? [] : [{ required: true, message: '请选择日期' }]"
          @click="isDetail || (showDatePicker = true)"
        />
        <van-field
          v-model="state.form.operator"
          label="实验/移交人"
          placeholder="当前用户"
          readonly
        />
      </van-cell-group>

      <h4 class="mb8 mt8">灭菌物品</h4>
      <van-cell-group>
        <van-field label="选择灭菌物品">
          <template #input>
            <van-checkbox-group v-model="state.checkedItems" direction="horizontal">
              <van-checkbox style="margin-bottom:15px;" name="10" shape="square" :disabled="isDetail">实验固体废弃物</van-checkbox>
              <van-checkbox style="margin-bottom:15px;" name="20" shape="square" :disabled="isDetail">防护物品固体废弃物</van-checkbox>
              <van-checkbox style="margin-bottom:15px;" name="30" shape="square" :disabled="isDetail">需重复使用的器皿</van-checkbox>
              <van-checkbox name="40" shape="square" :disabled="isDetail">液体废弃物</van-checkbox>
            </van-checkbox-group>
          </template>
        </van-field>
        <van-field
          v-if="state.checkedItems.includes('40')"
          v-model="state.form.liquidWasteDesc"
          label="液体废弃物名称"
          placeholder="请填写液体废弃物名称"
          maxlength="255"
          :readonly="isDetail"
        />
      </van-cell-group>

      <h4 class="mb8 mt8">灭菌详情</h4>
      <van-cell-group>
        <van-field
          v-model="state.form.quantity"
          label="数量/袋"
          placeholder="如：5"
          maxlength="255"
          :readonly="isDetail"
          :rules="isDetail ? [] : [{ required: true, message: '请输入数量/袋' }]"
        />
        <van-field name="uploader" label="灭菌物理监测">
          <template #input>
            <template v-if="isDetail">
              <a v-if="state.form.monitorAttachment" :href="state.form.monitorAttachment" target="_blank" style="color:#3c78e3">{{ state.form.monitorAttachmentName || '查看附件' }}</a>
              <span v-else>-</span>
            </template>
            <van-uploader v-else v-model="state.fileList" :after-read="afterRead" preview-size="60" :preview-full-image="true" :max-count="1" />
          </template>
        </van-field>
        <van-field
          v-model="state.form.duration"
          label="灭菌时长/min"
          placeholder="如：30"
          maxlength="225"
          :readonly="isDetail"
          :rules="isDetail ? [] : [{ required: true, message: '请输入灭菌时长' }]"
        />
      </van-cell-group>

      <h4 class="mb8 mt8">仪器状态</h4>
      <van-cell-group>
        <van-field label="状态" :rules="isDetail ? [] : [{ required: true, message: '请选择仪器状态' }]">
          <template #input>
            <van-radio-group v-model="state.form.instrumentStatus" direction="horizontal">
              <van-radio name="10" :disabled="isDetail">正常</van-radio>
              <van-radio name="20" :disabled="isDetail">故障</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-field
          v-if="state.form.instrumentStatus === '20'"
          v-model="state.form.faultDesc"
          label="故障描述"
          placeholder="请描述故障情况"
          maxlength="512"
          type="textarea"
          rows="2"
          autosize
          :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('/sterilization')" />
        <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 { useSterilizationApi } from '/@/api/sterilization'
import { useUserInfo } from '/@/stores/userInfo'
import { formatDate } from '/@/utils/formatTime'
import { handleUpload } from '/@/utils/upload'
import { showNotify } from 'vant'

const router = useRouter()
const route = useRoute()
const sterilizationApi = useSterilizationApi()
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,
    recordDate: formatDate(new Date(), 'YYYY-mm-dd'),
    operatorId: 0,
    operator: '',
    sterilizationItems: '',
    liquidWasteDesc: '',
    quantity: '',
    monitorAttachment: '',
    monitorAttachmentName: '',
    duration: '',
    instrumentStatus: '10',
    faultDesc: '',
  },
  checkedItems: [] as string[],
  fileList: [] as any[],
})

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

const loadData = async (id: number) => {
  const [err, res]: any = await to(sterilizationApi.getById({ id }))
  if (err) return
  const d = res?.data
  if (d) {
    state.form = {
      id: d.id || 0,
      recordDate: d.recordDate ? d.recordDate.slice(0, 10) : '',
      operatorId: d.operatorId || 0,
      operator: d.operator || '',
      sterilizationItems: d.sterilizationItems || '',
      liquidWasteDesc: d.liquidWasteDesc || '',
      quantity: d.quantity || '',
      monitorAttachment: d.monitorAttachment || '',
      monitorAttachmentName: d.monitorAttachmentName || '',
      duration: d.duration || '',
      instrumentStatus: d.instrumentStatus || '10',
      faultDesc: d.faultDesc || '',
    }
    state.checkedItems = d.sterilizationItems ? d.sterilizationItems.split(',').filter(Boolean) : []
    if (d.monitorAttachment) {
      state.fileList = [{ name: d.monitorAttachmentName || d.monitorAttachment.split('/').pop() || '附件', url: d.monitorAttachment }]
    }
  }
}

const afterRead = async (file: any) => {
  file.status = 'uploading'
  const [err, res]: ToResponse = await to(handleUpload(file.file))
  if (err) {
    file.status = 'failed'
    return
  }
  file.status = 'success'
  file.url = res as string
  file.name = file.file.name
  state.form.monitorAttachment = res as string
  state.form.monitorAttachmentName = file.file.name
}

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

  if (state.checkedItems.length === 0) {
    showNotify({ type: 'warning', message: '请至少选择一项灭菌物品' })
    return
  }

  submitting.value = true
  state.form.sterilizationItems = state.checkedItems.join(',')
  const params = JSON.parse(JSON.stringify(state.form))
  const post = isEditMode.value ? sterilizationApi.update : sterilizationApi.create
  const [err]: any = await to(post(params))
  submitting.value = false
  if (err) return

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