<template>
  <el-drawer
    v-model="dialogVisible"
    :title="title"
    resizable
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :destroy-on-close="true"
    size="70%"
    :before-close="handleClosed"
  >
    <div class="attack-risk-form">
      <h1 class="form-title">变更事项确认表</h1>
      <!-- 基本信息 -->
      <el-row :gutter="40">
        <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" class="row">
          <text>长者姓名</text>
          <search-the-elderly
            ref="selectElderRef"
            :disabled="isDetail"
            @update_elder="elderUp"
            v-model="dataForm.elderName"
            :tId="dataForm.tenantId"
          />
        </el-col>
        <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" class="row">
          <text>档案号</text>
          <el-input v-if="!isDetail" v-model="dataForm.contractNumber" disabled />
          <el-text v-else disabled="">{{ dataForm.contractNumber }}</el-text>
        </el-col>
      </el-row>
      <el-row :gutter="40">
        <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" class="row">
          <text>入院日期</text>
          <el-input
            v-if="!isDetail"
            :model-value="
              dayjs(dataForm.checkInTime).format('YYYY-MM-DD') == 'Invalid Date'
                ? ''
                : dayjs(dataForm.checkInTime).format('YYYY-MM-DD')
            "
            disabled
          />
          <el-text v-else disabled="">{{
            dayjs(dataForm.checkInTime).format('YYYY-MM-DD')
          }}</el-text>
        </el-col>
        <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" class="row">
          <text>床位号</text>
          <el-input v-if="!isDetail" v-model="dataForm.bedName" disabled />
          <el-text v-else disabled="">{{ dataForm.bedName }}</el-text>
        </el-col>
      </el-row>

      <el-row :gutter="40">
        <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" class="row">
          <text>记录人</text>
          <el-input :disabled="isDetail" v-model="form.recorder" />
        </el-col>
        <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" class="row">
          <text>记录日期</text>
          <el-date-picker
            :disabled="isDetail"
            v-model="form.recordDate"
            type="date"
            style="width: 100%"
          />
        </el-col>
      </el-row>

      <!-- 内容区域 -->
      <div class="form-body">
        <ChangeConfirmationFormBody ref="bodyRef" v-model="changeForm" :is-text-mode="isDetail" />
      </div>
    </div>

    <template #footer>
      <el-button @click="handleClosed">关闭</el-button>
      <el-button
        style="margin-left: 22px; margin-right: 30px"
        v-loading="formLoading"
        type="primary"
        v-show="!isDetail"
        @click="submitForm"
        >确定</el-button
      >
    </template>
  </el-drawer>
</template>

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

import dayjs from 'dayjs'
import ChangeConfirmationFormBody from '../components/ChangeConfirmationFormBody.vue'

import {
  changeConfirmationForm_create,
  changeConfirmationForm_update,
  changeConfirmationForm_getById
} from '@/api/elderly/contracts'
const message = useMessage()
const { t } = useI18n()
const title = ref('')
const dialogVisible = ref(false)
const selectElderRef = ref()
const bodyRef = ref()
const isDetail = ref(false)
const formLoading = ref(false)
let dataForm = ref({
  id: undefined,
  elderName: '',
  elderId: '',
  bedName: '',
  checkInTime: '',
  contractNumber: '',
  tenantId: undefined
})

const changeForm = ref({})

const form = reactive({
  recorder: '',
  recordDate: ''
})

const elderUp = (e) => {
  dataForm.value.elderName = e.elderName
  dataForm.value.elderId = e.id
  dataForm.value.bedName = e.bedName || ''
  dataForm.value.checkInTime = e.checkInTime
  dataForm.value.contractNumber = e.contractNumber || e.fileNumber
  changeForm.value.partyBName = e.elderName
}

const open = async (tenantId, id?: any, detail: boolean = false) => {
  resetForm()
  dialogVisible.value = true
  dataForm.value.tenantId = tenantId
  isDetail.value = detail
  if (id) {
    title.value = detail ? '详情-变更事项确认表' : '编辑-变更事项确认表'
    dataForm.value.id = id
    await loadAttachmentData(id)
  } else {
    title.value = '新增-变更事项确认表'
  }
}

const loadAttachmentData = async (id: number) => {
  try {
    const res = await changeConfirmationForm_getById(id)
    if (res) {
      dataForm.value.elderName = res.elderName || ''
      dataForm.value.elderId = res.elderId || ''
      dataForm.value.bedName = res.bedName || ''
      dataForm.value.contractNumber = res.contractNumber || res.fileNumber || ''
      dataForm.value.checkInTime = res.checkInTime || ''
      form.recorder = res.recorder || ''
      form.recordDate = res.recordDate ? dayjs(res.recordDate).toDate() : ''
      if (res.content) {
        try {
          const contentData = JSON.parse(res.content)
          changeForm.value = { ...changeForm.value, ...contentData }
        } catch (e) {
          console.error('解析变更事项确认表内容失败', e)
        }
      }
      await selectElderRef.value?.upData(res.elderName, res.elderId)
    }
  } catch (error) {
    message.error('加载数据失败')
  }
}

defineExpose({ open })

const emit = defineEmits(['success'])
const submitForm = async () => {
  if (formLoading.value) {
    return
  }
  formLoading.value = true
  try {
    const bodyForm = bodyRef.value?.form || changeForm.value
    const content = JSON.stringify({ ...bodyForm })
    const tempParams = {
      id: dataForm.value.id,
      elderId: dataForm.value.elderId,
      elderName: dataForm.value.elderName,
      bedName: dataForm.value.bedName,
      recorder: form.recorder,
      recordDate: form.recordDate ? dayjs(form.recordDate).format('YYYY-MM-DD') : '',
      content: content,
      signYi: bodyForm.partyBSign || '',
      signBing: bodyForm.partyCSign || '',
      signDate: bodyForm.signDate || '',
      tenantId: dataForm.value.tenantId
    }

    let res
    if (dataForm.value.id) {
      res = await changeConfirmationForm_update(tempParams)
    } else {
      res = await changeConfirmationForm_create(tempParams)
    }
    if (res) {
      message.success(dataForm.value.id ? t('common.updateSuccess') : t('common.createSuccess'))
      dialogVisible.value = false
      emit('success')
    }
  } finally {
    setTimeout(() => {
      formLoading.value = false
    }, 500)
  }
}

const resetForm = () => {
  dataForm.value = {
    id: undefined,
    elderName: '',
    elderId: '',
    bedName: '',
    checkInTime: '',
    contractNumber: '',
    tenantId: undefined
  }
  form.recorder = ''
  form.recordDate = ''
  changeForm.value = {}
}

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

<style scoped lang="scss">
.form-title {
  text-align: center;
  font-size: 20px;
  width: 100%;
  margin-bottom: 20px;
}

.attack-risk-form {
  max-width: 1200px;
  margin: 0 auto;
  background: #fff;

  .form-body {
    border: 1px solid #333;
    padding: 15px;
  }
}
.row {
  margin-bottom: 12px;
  display: flex;
  flex-direction: row;
  align-items: center;
  text {
    text-align: right;
    margin-right: 4px;
    width: 82px;
  }
}
</style>
