<template>
  <Dialog
    @close="dialogVisible = false"
    style="min-width: 46vw; max-width: 100vw"
    v-model="dialogVisible"
    title="退住转离住"
    class="elderly-info-bak"
    noPaddingEL="elderly-info-bak"
  >
    <el-form ref="formRef" :model="dataForm" :rules="dataRule" :label-width="labelWidth">
      <div class="info-wrap">
        <el-row>
          <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
            <el-form-item label="长者姓名:" prop="elderName">
              <el-text>{{ dataForm.elderName || '' }}</el-text>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
            <el-form-item label="床位号:" prop="bedName">
              <el-text>{{ dataForm.bedName || '' }}</el-text>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
            <el-form-item prop="retreatDate" label="退住日期" label-suffix="*">
              <template #label>
                <div class="flex">
                  退住日期
                  <el-icon>
                    <el-tooltip
                      class="item"
                      effect="dark"
                      content="该日期后不再生成护理计划"
                      placement="top-start"
                    >
                      <InfoFilled />
                    </el-tooltip>
                  </el-icon>
                </div>
              </template>
              <TgDatePicker
                v-model="dataForm.retreatDate"
                type="date"
                placeholder="请选择日期"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
            <el-form-item label="费用截止日期" prop="costDeadline" label-suffix="*">
              <template #label>
                <div class="flex">
                  费用截止日期
                  <el-icon>
                    <el-tooltip
                      class="item"
                      effect="dark"
                      content="请选择退住当天或前一天"
                      placement="top-start"
                    >
                      <InfoFilled />
                    </el-tooltip>
                  </el-icon>
                </div>
              </template>
              <TgDatePicker
                v-model="dataForm.costDeadline"
                type="date"
                placeholder="请选择日期"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="退住原因" prop="retreatReason">
              <TgSelect
                v-model="dataForm.retreatReason"
                placeholder="请选择"
                :list="getDictOptions(DICT_TYPE.BACK_CAUSE_ARR)"
              >
                <el-option
                  v-for="(item, index) in getStrDictOptions(DICT_TYPE.BACK_CAUSE_ARR)"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </TgSelect>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="退住描述" prop="retreatDescribe">
              <TgInput
                v-model="dataForm.retreatDescribe"
                type="textarea"
                placeholder="请输入退住描述"
                :rows="3"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>

    <template #footer>
      <el-button @click="handleClosed">关闭</el-button>
      <el-button v-loading="formLoading" type="primary" @click="submitForm">确定</el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import { computed, reactive, ref } from 'vue'

import { useMediaQuery } from '@vueuse/core'
import { retreatSimpleCreate } from '@/api/elderly/elder/outwardRegustration'
import { DICT_TYPE, getDictOptions, getStrDictOptions } from '@/utils/dict'
import { FormRules } from 'element-plus'

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const dialogVisible = ref(false) // 弹窗
const formRef = ref() // 表单 Ref
const formLoading = ref(false) // 表单的加载中：提交的按钮禁用
const dataForm = reactive({
  elderName: '',
  bedName: '',
  retreatDate: '',
  costDeadline: '',
  retreatReason: '',
  retreatDescribe: '',
  elderlyId: undefined,
  tempOutId: undefined
})

// 计算窗口大小
const currentWidth = useMediaQuery('(max-width: 800px)')
// 计算文字大小
const labelWidth = computed(() => {
  return currentWidth.value ? '100px' : '130px'
})

// 表单规则
const dataRule = reactive<FormRules>({
  retreatDate: [{ required: true, message: '退住日期不能为空', trigger: 'change' }],
  costDeadline: [{ required: true, message: '费用截止日期不能为空', trigger: 'change' }],
  retreatReason: [{ required: true, message: '退住原因不能为空', trigger: 'change' }]
})

/** 打开弹窗 */
const open = (row) => {
  dataForm.elderName = row.elderName
  dataForm.bedName = row.bedName
  dataForm.retreatDate = row.retreatDate
  dataForm.costDeadline = row.costDeadline
  dataForm.retreatReason = row.retreatReason
  dataForm.retreatDescribe = row.retreatDescribe
  dataForm.elderlyId = row.elderId
  dataForm.tempOutId = row.id
  dialogVisible.value = true
  console.log('dataForm', dataForm)
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  if (formLoading.value) {
    return
  }
  formLoading.value = true
  try {
    // 校验表单
    if (!formRef.value) return
    const valid = await formRef.value.validate()
    if (!valid) return

    // 退住原因转为汉字后提交
    const reasonLabel = getStrDictOptions(DICT_TYPE.BACK_CAUSE_ARR).find(
      (item) => item.value === dataForm.retreatReason
    )?.label

    // 发起退住申请
    const res = await retreatSimpleCreate({
      retreatDate: dataForm.retreatDate,
      costDeadline: dataForm.costDeadline,
      elderlyId: dataForm.elderlyId,
      retreatReason: reasonLabel || dataForm.retreatReason,
      retreatDescribe: dataForm.retreatDescribe,
      tempOutId: dataForm.tempOutId
    })
    if (res) {
      message.success(t('common.updateSuccess'))
      handleClosed()
      // 发送操作成功的事件
      emit('success')
    }
  } catch {} finally {
    setTimeout(() => {
      formLoading.value = false
    }, 500)
  }
}

/** 重置表单 */
const resetForm = () => {
  dataForm.elderName = ''
  dataForm.bedName = ''
  dataForm.retreatDate = ''
  dataForm.costDeadline = ''
  dataForm.retreatReason = ''
  dataForm.retreatDescribe = ''
  dataForm.elderlyId = undefined
  dataForm.tempOutId = undefined
  formRef.value?.resetFields()
}

// 关闭表单
const handleClosed = () => {
  dialogVisible.value = false
  resetForm()
}
</script>

<style lang="scss" scoped>
.elderly-info-bak {
  .el-form {
    padding: 15px !important;
  }
  .info-wrap {
    margin: 15px;
  }
  @media (max-width: 1200) {
    :deep(.el-form-item--default .el-form-item__label) {
      line-height: 0 !important;
    }
  }
}
</style>
